首页 > 代码库 > 文本转换位图

文本转换位图

前言

想不想看看你写的代码长成哪副挫样,

或者看看你写的日记长成哪副挫样.

大家跟随我, 一起来强势围观自己代码长得有多丑.

源码

 1 #include <iostream> 2 #include <vector> 3 #include <fstream> 4 #include <string> 5 #include <cmath> 6 #include <Windows.h> 7  8 using namespace std; 9 10 string getFileData(ifstream &ifile);11 size_t getFileLength(ifstream &ifile);12 bool saveToFile(const string &fname, const string &data);13 SIZE getSizeByLength(size_t len);14 15 int main(int num, char **params)16 {17     if (num == 3)18     {19         ifstream ifile(params[1]);20         auto &&data =http://www.mamicode.com/ getFileData(ifile);21         saveToFile(params[2], data);22         cout << "转成成功!" << endl;23     }24     else25     {26         cout << "输入参数: 文本文件 位图文件" << endl;27     }28     return 0;29 }30 31 string getFileData(ifstream &ifile)32 {33     auto length = getFileLength(ifile);34     auto data = http://www.mamicode.com/string(length, \0);35     ifile.read(&data[0], length);36     return data;37 }38 39 size_t getFileLength(ifstream &ifile)40 {41     ifile.seekg(0, ios::end);42     size_t len = (size_t)ifile.tellg();43     ifile.seekg(0, ios::beg);44     return len;45 }46 47 bool saveToFile(const string &fname, const string &data)48 {49     auto size = getSizeByLength(data.size() / 3);50     auto lineWidth = (size.cx * 3 + 3) / 4 * 4;51 52     BITMAPFILEHEADER bfh;53     bfh.bfSize = 54 + lineWidth * 5;54     bfh.bfType = 0x4D42;55     bfh.bfOffBits = 54;56     bfh.bfReserved1 = 0;57     bfh.bfReserved2 = 0;58 59     BITMAPINFOHEADER bih;60     bih.biSize = sizeof(BITMAPINFOHEADER);61     bih.biPlanes = 1;62     bih.biWidth = size.cx;63     bih.biHeight = size.cy;64     bih.biBitCount = 24;65     bih.biClrUsed = 0;66     bih.biClrImportant = 0;67     bih.biXPelsPerMeter = 3780;68     bih.biYPelsPerMeter = 3780;69     bih.biCompression = BI_RGB;70     bih.biSizeImage = lineWidth * bih.biHeight;71 72     ofstream ofile(fname);73     ofile.write( (const char *)&bfh, sizeof(BITMAPFILEHEADER) );74     ofile.write( (const char *)&bih, sizeof(BITMAPINFOHEADER) );75     ofile.write( (const char *)&data[0], bih.biSizeImage );76     ofile.close();77 78     return true;79 }80 81 SIZE getSizeByLength(size_t len)82 {83     static int widths[] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};84     auto index = 0;85     while (86         index < sizeof(widths) / sizeof(int) && 87         widths[index] * widths[index] < (int)len )88     {89         ++index;90     }91     int width = widths[index];92     int height = (int)(len / width + 0.9f);93 94     SIZE size = { width, height };95     return size;96 }

这个思路很简单.

就是读出二进制数据, 每个字节表示RGB其中一个值, 由于是24位位图, 因此3个字节表示一个像素颜色.
然后填充位图, 生成问题.

 

注意! 由于3个字节表示一个像素, 最小生成位图大小是2X2, 因此长度必须有2 * 3 * 2 * 3.