转换工具将jpg格式转换为bmp格式
### 代码样例 ###
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define BYTE unsigned char
int main(int argc, char **argv)
{
if(argc != 3){
fprintf(stderr, "Usage : ./jpg2bmp.exe inputfile outputfile\n");
return -1;
}
// 打开输入文件
FILE *fp = fopen(argv[1], "rb");
if(fp == NULL){
fprintf(stderr, "fopen %s error\n", argv[1]);
return -1;
}
// 读取文件头
BYTE head[54];
if(fread(head, sizeof(BYTE), 54, fp) != 54){
fprintf(stderr, "read %s error\n", argv[1]);
fclose(fp);
return -1;
}
// 判断是否是BMP格式
if(head[0] != 'B' || head[1] != 'M'){
fprintf(stderr, "%s is not BMP format\n", argv[1]);
fclose(fp);
return -1;
}
// 获取图像尺寸
int width = *(int *)(&head[18]);
int height = *(int *)(&head[22]);
// 创建位图图像数据数组
BYTE *data = (BYTE *)malloc(sizeof(BYTE) * width * height * 3);
if(data == NULL){
fprintf(stderr,"malloc data error\n");
fclose(fp);
return -1;
}
// 读取图像像素点数据
int ret = fread(data, sizeof(BYTE), width * height * 3, fp);
if(ret != width * height * 3){
fprintf(stderr,"read %s pixel data error\n", argv[1]);
fclose(fp);
free(data);
return -1;
}
fclose(fp);
// 创建输出文件
FILE *ofp = fopen(argv[2], "wb");
if(ofp == NULL){
fprintf(stderr, "fopen %s error\n", argv[2]);
free(data);
return -1;
}
// 写入BMP文件头
if(fwrite(head, sizeof(BYTE), 54, ofp) != 54){
fprintf(stderr, "write %s bmp header error\n", argv[2]);
fclose(ofp);
free(data);
return -1;
}
// 写入图像数据
if(fwrite(data, sizeof(BYTE), width * height * 3, ofp) != width * height * 3){
fprintf(stderr, "write %s pixel data error\n", argv[2]);
fclose(ofp);
free(data);
return -1;
}
fclose(ofp);
free(data);
return 0;
}
用户评论