// ReversePNG.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<FreeImage.h>
#include<vector>
#pragma comment(lib,"FreeImaged.lib")
using namespace std;
struct byte4
{
BYTE r;
BYTE g;
BYTE b;
BYTE a;
};
int main()
{
// 初始化
FreeImage_Initialise(TRUE);
// 文件名
const char* imageFile = "e.jpg";
const char* saveFile = "ha.jpg";
// 图片格式
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
// 获取图片格式
/* 此处需要特别注意,即使后缀名是.png并不代表图片格式就真是PNG格式,这里先通过FreeImage_GetFileType函数获取图片格式,
然后再进行加载,否则,也许会出现加载失败的情况。
*/
fif = FreeImage_GetFileType(imageFile);
if (fif == FIF_UNKNOWN)
fif = FreeImage_GetFIFFromFilename(imageFile);
FIBITMAP *bitmap1 = NULL;
FIBITMAP *bitmap2 = NULL;
if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
bitmap1 = FreeImage_Load(fif, imageFile, PNG_DEFAULT);
}
if (!bitmap1) {
fprintf(stderr, "Fail to Load Image!\n");
exit(-1);
}
else {
FreeImage_Save(fif, bitmap1, saveFile, PNG_DEFAULT);
bitmap2 = FreeImage_Load(fif, saveFile, PNG_DEFAULT);
if (!bitmap2) {
fprintf(stderr, "Fail to Load saved Image!\n");
exit(-1);
}
}
// 获取影像的宽高,都以像素为单位
int width = FreeImage_GetWidth(bitmap1);
int height = FreeImage_GetHeight(bitmap1);
// 获取总共的像素数目
int pixel_num = width * height;
// 获取保存每个像素的字节数 这里为3,分别为RGB
unsigned int byte_per_pixel = FreeImage_GetLine(bitmap1) / width;
printf("Width:%d\t Height:%d\t 像素总数:%d\t 每像素字节数:%d\n", width, height, pixel_num, byte_per_pixel);
// 获取保存图片的字节数组
unsigned char *bits1 = FreeImage_GetBits(bitmap1);
unsigned char *bits2 = FreeImage_GetBits(bitmap2);
// 获取每个像素对应的RGB
unsigned char *reds = new unsigned char[pixel_num];
unsigned char *greens = new unsigned char[pixel_num];
unsigned char *blues = new unsigned char[pixel_num];
unsigned char **rgb = new unsigned char*[pixel_num];
for(int i = 0; i < pixel_num; i++)
rgb[i] = new unsigned char[3];
int cur = 0;
int len = sizeof(bits1);
for (int x = 0; x < pixel_num; ++x) {
// 这里对应于上述的每个像素的字节数:3
rgb[x][0] = bits1[cur++];
rgb[x][1] = bits1[cur++];
rgb[x][2] = bits1[cur++];
}
// 将图片一的像素信息反转保存到saveFile
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int x = i * height + width - j - 1;
cur = i * height + j;
cout << cur << " " << x << endl;
bits2[cur++] = rgb[x][0];
bits2[cur++] = rgb[x][1];
bits2[cur++] = rgb[x][2];
}
cout << endl << endl;
}
// 保存更新后的图片
FreeImage_Save(fif, bitmap2, saveFile, PNG_DEFAULT);
// 从内存中删除载入图片,防止内存泄漏
FreeImage_Unload(bitmap1);
FreeImage_Unload(bitmap2);
// 撤销初始化
FreeImage_DeInitialise();
return 0;
}