jpeg.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /****************************************************************************
  2. jpeg.c - read and write jpeg images using libjpeg routines
  3. Copyright (C) 2002 Hari Nair <hari@alumni.caltech.edu>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  15. ****************************************************************************/
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <jpeglib.h>
  20. int
  21. read_jpeg(const char *filename, int *width, int *height, unsigned char **rgb)
  22. {
  23. struct jpeg_decompress_struct cinfo;
  24. struct jpeg_error_mgr jerr;
  25. unsigned char *ptr = NULL;
  26. unsigned int i, ipos;
  27. FILE *infile = fopen(filename, "rb");
  28. cinfo.err = jpeg_std_error(&jerr);
  29. jpeg_create_decompress(&cinfo);
  30. jpeg_stdio_src(&cinfo, infile);
  31. jpeg_read_header(&cinfo, TRUE);
  32. jpeg_start_decompress(&cinfo);
  33. *width = cinfo.output_width;
  34. *height = cinfo.output_height;
  35. rgb[0] = malloc(3 * cinfo.output_width * cinfo.output_height);
  36. if (rgb[0] == NULL)
  37. {
  38. fprintf(stderr, "Can't allocate memory for JPEG file.\n");
  39. fclose(infile);
  40. return(0);
  41. }
  42. if (cinfo.output_components == 3)
  43. {
  44. ptr = rgb[0];
  45. while (cinfo.output_scanline < cinfo.output_height)
  46. {
  47. jpeg_read_scanlines(&cinfo, &ptr, 1);
  48. ptr += 3 * cinfo.output_width;
  49. }
  50. }
  51. else if (cinfo.output_components == 1)
  52. {
  53. ptr = malloc(cinfo.output_width);
  54. if (ptr == NULL)
  55. {
  56. fprintf(stderr, "Can't allocate memory for JPEG file.\n");
  57. fclose(infile);
  58. return(0);
  59. }
  60. ipos = 0;
  61. while (cinfo.output_scanline < cinfo.output_height)
  62. {
  63. jpeg_read_scanlines(&cinfo, &ptr, 1);
  64. for (i = 0; i < cinfo.output_width; i++)
  65. {
  66. memset(rgb[0] + ipos, ptr[i], 3);
  67. ipos += 3;
  68. }
  69. }
  70. free(ptr);
  71. }
  72. jpeg_finish_decompress(&cinfo);
  73. jpeg_destroy_decompress(&cinfo);
  74. fclose(infile);
  75. return(1);
  76. }