在ubuntu中用c语言写一个实现图片缩放的代码
时间: 2024-02-23 22:58:08 浏览: 105
好的,下面是一个简单的图片缩放的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
int main(int argc, char* argv[])
{
if (argc < 4) {
printf("Usage: %s input_file output_file scale\n", argv[0]);
return 1;
}
char* input_file = argv[1];
char* output_file = argv[2];
float scale = atof(argv[3]);
int width, height, channels;
unsigned char* image_data = stbi_load(input_file, &width, &height, &channels, STBI_rgb_alpha);
if (!image_data) {
printf("Error: Failed to load image file %s\n", input_file);
return 1;
}
int new_width = (int)round(scale * width);
int new_height = (int)round(scale * height);
unsigned char* new_image_data = (unsigned char*)malloc(new_width * new_height * 4);
for (int y = 0; y < new_height; y++) {
for (int x = 0; x < new_width; x++) {
int src_x = (int)round(x / scale);
int src_y = (int)round(y / scale);
src_x = src_x >= width ? width - 1 : src_x;
src_y = src_y >= height ? height - 1 : src_y;
int src_index = (src_y * width + src_x) * 4;
int dst_index = (y * new_width + x) * 4;
new_image_data[dst_index] = image_data[src_index];
new_image_data[dst_index + 1] = image_data[src_index + 1];
new_image_data[dst_index + 2] = image_data[src_index + 2];
new_image_data[dst_index + 3] = image_data[src_index + 3];
}
}
stbi_write_png(output_file, new_width, new_height, STBI_rgb_alpha, new_image_data, new_width * 4);
stbi_image_free(image_data);
free(new_image_data);
return 0;
}
```
这个代码依赖于STB的图像处理库,可以使用以下命令安装:
```
sudo apt-get install libstb-dev
```
然后使用以下命令编译:
```
gcc -o image_scale image_scale.c -lm -lstb_image -lstb_image_write
```
使用方式如下:
```
./image_scale input_file output_file scale
```
其中,input_file为原始图片路径,output_file为缩放后图片路径,scale为缩放比例。例如:
```
./image_scale input.png output.png 0.5
```
会将input.png缩放为原始图片的一半大小,并保存为output.png。
阅读全文