#include <stdio.h>
#include <windows.h> //bmp
#include <iostream>
using namespace std;
#define BYTE unsigned char
int m_Width;
int m_Height;
int i; int j;
int a1; int a2;
int b1; int b2;
BITMAPFILEHEADER hf;
BITMAPINFOHEADER hInfo;
void SetPixel(BYTE *lpImg, int i, int j, BYTE r, BYTE g, BYTE b);
void Raw2BMP(BYTE *lpImg);
void MakeBMPFile(char *FileName, BYTE *OutImage);
void main()
m_Width = 60;
m_Height = 60;
BYTE *lpImg = new BYTE[m_Width * m_Height*3];
memset(lpImg, 0, m_Width*m_Height*3);
// pixel drawing in(i,j)=>(r,g,b)
BYTE r=255;
BYTE g=255;
BYTE b=255;
SetPixel(lpImg, i, j, r, g, b); //lpImp,10,100,123,200,40
Raw2BMP (lpImg);
// save to bmp
// BMP header
hInfo.biSize=40;
hInfo.biWidth=m_Width;
hInfo.biHeight=m_Height*-1;
hInfo.biPlanes=1;
hInfo.biBitCount=24;
hInfo.biCompression=0;
hInfo.biSizeImage=m_Width*m_Height*3;
hInfo.biXPelsPerMeter=0;
hInfo.biYPelsPerMeter=0;
hInfo.biClrUsed=0;
hInfo.biClrImportant=0;
hf.bfType=19778;
hf.bfOffBits=54;
hf.bfReserved1=0;
hf.bfReserved2=0;
hf.bfSize=hInfo.biSizeImage+hf.bfOffBits;
MakeBMPFile ("BMP.bmp",lpImg);
void SetPixel (BYTE *lpImg, int i, int j, BYTE r, BYTE g, BYTE b)//lpImp,10,100,123,200,40
cout << "X(0-60)" << endl;
cin >> b1;
cout << "X(0-60)" << endl;
cin >> b2;
cout << "Y(0-60)" << endl;
cin >> a1;
cout << "Y(0-60)" << endl;
cin >> a2;
for ( i = a1; i < a2; i++){
for( j = b1; j < b2; j++){
*(lpImg+m_Width*3*i+j*3+0)=r; //red
*(lpImg+m_Width*3*i+j*3+1)=g; //green
*(lpImg+m_Width*3*i+j*3+2)=b; //blue
void Raw2BMP (BYTE *lpImg)
BYTE *TmpBuf = new BYTE[m_Width*m_Height*3];
for(i = 0 ; i < m_Height; i++) {
for( j=0 ; j < m_Width; j++) {
*(TmpBuf+m_Width*3*i+j*3+2) = *(lpImg+m_Width*3*i+j*3+0);
*(TmpBuf+m_Width*3*i+j*3+1) = *(lpImg+m_Width*3*i+j*3+1);
*(TmpBuf+m_Width*3*i+j*3+0) = *(lpImg+m_Width*3*i+j*3+2);
delete []TmpBuf;
void MakeBMPFile(char *FileName, BYTE *OutImage)
FILE *OutFile;
OutFile = fopen(FileName, "wb");
fwrite(&hf,sizeof(char), sizeof(BITMAPFILEHEADER), OutFile);
fwrite(&hInfo, sizeof(char), sizeof(BITMAPINFOHEADER), OutFile);
fwrite(OutImage, m_Width * m_Height * 3, 1, OutFile);
fclose(OutFile);
上下倒
追答原理很简单。 伪代码:
void swap(rgb* data, int w, int h)
{
k = h/2;
for(i=0; ir = (data+(h-i)*w)->r;
/* 个人建议用rgb结构体表示较好, 用[0], [1], [2]表示不利于rgb转换。 windows下,位图按照bgr 存储的。
*/
(data+i*w)->g = (data+(h-i)*w)->g;
(data+i*w)->b= (data+(h-i)*w)->b;
}
}