要在Linux上读取C++中的JPEG和PNG像素,您可以使用以下库和工具:
以下是一个使用libjpeg和libpng库读取JPEG和PNG图像像素的示例代码:
#include<iostream>
#include <jpeglib.h>
#include <png.h>
void readJPEG(const char* filename) {
FILE* infile;
JSAMPARRAY buffer;
int row_stride;
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
infile = fopen(filename, "rb");
if (infile == NULL) {
std::cerr << "Error opening JPEG file"<< std::endl;
return;
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines(&cinfo, buffer, 1);
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
}
void readPNG(const char* filename) {
FILE* infile;
png_structp png_ptr;
png_infop info_ptr;
int width, height, bit_depth, color_type;
infile = fopen(filename, "rb");
if (infile == NULL) {
std::cerr << "Error opening PNG file"<< std::endl;
return;
}
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
if (setjmp(png_jmpbuf(png_ptr))) {
std::cerr << "Error during init_io"<< std::endl;
return;
}
png_init_io(png_ptr, infile);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
// TODO: Process the image data
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(infile);
}
int main() {
readJPEG("image.jpg");
readPNG("image.png");
return 0;
}
请注意,这只是一个示例代码,您需要根据您的需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云