使用libpng将图片转换为RGB数组的代码
时间: 2024-05-07 12:23:21 浏览: 149
下面是使用libpng将一张PNG图片转换为RGB数组的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <input_file>\n", argv[0]);
return 1;
}
const char *filename = argv[1];
FILE *fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Failed to open file: %s\n", filename);
return 1;
}
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
fprintf(stderr, "Failed to create PNG read structure\n");
fclose(fp);
return 1;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
fprintf(stderr, "Failed to create PNG info structure\n");
png_destroy_read_struct(&png_ptr, NULL, NULL);
fclose(fp);
return 1;
}
if (setjmp(png_jmpbuf(png_ptr))) {
fprintf(stderr, "Failed to set PNG error handling\n");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(fp);
return 1;
}
png_init_io(png_ptr, fp);
png_read_info(png_ptr, info_ptr);
png_uint_32 width = png_get_image_width(png_ptr, info_ptr);
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
png_byte color_type = png_get_color_type(png_ptr, info_ptr);
png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
if (color_type != PNG_COLOR_TYPE_RGB_ALPHA) {
fprintf(stderr, "Only RGB with alpha channel PNG images are supported\n");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(fp);
return 1;
}
if (bit_depth != 8) {
fprintf(stderr, "Only 8-bit per channel PNG images are supported\n");
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(fp);
return 1;
}
png_bytepp rows = png_malloc(png_ptr, height * sizeof(png_bytep));
for (png_uint_32 y = 0; y < height; y++) {
rows[y] = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr));
}
png_read_image(png_ptr, rows);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(fp);
// Convert the image to an RGBA array
size_t num_pixels = width * height;
unsigned char *rgba_data = malloc(num_pixels * 4);
for (size_t i = 0; i < num_pixels; i++) {
rgba_data[i * 4 + 0] = rows[i / width][i % width * 4 + 0];
rgba_data[i * 4 + 1] = rows[i / width][i % width * 4 + 1];
rgba_data[i * 4 + 2] = rows[i / width][i % width * 4 + 2];
rgba_data[i * 4 + 3] = rows[i / width][i % width * 4 + 3];
}
// Convert the RGBA array to an RGB array
unsigned char *rgb_data = malloc(num_pixels * 3);
for (size_t i = 0; i < num_pixels; i++) {
rgb_data[i * 3 + 0] = rgba_data[i * 4 + 0];
rgb_data[i * 3 + 1] = rgba_data[i * 4 + 1];
rgb_data[i * 3 + 2] = rgba_data[i * 4 + 2];
}
// Free memory
for (png_uint_32 y = 0; y < height; y++) {
png_free(png_ptr, rows[y]);
}
png_free(png_ptr, rows);
free(rgba_data);
// Do something with the RGB data here...
free(rgb_data);
return 0;
}
```
注意,这个示例只支持RGB格式的PNG图片,并且要求每个通道都是8位精度。如果你需要处理其他格式的图片,需要修改相应的代码。
阅读全文