libjpeg-turbo的使用

平时用OpenCV存图,bmp格式速度快但占空间大,jpg格式反之。新版libjpeg-turbo存图效率高,可从官网下载,安装.exe文件并解压压缩包。应用时参考doc文件夹中的example.txt,注意图片指针数据需为RGB,静态调用更可靠。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

平时都用OpenCV的imwrite存图,保存为bmp格式的图片,速度快但占用空间大;存为jpg格式,占用空间小但存图时间长。
了解到libjpeg这个开源库存图,实验了一下,老版的libjpeg与OpenCV相比,没有优势。新版的libjpeg-turbo就不一样了,存图效率很高。
(1)从官网下载最新版本的libjpeg-turbo
https://libjpeg-turbo.org/
在这里插入图片描述
(2)安装.exe文件,解压压缩包
在这里插入图片描述
(3)应用
参考doc文件夹中的example.txt,了解使用步骤
注意:
要求的图片指针数据为 RGB!
要求的图片指针数据为 RGB!
要求的图片指针数据为 RGB!

参数解析:
char filename 要保存的图像文件名
int quality jpg图像的压缩率(0-100)
unsigned char
image_buffer 图像指针(RGB排序)
int image_width 图像宽
int image_height 图像高

void write_JPEG_file(char *filename, int quality, unsigned char* image_buffer, int image_width, int image_height)
{
	/* This struct contains the JPEG compression parameters and pointers to
	* working space (which is allocated as needed by the JPEG library).
	* It is possible to have several such structures, representing multiple
	* compression/decompression processes, in existence at once.  We refer
	* to any one struct (and its associated working data) as a "JPEG object".
	*/
	struct jpeg_compress_struct cinfo;
	/* This struct represents a JPEG error handler.  It is declared separately
	* because applications often want to supply a specialized error handler
	* (see the second half of this file for an example).  But here we just
	* take the easy way out and use the standard error handler, which will
	* print a message on stderr and call exit() if compression fails.
	* Note that this struct must live as long as the main JPEG parameter
	* struct, to avoid dangling-pointer problems.
	*/
	struct jpeg_error_mgr jerr;
	/* More stuff */
	FILE *outfile;                /* target file */
	JSAMPROW row_pointer[1];      /* pointer to JSAMPLE row[s] */
	int row_stride;               /* physical row width in image buffer */

	/* Step 1: allocate and initialize JPEG compression object */

	/* We have to set up the error handler first, in case the initialization
	* step fails.  (Unlikely, but it could happen if you are out of memory.)
	* This routine fills in the contents of struct jerr, and returns jerr's
	* address which we place into the link field in cinfo.
	*/
	cinfo.err = jpeg_std_error(&jerr);
	/* Now we can initialize the JPEG compression object. */
	jpeg_create_compress(&cinfo);

	/* Step 2: specify data destination (eg, a file) */
	/* Note: steps 2 and 3 can be done in either order. */

	/* Here we use the library-supplied code to send compressed data to a
	* stdio stream.  You can also write your own code to do something else.
	* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
	* requires it in order to write binary files.
	*/
	if ((outfile = fopen(filename, "wb")) == NULL) {
		fprintf(stderr, "can't open %s\n", filename);
		exit(1);
	}
	jpeg_stdio_dest(&cinfo, outfile);

	/* Step 3: set parameters for compression */

	/* First we supply a description of the input image.
	* Four fields of the cinfo struct must be filled in:
	*/
	cinfo.image_width = image_width;      /* image width and height, in pixels */
	cinfo.image_height = image_height;
	cinfo.input_components = 3;           /* # of color components per pixel */
	cinfo.in_color_space = JCS_RGB;       /* colorspace of input image */
	/* Now use the library's routine to set default compression parameters.
	* (You must set at least cinfo.in_color_space before calling this,
	* since the defaults depend on the source color space.)
	*/
	jpeg_set_defaults(&cinfo);
	/* Now you can set any non-default parameters you wish to.
	* Here we just illustrate the use of quality (quantization table) scaling:
	*/
	jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);

	/* Step 4: Start compressor */

	/* TRUE ensures that we will write a complete interchange-JPEG file.
	* Pass TRUE unless you are very sure of what you're doing.
	*/
	jpeg_start_compress(&cinfo, TRUE);

	/* Step 5: while (scan lines remain to be written) */
	/*           jpeg_write_scanlines(...); */

	/* Here we use the library's state variable cinfo.next_scanline as the
	* loop counter, so that we don't have to keep track ourselves.
	* To keep things simple, we pass one scanline per call; you can pass
	* more if you wish, though.
	*/
	row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */

	while (cinfo.next_scanline < cinfo.image_height) {
		/* jpeg_write_scanlines expects an array of pointers to scanlines.
		* Here the array is only one element long, but you could pass
		* more than one scanline at a time if that's more convenient.
		*/
		row_pointer[0] = &image_buffer[cinfo.next_scanline * row_stride];
		(void)jpeg_write_scanlines(&cinfo, row_pointer, 1);
	}

	/* Step 6: Finish compression */

	jpeg_finish_compress(&cinfo);
	/* After finish_compress, we can close the output file. */
	fclose(outfile);

	/* Step 7: release JPEG compression object */

	/* This is an important step since it will release a good deal of memory. */
	jpeg_destroy_compress(&cinfo);

	/* And we're done! */
}

最重要的一点:动态调用的方式用问题,但 静态调用 放心大胆的使用!
最重要的一点:动态调用的方式用问题,但 静态调用 放心大胆的使用!
最重要的一点:动态调用的方式用问题,但 静态调用 放心大胆的使用!

### 如何使用 libjpeg-turbo 库 为了有效地利用 `libjpeg-turbo` 进行 JPEG 文件的操作,可以遵循以下指南: #### 添加环境变量路径 确保已将 NASM 的安装目录添加到系统的环境变量 PATH 中[^1]。 ```bash export PATH=$PATH:/C/Program\ Files/NASM ``` #### 编译并安装 libjpeg-turbo 可以通过源码编译的方式来获取最新版本的 `libjpeg-turbo`。以下是基于 Linux 平台上的操作流程;对于 Windows 用户,则需调整命令以适应特定平台需求。 下载最新的 tarball 或者克隆官方仓库: ```bash git clone https://github.com/libjpeg-turbo/libjpeg-turbo.git cd libjpeg-turbo/ mkdir build && cd build cmake .. make -j$(nproc) sudo make install ``` 上述过程会完成库文件以及头文件的安装工作。如果希望验证安装是否成功,可尝试运行简单的测试程序来确认功能正常。 #### 使用 CMake 构建项目时链接 libjpeg-turbo 当创建新的应用程序并与 `libjpeg-turbo` 配合时,在项目的 CMakeLists.txt 文件内加入如下配置项以便于自动查找和连接所需的静态或共享库。 ```cmake find_package(JPEG REQUIRED) target_link_libraries(your_project_name PRIVATE ${JPEG_LIBRARIES}) include_directories(${JPEG_INCLUDE_DIRS}) ``` 这样设置之后就可以顺利调用 `libjpeg-turbo` 提供的功能接口了。 #### 示例代码:读取与保 JPEG 像 这里给出一段 Python 和 C++ 下载片并通过 `libjpeg-turbo` 解压缩的例子作为参考。 Python 版本依赖 Pillow 库支持 TurboJPEG 加速解压: ```python from PIL import Image import turbojpeg turbo_jpeg = turbojpeg.TurboJPEG() with open('input.jpg', 'rb') as f: img_bytes = f.read() img_array = turbo_jpeg.decode(img_bytes) image = Image.fromarray(img_array) image.save('output.png') ``` C++ 版本则直接通过 API 调用来实现相同目的: ```cpp #include <iostream> #include <fstream> #include <vector> extern "C" { #include <jpeglib.h> } int main() { std::ifstream file("example.jpg", std::ios::binary); if (!file.is_open()) { /* handle error */ } // Read entire contents of input image into buffer. file.seekg(0, std::ios::end); size_t length = file.tellg(); char* buffer = new char[length]; file.seekg(0, std::ios::beg); file.read(buffer, length); struct jpeg_decompress_struct cinfo; JSAMPARRAY buffer_out; // Output row buffer unsigned long width, height; // Dimensions after decompression int row_stride; // Initialize the JPEG decompression object with default parameters. jpeg_create_decompress(&cinfo); // Specify data source for this instance of libjpeg. jpeg_mem_src(&cinfo, reinterpret_cast<JOCTET*>(buffer), static_cast<unsigned long>(length)); // Read header information from the JPEG source. jpeg_read_header(&cinfo, TRUE); // Start actual decompression process. jpeg_start_decompress(&cinfo); width = cinfo.output_width; height = cinfo.output_height; row_stride = width * cinfo.output_components; // Allocate memory to hold one scanline at a time. buffer_out = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1); while (cinfo.output_scanline < cinfo.output_height) { // Read each line sequentially until done reading whole image. jpeg_read_scanlines(&cinfo, buffer_out, 1); } // Finish up by releasing resources used during compression/decompression processes. jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); delete[] buffer; } ``` 以上展示了如何集成 `libjpeg-turbo` 到不同编程环境中,并提供了基本示例帮助理解其核心概念。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mirinda_cjy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值