// BMP_24-16.cpp : 定义控制台应用程序的入口点。
//
///24位bmp图像转16位bmp图像
#include "stdafx.h"
#include "iostream"
#include "fstream"
using namespace std;
#pragma pack(2)
struct bmp_fileheader //文件头,长度为14Byte固定
{
unsigned short bfType;
unsigned long bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned long bfOffBits;
};
struct bmp_infoheader //文件信息头,长度为40Byte固定
{
unsigned long biSize;
unsigned long biWidth;
unsigned long biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned long biCompression;
unsigned long biSizeImage;
unsigned long biXPelsPerMeter;
unsigned long biYPelsPerMeter;
unsigned long biClrUsed;
unsigned long biClrImportant;
};
fstream input_file;
fstream output_file;
struct bmp_fileheader bfh;
struct bmp_infoheader bih;
unsigned char *src_buff;
unsigned char *dst_buff;
void read_bmp_fileheader()
{
input_file.read((char*)&bfh, sizeof(struct bmp_fileheader));将bfh强制转换位char,第二个参数为结构的长度
}
void read_bmp_infoheader()
{
input_file.read((char*)&bih, sizeof(struct bmp_infoheader));
}
void read_bmp_data()
{
src_buff = new unsigned char[bih.biHeight*bih.biWidth * 3];
input_file.read((char*)src_buff, sizeof(unsigned char)*bih.biHeight*bih.biWidth * 3);
}
void bmp_translate()
{
dst_buff = new unsigned char[bih.biHeight*bih.biWidth * 2];
int temp[3];
unsigned long j = 0;
for (unsigned long i = 0; i < bih.biHeight *bih.biWidth * 3;i+=3)
{
temp[0] = src_buff[i] * 32 / 256;
temp[1] = src_buff[i+1] * 32 / 256;
temp[2] = src_buff[i+2] * 32 / 256;
dst_buff[j] = (temp[0] << 3) + ((temp[1] >> 2) << 3);
dst_buff[j + 1] = (temp[1] << 6) + (temp[2] << 1);
j += 2;
}
}
void write_bmp_fileheader()
{
bfh.bfSize = bfh.bfOffBits + bih.biHeight*bih.biWidth * 2;
output_file.write((char*)&bfh, sizeof(struct bmp_fileheader));
}
void write_bmp_infoheader()
{
bih.biBitCount = 16;
output_file.write((char*)&bih, sizeof(struct bmp_infoheader));
}
void write_bmp_data()
{
output_file.write((char*)dst_buff, sizeof(unsigned char)*bih.biWidth*bih.biHeight * 2);
}
int _tmain(int argc, _TCHAR* argv[])
{
input_file.open("E:\\FFOutput\\pic1.bmp", ios::binary | ios::in);
output_file.open("E:\\FFOutput\\pic116.bmp", ios::binary | ios::out);
read_bmp_fileheader();
read_bmp_infoheader();
read_bmp_data();
bmp_translate();
write_bmp_fileheader();
write_bmp_infoheader();
write_bmp_data();
cout << "Well Done!" << endl;
cin.get();
delete[] src_buff;
delete[] dst_buff;
return 0;
}
这几天尝试了一下bmp图片的格式转换,参考了一下网上的例子,自己尝试着将24位真彩色的bmp图像转换为16位,其中16位选择rgb555分配的方式
在bmp图像中只有单色,16色,256色(灰度图)有调色板。
在处理的过程中,先将原图中的rgb分量读取出来,然后根据比例计算出5位的数据。
将rgb555的数据拼凑成2Byte的数据。最后一位置零。
处理过程中用C++中的<<和>>移位运算实现。