I have the next standard code for JPEG image decompression which is based on libjpeg.
jpeg_decompress_struct cinfo;
// ...Set error manager and data source...
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
while (cinfo.output_scanline < cinfo.output_height) {
JSAMPLE* scanlines[1];
// ...Set target pointer for scanline...
jpeg_read_scanlines(&cinfo, scanlines, 1);
}
jpeg_destroy_decompress(&cinfo);
I want to read a part of the image, cropped by a rectangle:
// struct RECT {
// int left;
// int top;
// int right;
// int bottom;
// };
RECT cropRect; // Coordinates of the crop rectangle relative to the output image size
What should I modify in the code below to tell libjpeg to crop the image immediately?
This is how I can implement it:
- Ignore first
top - 1lines; - For each of the next
bottom - toplines:
1) Read scanline to temporary buffer;
2) Copy pixels from column range[left, right)from temporary buffer to the target buffer. - Abort the decompression.
But this code is redundant.
Performance-wise, especially if the original image is high resolution and you need a relatively small part of it, you should perhaps first crop/trim the image losslessly without decompressing it, which is possible at 16×16 px (8×8?) granularity and fast, and then decompress skipping just a few lines and pixels off the margins. You might also like this approach for smaller amount of memory in use for the operation.
If you are cropping just a bit, then the original plan to start decompressing in full is perhaps the best. There is almost no redundancy here.