#include <stdio.h> #include <stdlib.h> #include <math.h> #define STB_IMAGE_IMPLEMENTATION #include "/usr/include/stb/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "/usr/include/stb/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_jpeg(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; }
时间: 2024-04-28 14:22:59 浏览: 160
这是一个用 C 语言编写的图像缩放程序,可以将输入的图片按照指定的比例缩小,并输出为新的图片。程序使用了 stb 库来加载和保存图片。具体的实现过程是先通过 stbi_load 函数加载输入图片,然后根据缩放比例计算出新图片的尺寸,创建一个新的图片数据数组 new_image_data,遍历新图片的每个像素,计算出对应的原图像素的位置,将其复制到新的数据数组中,最后通过 stbi_write_jpeg 函数将新的图片保存为 JPEG 格式。
阅读全文