2 * Copyright (C)2011-2012, 2014-2015, 2017, 2019, 2021-2023
3 * D. R. Commander. All Rights Reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * - Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * - Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * - Neither the name of the libjpeg-turbo Project nor the names of its
14 * contributors may be used to endorse or promote products derived from this
15 * software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS",
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
31 * This program demonstrates how to compress, decompress, and transform JPEG
32 * images using the TurboJPEG C API
36 #define _CRT_SECURE_NO_DEPRECATE
43 #include <turbojpeg.h>
47 #define strcasecmp stricmp
48 #define strncasecmp strnicmp
51 #define THROW(action, message) { \
52 printf("ERROR in line %d while %s:\n%s\n", __LINE__, action, message); \
53 retval = -1; goto bailout; \
56 #define THROW_TJ(action) THROW(action, tj3GetErrorStr(tjInstance))
58 #define THROW_UNIX(action) THROW(action, strerror(errno))
60 #define DEFAULT_SUBSAMP TJSAMP_444
61 #define DEFAULT_QUALITY 95
64 const char *subsampName[TJ_NUMSAMP] = {
65 "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0", "4:1:1", "4:4:1"
68 const char *colorspaceName[TJ_NUMCS] = {
69 "RGB", "YCbCr", "GRAY", "CMYK", "YCCK"
72 tjscalingfactor *scalingFactors = NULL;
73 int numScalingFactors = 0;
76 /* DCT filter example. This produces a negative of the image. */
78 static int customFilter(short *coeffs, tjregion arrayRegion,
79 tjregion planeRegion, int componentIndex,
80 int transformIndex, tjtransform *transform)
84 for (i = 0; i < arrayRegion.w * arrayRegion.h; i++)
85 coeffs[i] = -coeffs[i];
91 static void usage(char *programName)
95 printf("\nUSAGE: %s <Input image> <Output image> [options]\n\n",
98 printf("Input and output images can be in Windows BMP or PBMPLUS (PPM/PGM) format. If\n");
99 printf("either filename ends in a .jpg extension, then the TurboJPEG API will be used\n");
100 printf("to compress or decompress the image.\n\n");
102 printf("Compression Options (used if the output image is a JPEG image)\n");
103 printf("--------------------------------------------------------------\n\n");
105 printf("-subsamp <444|422|420|gray> = Apply this level of chrominance subsampling when\n");
106 printf(" compressing the output image. The default is to use the same level of\n");
107 printf(" subsampling as in the input image, if the input image is also a JPEG\n");
108 printf(" image, or to use grayscale if the input image is a grayscale non-JPEG\n");
109 printf(" image, or to use %s subsampling otherwise.\n\n",
110 subsampName[DEFAULT_SUBSAMP]);
112 printf("-q <1-100> = Compress the output image with this JPEG quality level\n");
113 printf(" (default = %d).\n\n", DEFAULT_QUALITY);
115 printf("Decompression Options (used if the input image is a JPEG image)\n");
116 printf("---------------------------------------------------------------\n\n");
118 printf("-scale M/N = Scale the input image by a factor of M/N when decompressing it.\n");
120 for (i = 0; i < numScalingFactors; i++) {
121 printf("%d/%d", scalingFactors[i].num, scalingFactors[i].denom);
122 if (numScalingFactors == 2 && i != numScalingFactors - 1)
124 else if (numScalingFactors > 2) {
125 if (i != numScalingFactors - 1)
127 if (i == numScalingFactors - 2)
133 printf("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =\n");
134 printf(" Perform one of these lossless transform operations on the input image\n");
135 printf(" prior to decompressing it (these options are mutually exclusive.)\n\n");
137 printf("-grayscale = Perform lossless grayscale conversion on the input image prior\n");
138 printf(" to decompressing it (can be combined with the other transform operations\n");
139 printf(" above.)\n\n");
141 printf("-crop WxH+X+Y = Perform lossless cropping on the input image prior to\n");
142 printf(" decompressing it. X and Y specify the upper left corner of the cropping\n");
143 printf(" region, and W and H specify the width and height of the cropping region.\n");
144 printf(" X and Y must be evenly divible by the MCU block size (8x8 if the input\n");
145 printf(" image was compressed using no subsampling or grayscale, 16x8 if it was\n");
146 printf(" compressed using 4:2:2 subsampling, or 16x16 if it was compressed using\n");
147 printf(" 4:2:0 subsampling.)\n\n");
149 printf("General Options\n");
150 printf("---------------\n\n");
152 printf("-fastupsample = Use the fastest chrominance upsampling algorithm available\n\n");
154 printf("-fastdct = Use the fastest DCT/IDCT algorithm available\n\n");
160 int main(int argc, char **argv)
162 tjscalingfactor scalingFactor = TJUNSCALED;
163 int outSubsamp = -1, outQual = -1;
165 int fastUpsample = 0, fastDCT = 0;
167 char *inFormat, *outFormat;
168 FILE *jpegFile = NULL;
169 unsigned char *imgBuf = NULL, *jpegBuf = NULL;
170 int retval = 0, i, pixelFormat = TJPF_UNKNOWN;
171 tjhandle tjInstance = NULL;
173 if ((scalingFactors = tj3GetScalingFactors(&numScalingFactors)) == NULL)
174 THROW_TJ("getting scaling factors");
175 memset(&xform, 0, sizeof(tjtransform));
180 /* Parse arguments. */
181 for (i = 3; i < argc; i++) {
182 if (!strncasecmp(argv[i], "-sc", 3) && i < argc - 1) {
183 int match = 0, temp1 = 0, temp2 = 0, j;
185 if (sscanf(argv[++i], "%d/%d", &temp1, &temp2) < 2)
187 for (j = 0; j < numScalingFactors; j++) {
188 if ((double)temp1 / (double)temp2 == (double)scalingFactors[j].num /
189 (double)scalingFactors[j].denom) {
190 scalingFactor = scalingFactors[j];
197 } else if (!strncasecmp(argv[i], "-su", 3) && i < argc - 1) {
199 if (!strncasecmp(argv[i], "g", 1))
200 outSubsamp = TJSAMP_GRAY;
201 else if (!strcasecmp(argv[i], "444"))
202 outSubsamp = TJSAMP_444;
203 else if (!strcasecmp(argv[i], "422"))
204 outSubsamp = TJSAMP_422;
205 else if (!strcasecmp(argv[i], "420"))
206 outSubsamp = TJSAMP_420;
209 } else if (!strncasecmp(argv[i], "-q", 2) && i < argc - 1) {
210 outQual = atoi(argv[++i]);
211 if (outQual < 1 || outQual > 100)
213 } else if (!strncasecmp(argv[i], "-g", 2))
214 xform.options |= TJXOPT_GRAY;
215 else if (!strcasecmp(argv[i], "-hflip"))
216 xform.op = TJXOP_HFLIP;
217 else if (!strcasecmp(argv[i], "-vflip"))
218 xform.op = TJXOP_VFLIP;
219 else if (!strcasecmp(argv[i], "-transpose"))
220 xform.op = TJXOP_TRANSPOSE;
221 else if (!strcasecmp(argv[i], "-transverse"))
222 xform.op = TJXOP_TRANSVERSE;
223 else if (!strcasecmp(argv[i], "-rot90"))
224 xform.op = TJXOP_ROT90;
225 else if (!strcasecmp(argv[i], "-rot180"))
226 xform.op = TJXOP_ROT180;
227 else if (!strcasecmp(argv[i], "-rot270"))
228 xform.op = TJXOP_ROT270;
229 else if (!strcasecmp(argv[i], "-custom"))
230 xform.customFilter = customFilter;
231 else if (!strncasecmp(argv[i], "-c", 2) && i < argc - 1) {
232 if (sscanf(argv[++i], "%dx%d+%d+%d", &xform.r.w, &xform.r.h, &xform.r.x,
234 xform.r.x < 0 || xform.r.y < 0 || xform.r.w < 1 || xform.r.h < 1)
236 xform.options |= TJXOPT_CROP;
237 } else if (!strcasecmp(argv[i], "-fastupsample")) {
238 printf("Using fast upsampling code\n");
240 } else if (!strcasecmp(argv[i], "-fastdct")) {
241 printf("Using fastest DCT/IDCT algorithm\n");
243 } else usage(argv[0]);
246 /* Determine input and output image formats based on file extensions. */
247 inFormat = strrchr(argv[1], '.');
248 outFormat = strrchr(argv[2], '.');
249 if (inFormat == NULL || outFormat == NULL || strlen(inFormat) < 2 ||
250 strlen(outFormat) < 2)
252 inFormat = &inFormat[1];
253 outFormat = &outFormat[1];
255 if (!strcasecmp(inFormat, "jpg")) {
256 /* Input image is a JPEG image. Decompress and/or transform it. */
258 int inSubsamp, inColorspace;
259 int doTransform = (xform.op != TJXOP_NONE || xform.options != 0 ||
260 xform.customFilter != NULL);
263 /* Read the JPEG file into memory. */
264 if ((jpegFile = fopen(argv[1], "rb")) == NULL)
265 THROW_UNIX("opening input file");
266 if (fseek(jpegFile, 0, SEEK_END) < 0 || ((size = ftell(jpegFile)) < 0) ||
267 fseek(jpegFile, 0, SEEK_SET) < 0)
268 THROW_UNIX("determining input file size");
270 THROW("determining input file size", "Input file contains no data");
272 if ((jpegBuf = tj3Alloc(jpegSize)) == NULL)
273 THROW_UNIX("allocating JPEG buffer");
274 if (fread(jpegBuf, jpegSize, 1, jpegFile) < 1)
275 THROW_UNIX("reading input file");
276 fclose(jpegFile); jpegFile = NULL;
280 unsigned char *dstBuf = NULL; /* Dynamically allocate the JPEG buffer */
283 if ((tjInstance = tj3Init(TJINIT_TRANSFORM)) == NULL)
284 THROW_TJ("initializing transformer");
285 xform.options |= TJXOPT_TRIM;
286 if (tj3Transform(tjInstance, jpegBuf, jpegSize, 1, &dstBuf, &dstSize,
289 THROW_TJ("transforming input image");
295 if ((tjInstance = tj3Init(TJINIT_DECOMPRESS)) == NULL)
296 THROW_TJ("initializing decompressor");
298 if (tj3Set(tjInstance, TJPARAM_FASTUPSAMPLE, fastUpsample) < 0)
299 THROW_TJ("setting TJPARAM_FASTUPSAMPLE");
300 if (tj3Set(tjInstance, TJPARAM_FASTDCT, fastDCT) < 0)
301 THROW_TJ("setting TJPARAM_FASTDCT");
303 if (tj3DecompressHeader(tjInstance, jpegBuf, jpegSize) < 0)
304 THROW_TJ("reading JPEG header");
305 width = tj3Get(tjInstance, TJPARAM_JPEGWIDTH);
306 height = tj3Get(tjInstance, TJPARAM_JPEGHEIGHT);
307 inSubsamp = tj3Get(tjInstance, TJPARAM_SUBSAMP);
308 inColorspace = tj3Get(tjInstance, TJPARAM_COLORSPACE);
310 if (tj3Get(tjInstance, TJPARAM_LOSSLESS))
311 scalingFactor = TJUNSCALED;
313 printf("%s Image: %d x %d pixels, %s subsampling, %s colorspace\n",
314 (doTransform ? "Transformed" : "Input"), width, height,
315 subsampName[inSubsamp], colorspaceName[inColorspace]);
317 if (!strcasecmp(outFormat, "jpg") && doTransform &&
318 scalingFactor.num == 1 && scalingFactor.denom == 1 && outSubsamp < 0 &&
320 /* Input image has been transformed, and no re-compression options
321 have been selected. Write the transformed image to disk and exit. */
322 if ((jpegFile = fopen(argv[2], "wb")) == NULL)
323 THROW_UNIX("opening output file");
324 if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
325 THROW_UNIX("writing output file");
326 fclose(jpegFile); jpegFile = NULL;
330 /* Scaling and/or a non-JPEG output image format and/or compression options
331 have been selected, so we need to decompress the input/transformed
333 if (tj3SetScalingFactor(tjInstance, scalingFactor) < 0)
334 THROW_TJ("setting scaling factor");
335 width = TJSCALED(width, scalingFactor);
336 height = TJSCALED(height, scalingFactor);
338 outSubsamp = inSubsamp;
340 pixelFormat = TJPF_BGRX;
341 if ((unsigned long long)width * height * tjPixelSize[pixelFormat] >
342 (unsigned long long)((size_t)-1))
343 THROW("allocating uncompressed image buffer", "Image is too large");
345 (unsigned char *)malloc(sizeof(unsigned char) * width * height *
346 tjPixelSize[pixelFormat])) == NULL)
347 THROW_UNIX("allocating uncompressed image buffer");
349 if (tj3Decompress8(tjInstance, jpegBuf, jpegSize, imgBuf, 0,
351 THROW_TJ("decompressing JPEG image");
352 tj3Free(jpegBuf); jpegBuf = NULL;
353 tj3Destroy(tjInstance); tjInstance = NULL;
355 /* Input image is not a JPEG image. Load it into memory. */
356 if ((tjInstance = tj3Init(TJINIT_COMPRESS)) == NULL)
357 THROW_TJ("initializing compressor");
358 if ((imgBuf = tj3LoadImage8(tjInstance, argv[1], &width, 1, &height,
359 &pixelFormat)) == NULL)
360 THROW_TJ("loading input image");
361 if (outSubsamp < 0) {
362 if (pixelFormat == TJPF_GRAY)
363 outSubsamp = TJSAMP_GRAY;
365 outSubsamp = TJSAMP_444;
367 printf("Input Image: %d x %d pixels\n", width, height);
370 printf("Output Image (%s): %d x %d pixels", outFormat, width, height);
372 if (!strcasecmp(outFormat, "jpg")) {
373 /* Output image format is JPEG. Compress the uncompressed image. */
376 jpegBuf = NULL; /* Dynamically allocate the JPEG buffer */
379 outQual = DEFAULT_QUALITY;
380 printf(", %s subsampling, quality = %d\n", subsampName[outSubsamp],
383 if (!tjInstance && (tjInstance = tj3Init(TJINIT_COMPRESS)) == NULL)
384 THROW_TJ("initializing compressor");
385 if (tj3Set(tjInstance, TJPARAM_SUBSAMP, outSubsamp) < 0)
386 THROW_TJ("setting TJPARAM_SUBSAMP");
387 if (tj3Set(tjInstance, TJPARAM_QUALITY, outQual) < 0)
388 THROW_TJ("setting TJPARAM_QUALITY");
389 if (tj3Set(tjInstance, TJPARAM_FASTDCT, fastDCT) < 0)
390 THROW_TJ("setting TJPARAM_FASTDCT");
391 if (tj3Compress8(tjInstance, imgBuf, width, 0, height, pixelFormat,
392 &jpegBuf, &jpegSize) < 0)
393 THROW_TJ("compressing image");
394 tj3Destroy(tjInstance); tjInstance = NULL;
396 /* Write the JPEG image to disk. */
397 if ((jpegFile = fopen(argv[2], "wb")) == NULL)
398 THROW_UNIX("opening output file");
399 if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
400 THROW_UNIX("writing output file");
401 tj3Destroy(tjInstance); tjInstance = NULL;
402 fclose(jpegFile); jpegFile = NULL;
403 tj3Free(jpegBuf); jpegBuf = NULL;
405 /* Output image format is not JPEG. Save the uncompressed image
408 if (tj3SaveImage8(tjInstance, argv[2], imgBuf, width, 0, height,
410 THROW_TJ("saving output image");
415 tj3Destroy(tjInstance);
417 if (jpegFile) fclose(jpegFile);