版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons)
image.h
//基于当前窗口的简单显示图片函数头文件image.h
#ifndef _IMAGE_
#define _IMAGE_
#include<iostream>
#include<Windows.h>
#include<malloc.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include"draw.h"
#include"strif.h"
using namespace std;
void imagedraw(char fileName[1000000],int x,int y,bool existerror/*如果文件不存在是否弹出错误窗口*/) {
char *buf; //定义文件读取缓冲区
char *p;
int r,g,b,pix;
// HWND wnd; //窗口句柄
// HDC dc; //绘图设备环境句柄
FILE *fp; //定义文件指针
FILE *fpw; //定义保存文件指针
DWORD w,h; //定义读取图像的长和宽
DWORD bitCorlorUsed; //定义
DWORD bitSize; //定义图像的大小
BITMAPFILEHEADER bf; //图像文件头
BITMAPINFOHEADER bi; //图像文件头信息
if(findstr(fileName,".bmp") != 1 && findstr(fileName,".BMP") != 1) {
MessageBox(GetForegroundWindow(),"Support only BMP images!","Error",MB_OK);
return;
}
if((fp=fopen(fileName,"rb"))==NULL) {
if(existerror==true) MessageBox(GetForegroundWindow(),"file does not exist!","Error",MB_OK);
return;
}
fread(&bf,sizeof(BITMAPFILEHEADER),1,fp);//读取BMP文件头文件
fread(&bi,sizeof(BITMAPINFOHEADER),1,fp);//读取BMP文件头文件信息
w=bi.biWidth; //获取图像的宽
h=bi.biHeight; //获取图像的高
bitSize=bi.biSizeImage; //获取图像的size
buf=(char*)malloc(w*h*3); //分配缓冲区大小
fseek(fp,long(sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)),0);//定位到像素起始位置
fread(buf,1,w*h*3,fp); //开始读取数据
// wnd=GetForegroundWindow(); //获取窗口句柄
// dc=GetDC(wnd); //获取绘图设备
system("cls");
p=buf;
for(int j=0; j<h; j++) {
for(int i=0; i<w; i++) {
b=*p++;
g=*p++;
r=*p++;
pix=RGB(r,g,b);
SetPixel(DC,x+i,y+h-j,pix);
}
}
fclose(fp);
return;
}
#endif
依赖我写的另外两个头文件,到我的主页里去找找
依赖draw.h和strif.h
参考网上一些零零碎碎的代码,做了不少优化,精简代码等等。