C++实现将一幅图片的像素转化到txt文档保存

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
 
using namespace std;
using namespace Gdiplus;
 
int main() {
    GdiplusStartupInput gdiplusstartupinput;
    ULONG_PTR gdiplustoken;
    GdiplusStartup(&gdiplustoken, &gdiplusstartupinput, NULL);
 
    wstring infilename(L"1.jpg");
    string outfilename("color.txt");
 
    Bitmap* bmp = new Bitmap(infilename.c_str());
    UINT height = bmp->GetHeight();
    UINT width  = bmp->GetWidth();
    cout << "width " << width << ", height " << height << endl;
 
    Color color;
    ofstream fout(outfilename.c_str());
 
    for (UINT y = 0; y < height; y++)
    for (UINT x = 0; x < width ; x++) {
            bmp->GetPixel(x, y, &color);
            fout << x << "," << y << ";"
                 << (int)color.GetRed()   << ","
                 << (int)color.GetGreen() << ","
                 << (int)color.GetBlue()  << endl;
    }
 
    fout.close();
 
    delete bmp;
    GdiplusShutdown(gdiplustoken);
    return 0;
}

其中,如果是灰度图,三个通道的值是一样的,就任意保存一个通道的值就OK,保存那些数据以及格式可以通过修改fout后面的格式和内容。

参考文献:https://bbs.csdn.net/topics/391842084

猜你喜欢

转载自blog.csdn.net/zbr794866300/article/details/102980627