C语言位图图像文件缩放(西电C程序作业3)

3、位图图像文件缩放
涉及知识点:文件读写、结构体定义、内存管理、基本图像处理算法、命令行参数
要求:
编写一个程序,可以在命令行输入参数,完成指定文件的缩放,并存储到新文件,命令行参数如下
zoom file1.bmp 200 file2.bmp
第一个参数为可执行程序名称,第二个参数为原始图像文件名,第三个参数为缩放比例(百分比),第四个参数为新文件名
bmp文件格式详解
https://blog.csdn.net/o_sun_o/article/details/8351037
C语言#ragma pack用法
https://www.jianshu.com/p/d994731f658d

思路简单,具体代码如下:

#include <stdio.h>
#include <stdlib.h>
//防止编译器的自动对齐
#pragma pack(1)
//定义bmp的起始部分
typedef struct { 
	unsigned short int type; 
	unsigned int size;
	unsigned short int reserved1, reserved2;
	unsigned int offset;
} FILEHEADER; 
typedef struct { 
	unsigned int size;/* Info Header size in bytes */ 
	int width,height;/* Width and height of image */ 

	unsigned short int planes;/* Number of colour planes */ 
	unsigned short int bits; /* Bits per pixel */ 
	unsigned int compression; /* Compression type */ 
	unsigned int imagesize; /* Image size in bytes */ 
	int xresolution,yresolution; /* Pixels per meter */ 
	unsigned int ncolours; /* Number of colours */ 
	unsigned int importantcolours; /* Important colours */ 
} INFOHEADER;
//储存给定文件的起始部分
FILEHEADER src_fh;
INFOHEADER src_ih;
//储存目标文件的起始部分
FILEHEADER dst_fh;
INFOHEADER dst_ih;

unsigned int *src_pixels;//储存目给定文件的所有像素点数据
unsigned int *dst_pixels;//储存目目标文件的所有像素点数据

void changeBmpFile(const char *filename1,const char *filename2 ,double t){
	FILE *fp;
	FILE *dst;
	//将给定文件和目标文件打开
	fp = fopen(filename1 , "rb");
	dst = fopen(filename2 , "wb");
	if(fp == NULL){
		printf("ERROR\n");
		return ;
	}
	//读取给定文件的信息并保存
	fread(&src_fh , sizeof(FILEHEADER) , 1 , fp);
	fread(&src_ih , sizeof(INFOHEADER) , 1 , fp);
	int size = src_ih.height*src_ih.width;
	src_pixels = (unsigned int*)malloc(sizeof(int)*size);
	fread(src_pixels , sizeof(int), size,fp);
	//计算缩放后产生文件的大小
	int height = (int)(src_ih.height*t);
	int width = (int)(src_ih.width*t);
	int newsize = height*width;
	
	dst_pixels = (unsigned int*)malloc(sizeof(unsigned int)*newsize);//申请数据储存的内存
	dst = fopen(filename2,"wb");
	//更改目标文件起始部分的数据
	dst_fh = src_fh;
	dst_ih = src_ih;
	dst_ih.height = height;
	dst_ih.width = width;
	
	//将位图数据全部置于目标文件存储的数组中
	for(int i = 0; i < height;i ++){
		for(int j = 0; j < width; j ++){
			int m = (int)(i/t)*src_ih.height + (int)(j/t);
			dst_pixels[i*height+j] = src_pixels[m];
		}
	}
	//将数据写入到文件中
	fwrite(&dst_fh, sizeof(FILEHEADER), 1, dst);
	fwrite(&dst_ih, sizeof(INFOHEADER), 1, dst);
	fwrite(dst_pixels, newsize, sizeof(int), dst);
	fclose(fp);
	fclose(dst);
}

int main(int argc, char** argv){
	double a = atoi(argv[2])/100.0;
	changeBmpFile(argv[1],argv[3],a);
	printf("OK!");
	return 0;
}
  • 20
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值