haha
unknown
plain_text
4 years ago
2.9 kB
8
Indexable
#include <iostream>
#include <fstream>
using namespace std;
struct bmpheader {
char Signature[2];
int FileSize;
int Reserved;
int DataOffSet;
};
struct DIB {
int dibSize;
int width;
int height;
short planes;
short bpp;
int compression;
int imageSize;
int XpixelsperM;
int YpixelsperM;
int colorsUsed;
int importantColor;
};
struct bmpImage {
bmpheader header;
DIB dib;
char* pDIBReserved;
char* pImageData;
};
int readBMP(const char* filename, bmpImage& bmp)
{
ifstream fin(filename, ios::binary);
if (!fin)
return 0;
fin.seekg(0, ios::beg);
fin.read((char*)&bmp.header, 14);
fin.read((char*)&bmp.dib, 40);
if (bmp.dib.dibSize > 40) {
int d = bmp.dib.dibSize - 40;
bmp.pDIBReserved = new char[d];
fin.read(bmp.pDIBReserved, d);
}
bmp.pImageData = new char[bmp.dib.imageSize];
fin.read(bmp.pImageData, bmp.dib.imageSize);
return 1;
}
int writeBMP(const char* filename, bmpImage bmp)
{
ofstream fout(filename, ios::out | ios::binary);
if (!fout)
return 0;
fout.write((char*)&bmp.header, 14);
fout.write((char*)&bmp.dib, 40);
if (bmp.dib.dibSize > 40) {
int d = bmp.dib.dibSize - 40;
bmp.pDIBReserved = new char[d];
fout.write(bmp.pDIBReserved, d);
}
bmp.pImageData = new char[bmp.dib.imageSize];
fout.write(bmp.pImageData, bmp.dib.imageSize);
return 1;
}
int ConvertTo8bit(bmpImage srcBMP, bmpImage& dstBMP)
{
if (srcBMP.dib.bpp != 24 && srcBMP.dib.bpp != 32 && srcBMP.pImageData == NULL)
return 0;
dstBMP.header = srcBMP.header;
dstBMP.dib = srcBMP.dib;
dstBMP.dib.bpp = 8;
int width = srcBMP.dib.width;
int height = srcBMP.dib.height;
int padding = 0;
dstBMP.dib.imageSize = width * height * (dstBMP.dib.bpp / 8) + height * padding;
return 1;
dstBMP.pImageData = new char[dstBMP.dib.imageSize];
char* pSrcRow = srcBMP.pImageData;
char* pDstRow = dstBMP.pImageData;
int nSrcByteInPix = srcBMP.dib.bpp / 8;
int nDstByteInPix = dstBMP.dib.bpp / 8;
int nSrcByteInRow = (width * nSrcByteInPix) + padding;
int nDstByteInRow = (width * nDstByteInPix) + padding;
for (int y = 0; y < height; y++) {
char* pSrcPix = pSrcRow;
char* pDstPix = pDstRow;
for (int x = 0; x < width; x++) {
char A, B, G, R;
if (srcBMP.dib.bpp == 24) {
B = pSrcPix[0];
G = pSrcPix[1];
R = pSrcPix[2];
}
if (srcBMP.dib.bpp == 32) {
A = pSrcPix[0];
B = pSrcPix[1];
G = pSrcPix[2];
R = pSrcPix[3];
}
char avg = (char)((B + G + R) / 3);
pDstPix[0] = avg;
pSrcPix += nSrcByteInPix;
pDstPix += nDstByteInPix;
}
pSrcRow += nSrcByteInRow;
pDstRow += nDstByteInRow;
}
return 1;
}
int main()
{
bmpImage srcImage = { NULL }, dstImage = { NULL };
readBMP("input.bmp", srcImage);
ConvertTo8bit(srcImage, dstImage);
writeBMP("output.bmp", dstImage);
return 0;
}Editor is loading...