- BMP->RGB
#include <iostream>
#include <windows.h>
#include <stdlib.h>
using namespace std;
int main()
{
FILE *fpBmp;
BITMAPFILEHEADER bmpHeader;//包含文件类型、大小和布局的信息
BITMAPINFOHEADER bmpInfHeader;//包含位图的尺寸和颜色格式
const char *bmpname = "F://share//1.bmp";
const char *txtname = "F://share//1.txt";
if((fpBmp = fopen(bmpname,"rb"))==NULL)//fopen( "D://test.bmp","rb")
{
cout<<"the bmp file can not open!"<<endl;
exit(1);
}
//read the BITMAPFILEHEADER
fread(&bmpHeader,sizeof(BITMAPFILEHEADER),1,fpBmp);
//read the BITMAPINFOHEADER
fread(&bmpInfHeader,sizeof(BITMAPINFOHEADER),1,fpBmp);
// read bmp data
unsigned char *bmpData = new unsigned char[bmpInfHeader.biHeight*bmpInfHeader.biWidth*3];
//unsigned char *bmpData = new unsigned char[bmpInfHeader.biHeight*bmpInfHeader.biWidth];//黑白图像
fseek(fpBmp,bmpHeader.bfOffBits,SEEK_SET);
fread(bmpData,1,bmpInfHeader.biHeight*bmpInfHeader.biWidth*3,fpBmp);
//fread(bmpData,1,bmpInfHeader.biHeight*bmpInfHeader.biWidth,fpBmp);//黑白图像
FILE *temp;
if((temp = fopen(txtname,"wb"))==NULL)//写TXT文件
{
cout<<"the file can not be built!"<<endl;
exit(1);
}
for(int i = 0;i<bmpInfHeader.biHeight;i++)
{
for(int j = 0;j<bmpInfHeader.biWidth;j++)
{
fprintf(temp,"(" );
fprintf(temp,"%d,",bmpData[i*bmpInfHeader.biWidth*3 + j*3]);
fprintf(temp,"%d,",bmpData[i*bmpInfHeader.biWidth*3 + j*3+1]);
fprintf(temp,"%d",bmpData[i*bmpInfHeader.biWidth*3 + j*3+2]);
fprintf(temp,")\n" );
//fprintf(temp,"%d ",bmpData[i*bmpInfHeader.biWidth + j]);//黑白图像
}
}
fclose(fpBmp);
fclose(temp);
return 0;
}
- RGB->BMP
from PIL import Image
x = 300 #x坐标 通过对txt里的行数进行整数分
y = 300 #y坐标 x * y = 行数
im = Image.new("RGB", (x, y))
file = open('1.txt')
for i in range(0, x):
for j in range(0, y):
line = file.readline() #获取一行的rgb值
line = line[:-2]
line = line[1:]
print (line)
rgb = line.split(",") #分离rgb,文本中逗号后面有空格
im.putpixel((i, j), (int(rgb[0]), int(rgb[1]), int(rgb[2])))
im.save('1.bmp')
- 举个栗子
还原前1.bmp(像素300×300)
生成的1.txt(90000行像素点)
(0,0,0)
(0,0,0)
(0,0,0)
...
...
...
(43,43,43)
(43,43,43)
(0,0,0)
(0,0,0)
(0,0,0)
(0,0,0)
(0,0,0)
(0,0,0)
(0,0,0)
(0,0,0)
(0,0,0)
(255,170,85)
(255,255,255)
(255,255,255)
...
...
...
(0,0,0)
(0,0,0)
(0,0,0)
还原后1.bmp(顺时针旋转了90度)