tjexample.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. * Copyright (C)2011-2012, 2014-2015, 2017, 2019 D. R. Commander.
  3. * All Rights Reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  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.
  16. *
  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.
  28. */
  29. /*
  30. * This program demonstrates how to compress, decompress, and transform JPEG
  31. * images using the TurboJPEG C API
  32. */
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <errno.h>
  37. #include <turbojpeg.h>
  38. #ifdef _WIN32
  39. #define strcasecmp stricmp
  40. #define strncasecmp strnicmp
  41. #endif
  42. #define THROW(action, message) { \
  43. printf("ERROR in line %d while %s:\n%s\n", __LINE__, action, message); \
  44. retval = -1; goto bailout; \
  45. }
  46. #define THROW_TJ(action) THROW(action, tjGetErrorStr2(tjInstance))
  47. #define THROW_UNIX(action) THROW(action, strerror(errno))
  48. #define DEFAULT_SUBSAMP TJSAMP_444
  49. #define DEFAULT_QUALITY 95
  50. const char *subsampName[TJ_NUMSAMP] = {
  51. "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0", "4:1:1"
  52. };
  53. const char *colorspaceName[TJ_NUMCS] = {
  54. "RGB", "YCbCr", "GRAY", "CMYK", "YCCK"
  55. };
  56. tjscalingfactor *scalingFactors = NULL;
  57. int numScalingFactors = 0;
  58. /* DCT filter example. This produces a negative of the image. */
  59. static int customFilter(short *coeffs, tjregion arrayRegion,
  60. tjregion planeRegion, int componentIndex,
  61. int transformIndex, tjtransform *transform)
  62. {
  63. int i;
  64. for (i = 0; i < arrayRegion.w * arrayRegion.h; i++)
  65. coeffs[i] = -coeffs[i];
  66. return 0;
  67. }
  68. static void usage(char *programName)
  69. {
  70. int i;
  71. printf("\nUSAGE: %s <Input image> <Output image> [options]\n\n",
  72. programName);
  73. printf("Input and output images can be in Windows BMP or PBMPLUS (PPM/PGM) format. If\n");
  74. printf("either filename ends in a .jpg extension, then the TurboJPEG API will be used\n");
  75. printf("to compress or decompress the image.\n\n");
  76. printf("Compression Options (used if the output image is a JPEG image)\n");
  77. printf("--------------------------------------------------------------\n\n");
  78. printf("-subsamp <444|422|420|gray> = Apply this level of chrominance subsampling when\n");
  79. printf(" compressing the output image. The default is to use the same level of\n");
  80. printf(" subsampling as in the input image, if the input image is also a JPEG\n");
  81. printf(" image, or to use grayscale if the input image is a grayscale non-JPEG\n");
  82. printf(" image, or to use %s subsampling otherwise.\n\n",
  83. subsampName[DEFAULT_SUBSAMP]);
  84. printf("-q <1-100> = Compress the output image with this JPEG quality level\n");
  85. printf(" (default = %d).\n\n", DEFAULT_QUALITY);
  86. printf("Decompression Options (used if the input image is a JPEG image)\n");
  87. printf("---------------------------------------------------------------\n\n");
  88. printf("-scale M/N = Scale the input image by a factor of M/N when decompressing it.\n");
  89. printf("(M/N = ");
  90. for (i = 0; i < numScalingFactors; i++) {
  91. printf("%d/%d", scalingFactors[i].num, scalingFactors[i].denom);
  92. if (numScalingFactors == 2 && i != numScalingFactors - 1)
  93. printf(" or ");
  94. else if (numScalingFactors > 2) {
  95. if (i != numScalingFactors - 1)
  96. printf(", ");
  97. if (i == numScalingFactors - 2)
  98. printf("or ");
  99. }
  100. }
  101. printf(")\n\n");
  102. printf("-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =\n");
  103. printf(" Perform one of these lossless transform operations on the input image\n");
  104. printf(" prior to decompressing it (these options are mutually exclusive.)\n\n");
  105. printf("-grayscale = Perform lossless grayscale conversion on the input image prior\n");
  106. printf(" to decompressing it (can be combined with the other transform operations\n");
  107. printf(" above.)\n\n");
  108. printf("-crop WxH+X+Y = Perform lossless cropping on the input image prior to\n");
  109. printf(" decompressing it. X and Y specify the upper left corner of the cropping\n");
  110. printf(" region, and W and H specify the width and height of the cropping region.\n");
  111. printf(" X and Y must be evenly divible by the MCU block size (8x8 if the input\n");
  112. printf(" image was compressed using no subsampling or grayscale, 16x8 if it was\n");
  113. printf(" compressed using 4:2:2 subsampling, or 16x16 if it was compressed using\n");
  114. printf(" 4:2:0 subsampling.)\n\n");
  115. printf("General Options\n");
  116. printf("---------------\n\n");
  117. printf("-fastupsample = Use the fastest chrominance upsampling algorithm available in\n");
  118. printf(" the underlying codec.\n\n");
  119. printf("-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying\n");
  120. printf(" codec.\n\n");
  121. printf("-accuratedct = Use the most accurate DCT/IDCT algorithms available in the\n");
  122. printf(" underlying codec.\n\n");
  123. exit(1);
  124. }
  125. int main(int argc, char **argv)
  126. {
  127. tjscalingfactor scalingFactor = { 1, 1 };
  128. int outSubsamp = -1, outQual = -1;
  129. tjtransform xform;
  130. int flags = 0;
  131. int width, height;
  132. char *inFormat, *outFormat;
  133. FILE *jpegFile = NULL;
  134. unsigned char *imgBuf = NULL, *jpegBuf = NULL;
  135. int retval = 0, i, pixelFormat = TJPF_UNKNOWN;
  136. tjhandle tjInstance = NULL;
  137. if ((scalingFactors = tjGetScalingFactors(&numScalingFactors)) == NULL)
  138. THROW_TJ("getting scaling factors");
  139. memset(&xform, 0, sizeof(tjtransform));
  140. if (argc < 3)
  141. usage(argv[0]);
  142. /* Parse arguments. */
  143. for (i = 3; i < argc; i++) {
  144. if (!strncasecmp(argv[i], "-sc", 3) && i < argc - 1) {
  145. int match = 0, temp1 = 0, temp2 = 0, j;
  146. if (sscanf(argv[++i], "%d/%d", &temp1, &temp2) < 2)
  147. usage(argv[0]);
  148. for (j = 0; j < numScalingFactors; j++) {
  149. if ((double)temp1 / (double)temp2 == (double)scalingFactors[j].num /
  150. (double)scalingFactors[j].denom) {
  151. scalingFactor = scalingFactors[j];
  152. match = 1;
  153. break;
  154. }
  155. }
  156. if (match != 1)
  157. usage(argv[0]);
  158. } else if (!strncasecmp(argv[i], "-su", 3) && i < argc - 1) {
  159. i++;
  160. if (!strncasecmp(argv[i], "g", 1))
  161. outSubsamp = TJSAMP_GRAY;
  162. else if (!strcasecmp(argv[i], "444"))
  163. outSubsamp = TJSAMP_444;
  164. else if (!strcasecmp(argv[i], "422"))
  165. outSubsamp = TJSAMP_422;
  166. else if (!strcasecmp(argv[i], "420"))
  167. outSubsamp = TJSAMP_420;
  168. else
  169. usage(argv[0]);
  170. } else if (!strncasecmp(argv[i], "-q", 2) && i < argc - 1) {
  171. outQual = atoi(argv[++i]);
  172. if (outQual < 1 || outQual > 100)
  173. usage(argv[0]);
  174. } else if (!strncasecmp(argv[i], "-g", 2))
  175. xform.options |= TJXOPT_GRAY;
  176. else if (!strcasecmp(argv[i], "-hflip"))
  177. xform.op = TJXOP_HFLIP;
  178. else if (!strcasecmp(argv[i], "-vflip"))
  179. xform.op = TJXOP_VFLIP;
  180. else if (!strcasecmp(argv[i], "-transpose"))
  181. xform.op = TJXOP_TRANSPOSE;
  182. else if (!strcasecmp(argv[i], "-transverse"))
  183. xform.op = TJXOP_TRANSVERSE;
  184. else if (!strcasecmp(argv[i], "-rot90"))
  185. xform.op = TJXOP_ROT90;
  186. else if (!strcasecmp(argv[i], "-rot180"))
  187. xform.op = TJXOP_ROT180;
  188. else if (!strcasecmp(argv[i], "-rot270"))
  189. xform.op = TJXOP_ROT270;
  190. else if (!strcasecmp(argv[i], "-custom"))
  191. xform.customFilter = customFilter;
  192. else if (!strncasecmp(argv[i], "-c", 2) && i < argc - 1) {
  193. if (sscanf(argv[++i], "%dx%d+%d+%d", &xform.r.w, &xform.r.h, &xform.r.x,
  194. &xform.r.y) < 4 ||
  195. xform.r.x < 0 || xform.r.y < 0 || xform.r.w < 1 || xform.r.h < 1)
  196. usage(argv[0]);
  197. xform.options |= TJXOPT_CROP;
  198. } else if (!strcasecmp(argv[i], "-fastupsample")) {
  199. printf("Using fast upsampling code\n");
  200. flags |= TJFLAG_FASTUPSAMPLE;
  201. } else if (!strcasecmp(argv[i], "-fastdct")) {
  202. printf("Using fastest DCT/IDCT algorithm\n");
  203. flags |= TJFLAG_FASTDCT;
  204. } else if (!strcasecmp(argv[i], "-accuratedct")) {
  205. printf("Using most accurate DCT/IDCT algorithm\n");
  206. flags |= TJFLAG_ACCURATEDCT;
  207. } else usage(argv[0]);
  208. }
  209. /* Determine input and output image formats based on file extensions. */
  210. inFormat = strrchr(argv[1], '.');
  211. outFormat = strrchr(argv[2], '.');
  212. if (inFormat == NULL || outFormat == NULL || strlen(inFormat) < 2 ||
  213. strlen(outFormat) < 2)
  214. usage(argv[0]);
  215. inFormat = &inFormat[1];
  216. outFormat = &outFormat[1];
  217. if (!strcasecmp(inFormat, "jpg")) {
  218. /* Input image is a JPEG image. Decompress and/or transform it. */
  219. long size;
  220. int inSubsamp, inColorspace;
  221. int doTransform = (xform.op != TJXOP_NONE || xform.options != 0 ||
  222. xform.customFilter != NULL);
  223. unsigned long jpegSize;
  224. /* Read the JPEG file into memory. */
  225. if ((jpegFile = fopen(argv[1], "rb")) == NULL)
  226. THROW_UNIX("opening input file");
  227. if (fseek(jpegFile, 0, SEEK_END) < 0 || ((size = ftell(jpegFile)) < 0) ||
  228. fseek(jpegFile, 0, SEEK_SET) < 0)
  229. THROW_UNIX("determining input file size");
  230. if (size == 0)
  231. THROW("determining input file size", "Input file contains no data");
  232. jpegSize = (unsigned long)size;
  233. if ((jpegBuf = (unsigned char *)tjAlloc(jpegSize)) == NULL)
  234. THROW_UNIX("allocating JPEG buffer");
  235. if (fread(jpegBuf, jpegSize, 1, jpegFile) < 1)
  236. THROW_UNIX("reading input file");
  237. fclose(jpegFile); jpegFile = NULL;
  238. if (doTransform) {
  239. /* Transform it. */
  240. unsigned char *dstBuf = NULL; /* Dynamically allocate the JPEG buffer */
  241. unsigned long dstSize = 0;
  242. if ((tjInstance = tjInitTransform()) == NULL)
  243. THROW_TJ("initializing transformer");
  244. xform.options |= TJXOPT_TRIM;
  245. if (tjTransform(tjInstance, jpegBuf, jpegSize, 1, &dstBuf, &dstSize,
  246. &xform, flags) < 0)
  247. THROW_TJ("transforming input image");
  248. tjFree(jpegBuf);
  249. jpegBuf = dstBuf;
  250. jpegSize = dstSize;
  251. } else {
  252. if ((tjInstance = tjInitDecompress()) == NULL)
  253. THROW_TJ("initializing decompressor");
  254. }
  255. if (tjDecompressHeader3(tjInstance, jpegBuf, jpegSize, &width, &height,
  256. &inSubsamp, &inColorspace) < 0)
  257. THROW_TJ("reading JPEG header");
  258. printf("%s Image: %d x %d pixels, %s subsampling, %s colorspace\n",
  259. (doTransform ? "Transformed" : "Input"), width, height,
  260. subsampName[inSubsamp], colorspaceName[inColorspace]);
  261. if (!strcasecmp(outFormat, "jpg") && doTransform &&
  262. scalingFactor.num == 1 && scalingFactor.denom == 1 && outSubsamp < 0 &&
  263. outQual < 0) {
  264. /* Input image has been transformed, and no re-compression options
  265. have been selected. Write the transformed image to disk and exit. */
  266. if ((jpegFile = fopen(argv[2], "wb")) == NULL)
  267. THROW_UNIX("opening output file");
  268. if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
  269. THROW_UNIX("writing output file");
  270. fclose(jpegFile); jpegFile = NULL;
  271. goto bailout;
  272. }
  273. /* Scaling and/or a non-JPEG output image format and/or compression options
  274. have been selected, so we need to decompress the input/transformed
  275. image. */
  276. width = TJSCALED(width, scalingFactor);
  277. height = TJSCALED(height, scalingFactor);
  278. if (outSubsamp < 0)
  279. outSubsamp = inSubsamp;
  280. pixelFormat = TJPF_BGRX;
  281. if ((imgBuf = (unsigned char *)tjAlloc(width * height *
  282. tjPixelSize[pixelFormat])) == NULL)
  283. THROW_UNIX("allocating uncompressed image buffer");
  284. if (tjDecompress2(tjInstance, jpegBuf, jpegSize, imgBuf, width, 0, height,
  285. pixelFormat, flags) < 0)
  286. THROW_TJ("decompressing JPEG image");
  287. tjFree(jpegBuf); jpegBuf = NULL;
  288. tjDestroy(tjInstance); tjInstance = NULL;
  289. } else {
  290. /* Input image is not a JPEG image. Load it into memory. */
  291. if ((imgBuf = tjLoadImage(argv[1], &width, 1, &height, &pixelFormat,
  292. 0)) == NULL)
  293. THROW_TJ("loading input image");
  294. if (outSubsamp < 0) {
  295. if (pixelFormat == TJPF_GRAY)
  296. outSubsamp = TJSAMP_GRAY;
  297. else
  298. outSubsamp = TJSAMP_444;
  299. }
  300. printf("Input Image: %d x %d pixels\n", width, height);
  301. }
  302. printf("Output Image (%s): %d x %d pixels", outFormat, width, height);
  303. if (!strcasecmp(outFormat, "jpg")) {
  304. /* Output image format is JPEG. Compress the uncompressed image. */
  305. unsigned long jpegSize = 0;
  306. jpegBuf = NULL; /* Dynamically allocate the JPEG buffer */
  307. if (outQual < 0)
  308. outQual = DEFAULT_QUALITY;
  309. printf(", %s subsampling, quality = %d\n", subsampName[outSubsamp],
  310. outQual);
  311. if ((tjInstance = tjInitCompress()) == NULL)
  312. THROW_TJ("initializing compressor");
  313. if (tjCompress2(tjInstance, imgBuf, width, 0, height, pixelFormat,
  314. &jpegBuf, &jpegSize, outSubsamp, outQual, flags) < 0)
  315. THROW_TJ("compressing image");
  316. tjDestroy(tjInstance); tjInstance = NULL;
  317. /* Write the JPEG image to disk. */
  318. if ((jpegFile = fopen(argv[2], "wb")) == NULL)
  319. THROW_UNIX("opening output file");
  320. if (fwrite(jpegBuf, jpegSize, 1, jpegFile) < 1)
  321. THROW_UNIX("writing output file");
  322. tjDestroy(tjInstance); tjInstance = NULL;
  323. fclose(jpegFile); jpegFile = NULL;
  324. tjFree(jpegBuf); jpegBuf = NULL;
  325. } else {
  326. /* Output image format is not JPEG. Save the uncompressed image
  327. directly to disk. */
  328. printf("\n");
  329. if (tjSaveImage(argv[2], imgBuf, width, 0, height, pixelFormat, 0) < 0)
  330. THROW_TJ("saving output image");
  331. }
  332. bailout:
  333. tjFree(imgBuf);
  334. if (tjInstance) tjDestroy(tjInstance);
  335. tjFree(jpegBuf);
  336. if (jpegFile) fclose(jpegFile);
  337. return retval;
  338. }