固定用8位256*256格式可以简化点:
#include<stdio.h>
#include<stdlib.h>
/*
位图头结构
*/
#pragma pack(1)
typedef struct tagBITMAPFILEHEADER
{
unsigned char bfType[2];//文件格式
unsigned long bfSize;//文件大小
unsigned short bfReserved1;//保留
unsigned short bfReserved2;
unsigned long bfOffBits; //DIB数据在文件中的偏移量
} fileHeader;
/*
位图数据信息结构
*/
typedef struct tagBITMAPINFOHEADER
{
unsigned long biSize;//该结构的大小
long biWidth;//文件宽度
long biHeight;//文件高度
unsigned short biPlanes;//平面数
unsigned short biBitCount;//颜色位数
unsigned long biCompression;//压缩类型
unsigned long biSizeImage;//DIB数据区大小
long biXPixPerMeter;
long biYPixPerMeter;
unsigned long biClrUsed;//多少颜色索引表
unsigned long biClrImporant;//多少重要颜色
} fileInfo;
/*
调色板结构
*/
typedef struct tagRGBQUAD
{
unsigned char rgbBlue; //蓝色分量亮度
unsigned char rgbGreen;//绿色分量亮度
unsigned char rgbRed;//红色分量亮度
unsigned char rgbReserved;
} rgbq;
typedef struct tagBITMAPINFO
{
fileHeader head;
fileInfo info;
rgbq rgb[256];
} bmpInfo;
#pragma pack()
FILE *_fopen(char *path, char *mode)
{
FILE *fp;
if ((fp=fopen(path,mode)) == NULL)
{
printf("打开文件失败, %s\n", path);
exit(0);
}
return fp;
}
unsigned char *_read(FILE *fp)
{
int fSize = sizeof(bmpInfo)+256*256;
unsigned char *buf = (unsigned char *)malloc(fSize);
if (buf == NULL)
{
printf("分配内存失败\n");
exit(0);
}
fread(buf, fSize, 1, fp);
return buf;
}
void _hide(char *fCov, char *fSec, char *fSte)
{
FILE *fpCov = _fopen(fCov,"rb");
FILE *fpSec = _fopen(fSec,"rb");
FILE *fpSte = _fopen(fSte,"wb");
unsigned char *CovBuf = _read(fpCov);
unsigned char *SecBuf = _read(fpSec);
bmpInfo *biCov = (bmpInfo *)CovBuf;
bmpInfo *biSec = (bmpInfo *)SecBuf;
if (biCov->info.biBitCount!=8 || biCov->info.biWidth!=256 || biCov->info.biHeight!=256 ||
biSec->info.biBitCount!=8 || biSec->info.biWidth!=256 || biSec->info.biHeight!=256)
{
printf("文件格式不符,要求8位256*256的BMP文件");
exit(0);
}
unsigned char *pCov = CovBuf + sizeof(bmpInfo);
unsigned char *pSec = SecBuf + sizeof(bmpInfo);
int i;
for (i=0; i<256*256; ++i,++pCov,++pSec)
*pCov = (*pCov&0xF0)|(*pSec>>4);
fwrite(CovBuf, sizeof(bmpInfo)+256*256, 1, fpSte);
free(CovBuf);
free(SecBuf);
fclose(fpCov);
fclose(fpSec);
fclose(fpSte);
}
void _show(char *fCov, char *fSte)
{
FILE *fpCov = _fopen(fCov,"rb");
FILE *fpSte = _fopen(fSte,"wb");
unsigned char *CovBuf = _read(fpCov);
bmpInfo *biCov = (bmpInfo *)CovBuf;
if (biCov->info.biBitCount!=8 || biCov->info.biWidth!=256 || biCov->info.biHeight!=256)
{
printf("文件格式不符,要求8位256*256的BMP文件");
exit(0);
}
unsigned char *pCov = CovBuf + sizeof(bmpInfo);
int i;
for (i=0; i<256*256; ++i,++pCov)
*pCov = *pCov<<4;
fwrite(CovBuf, sizeof(bmpInfo)+256*256, 1, fpSte);
free(CovBuf);
fclose(fpCov);
fclose(fpSte);
}
int main()
{
_hide("1.bmp", "2.bmp", "123.bmp");
_show("123.bmp", "321.bmp");
printf("success\n");
return 0;
}