home *** CD-ROM | disk | FTP | other *** search
/ ftp.hitl.washington.edu / ftp.hitl.washington.edu.tar / ftp.hitl.washington.edu / pub / people / habib / kodak / read_jpg.c < prev    next >
C/C++ Source or Header  |  2000-04-18  |  19KB  |  520 lines

  1. /*
  2.  * example.c
  3.  *
  4.  * This file illustrates how to use the IJG code as a subroutine library
  5.  * to read or write JPEG image files.  You should look at this code in
  6.  * conjunction with the documentation file libjpeg.doc.
  7.  *
  8.  * This code will not do anything useful as-is, but it may be helpful as a
  9.  * skeleton for constructing routines that call the JPEG library.  
  10.  *
  11.  * We present these routines in the same coding style used in the JPEG code
  12.  * (ANSI function definitions, etc); but you are of course free to code your
  13.  * routines in a different style if you prefer.
  14.  */
  15.  
  16. #include <stdio.h>
  17. #include <malloc.h>
  18.  
  19.  /*
  20.  * Include file for users of JPEG library.
  21.  * You will need to have included system headers that define at least
  22.  * the typedefs FILE and size_t before you can include jpeglib.h.
  23.  * (stdio.h is sufficient on ANSI-conforming systems.)
  24.  * You may also wish to include "jerror.h".
  25.  */
  26.  
  27. #include "./jpeglib.h"
  28.  
  29. /*
  30.  * <setjmp.h> is used for the optional error recovery mechanism shown in
  31.  * the second part of the example.
  32.  */
  33.  
  34. #include <setjmp.h>
  35.  
  36.  
  37.  
  38. /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
  39.  
  40. /* This half of the example shows how to feed data into the JPEG compressor.
  41.  * We present a minimal version that does not worry about refinements such
  42.  * as error recovery (the JPEG code will just exit() if it gets an error).
  43.  */
  44.  
  45.  
  46. /*
  47.  * IMAGE DATA FORMATS:
  48.  *
  49.  * The standard input image format is a rectangular array of pixels, with
  50.  * each pixel having the same number of "component" values (color channels).
  51.  * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
  52.  * If you are working with color data, then the color values for each pixel
  53.  * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
  54.  * RGB color.
  55.  *
  56.  * For this example, we'll assume that this data structure matches the way
  57.  * our application has stored the image in memory, so we can just pass a
  58.  * pointer to our image buffer.  In particular, let's say that the image is
  59.  * RGB color and is described by:
  60.  */
  61.  
  62. JSAMPLE * image_buffer;    /* Points to large array of R,G,B-order data */
  63. int image_height;    /* Number of rows in image */
  64. int image_width;        /* Number of columns in image */
  65.  
  66.  
  67. /*
  68.  * Sample routine for JPEG compression.  We assume that the target file name
  69.  * and a compression quality factor are passed in.
  70.  */
  71.  
  72. write_JPEG_file (char * filename, int quality)
  73. {
  74.   /* This struct contains the JPEG compression parameters and pointers to
  75.    * working space (which is allocated as needed by the JPEG library).
  76.    * It is possible to have several such structures, representing multiple
  77.    * compression/decompression processes, in existence at once.  We refer
  78.    * to any one struct (and its associated working data) as a "JPEG object".
  79.    */
  80.   struct jpeg_compress_struct cinfo;
  81.   /* This struct represents a JPEG error handler.  It is declared separately
  82.    * because applications often want to supply a specialized error handler
  83.    * (see the second half of this file for an example).  But here we just
  84.    * take the easy way out and use the standard error handler, which will
  85.    * print a message on stderr and call exit() if compression fails.
  86.    * Note that this struct must live as long as the main JPEG parameter
  87.    * struct, to avoid dangling-pointer problems.
  88.    */
  89.   struct jpeg_error_mgr jerr;
  90.   /* More stuff */
  91.   FILE * outfile;        /* target file */
  92.   JSAMPROW row_pointer[1];    /* pointer to JSAMPLE row[s] */
  93.   int row_stride;        /* physical row width in image buffer */
  94.  
  95.   /* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  96.    * requires it in order to write binary files. */
  97.   if ((outfile = fopen(filename, "wb")) == NULL) {
  98.     fprintf(stderr, "Je ne peux pas ouvrir %s\n", filename);
  99.     printf ("exit, fichier non lu \n");
  100.     return 1;
  101.   }
  102.  
  103.   /* Step 1: allocate and initialize JPEG compression object */
  104.  
  105.   /* We have to set up the error handler first, in case the initialization
  106.    * step fails.  (Unlikely, but it could happen if you are out of memory.)
  107.    * This routine fills in the contents of struct jerr, and returns jerr's
  108.    * address which we place into the link field in cinfo.
  109.    */
  110.   cinfo.err = jpeg_std_error(&jerr);
  111.   /* Now we can initialize the JPEG compression object. */
  112.   jpeg_create_compress(&cinfo);
  113.  
  114.   /* Step 2: specify data destination (eg, a file) */
  115.   /* Note: steps 2 and 3 can be done in either order. */
  116.  
  117.   /* Here we use the library-supplied code to send compressed data to a
  118.    * stdio stream.  You can also write your own code to do something else.
  119.    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  120.    * requires it in order to write binary files.
  121.    */
  122.   jpeg_stdio_dest(&cinfo, outfile);
  123.  
  124.   /* Step 3: set parameters for compression */
  125.  
  126.   /* First we supply a description of the input image.
  127.    * Four fields of the cinfo struct must be filled in:
  128.    */
  129.   cinfo.image_width = image_width;     /* image width and height, in pixels */
  130.   cinfo.image_height = image_height;
  131.   cinfo.input_components = 3;        /* # of color components per pixel */
  132.   cinfo.in_color_space = JCS_RGB;     /* colorspace of input image */
  133.   /* Now use the library's routine to set default compression parameters.
  134.    * (You must set at least cinfo.in_color_space before calling this,
  135.    * since the defaults depend on the source color space.)
  136.    */
  137.   jpeg_set_defaults(&cinfo);
  138.   /* Now you can set any non-default parameters you wish to.
  139.    * Here we just illustrate the use of quality (quantization table) scaling:
  140.    */
  141.   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
  142.  
  143.   /* Step 4: Start compressor */
  144.  
  145.   /* TRUE ensures that we will write a complete interchange-JPEG file.
  146.    * Pass TRUE unless you are very sure of what you're doing.
  147.    */
  148.   jpeg_start_compress(&cinfo, TRUE);
  149.  
  150.   /* Step 5: while (scan lines remain to be written) */
  151.   /*           jpeg_write_scanlines(...); */
  152.  
  153.   /* Here we use the library's state variable cinfo.next_scanline as the
  154.    * loop counter, so that we don't have to keep track ourselves.
  155.    * To keep things simple, we pass one scanline per call; you can pass
  156.    * more if you wish, though.
  157.    */
  158.   row_stride = image_width * 3;    /* JSAMPLEs per row in image_buffer */
  159.  
  160.   while (cinfo.next_scanline < cinfo.image_height) {
  161.     /* jpeg_write_scanlines expects an array of pointers to scanlines.
  162.      * Here the array is only one element long, but you could pass
  163.      * more than one scanline at a time if that's more convenient.
  164.      */
  165.     row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
  166.     (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
  167.   }
  168.  
  169.   /* Step 6: Finish compression */
  170.  
  171.   jpeg_finish_compress(&cinfo);
  172.   /* After finish_compress, we can close the output file. */
  173.   fclose(outfile);
  174.  
  175.   /* Step 7: release JPEG compression object */
  176.  
  177.   /* This is an important step since it will release a good deal of memory. */
  178.   jpeg_destroy_compress(&cinfo);
  179.  
  180.   /* And we're done! */
  181. }
  182.  
  183.  
  184. /*
  185.  * SOME FINE POINTS:
  186.  *
  187.  * In the above loop, we ignored the return value of jpeg_write_scanlines,
  188.  * which is the number of scanlines actually written.  We could get away
  189.  * with this because we were only relying on the value of cinfo.next_scanline,
  190.  * which will be incremented correctly.  If you maintain additional loop
  191.  * variables then you should be careful to increment them properly.
  192.  * Actually, for output to a stdio stream you needn't worry, because
  193.  * then jpeg_write_scanlines will write all the lines passed (or else exit
  194.  * with a fatal error).  Partial writes can only occur if you use a data
  195.  * destination module that can demand suspension of the compressor.
  196.  * (If you don't know what that's for, you don't need it.)
  197.  *
  198.  * If the compressor requires full-image buffers (for entropy-coding
  199.  * optimization or a multi-scan JPEG file), it will create temporary
  200.  * files for anything that doesn't fit within the maximum-memory setting.
  201.  * (Note that temp files are NOT needed if you use the default parameters.)
  202.  * On some systems you may need to set up a signal handler to ensure that
  203.  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
  204.  *
  205.  * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
  206.  * files to be compatible with everyone else's.  If you cannot readily read
  207.  * your data in that order, you'll need an intermediate array to hold the
  208.  * image.  See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
  209.  * source data using the JPEG code's internal virtual-array mechanisms.
  210.  */
  211.  
  212.  
  213.  
  214. /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
  215.  
  216. /* This half of the example shows how to read data from the JPEG decompressor.
  217.  * It's a bit more refined than the above, in that we show:
  218.  *   (a) how to modify the JPEG library's standard error-reporting behavior;
  219.  *   (b) how to allocate workspace using the library's memory manager.
  220.  *
  221.  * Just to make this example a little different from the first one, we'll
  222.  * assume that we do not intend to put the whole image into an in-memory
  223.  * buffer, but to send it line-by-line someplace else.  We need a one-
  224.  * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
  225.  * memory manager allocate it for us.  This approach is actually quite useful
  226.  * because we don't need to remember to deallocate the buffer separately: it
  227.  * will go away automatically when the JPEG object is cleaned up.
  228.  */
  229.  
  230.  
  231. /*
  232.  * ERROR HANDLING:
  233.  *
  234.  * The JPEG library's standard error handler (jerror.c) is divided into
  235.  * several "methods" which you can override individually.  This lets you
  236.  * adjust the behavior without duplicating a lot of code, which you might
  237.  * have to update with each future release.
  238.  *
  239.  * Our example here shows how to override the "error_exit" method so that
  240.  * control is returned to the library's caller when a fatal error occurs,
  241.  * rather than calling exit() as the standard error_exit method does.
  242.  *
  243.  * We use C's setjmp/longjmp facility to return control.  This means that the
  244.  * routine which calls the JPEG library must first execute a setjmp() call to
  245.  * establish the return point.  We want the replacement error_exit to do a
  246.  * longjmp().  But we need to make the setjmp buffer accessible to the
  247.  * error_exit routine.  To do this, we make a private extension of the
  248.  * standard JPEG error handler object.  (If we were using C++, we'd say we
  249.  * were making a subclass of the regular error handler.)
  250.  *
  251.  * Here's the extended error handler struct:
  252.  */
  253.  
  254. struct my_error_mgr {
  255.   struct jpeg_error_mgr pub;    /* "public" fields */
  256.  
  257.   jmp_buf setjmp_buffer;    /* for return to caller */
  258. };
  259.  
  260. typedef struct my_error_mgr * my_error_ptr;
  261.  
  262. /*
  263.  * Here's the routine that will replace the standard error_exit method:
  264.  */
  265.  
  266. void 
  267. my_error_exit (j_common_ptr cinfo)
  268. {
  269.   /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
  270.   my_error_ptr myerr = (my_error_ptr) cinfo->err;
  271.  
  272.   /* Always display the message. */
  273.   /* We could postpone this until after returning, if we chose. */
  274.   (*cinfo->err->output_message) (cinfo);
  275.  
  276.   /* Return control to the setjmp point */
  277.   longjmp(myerr->setjmp_buffer, 1);
  278. }
  279.  
  280.  
  281. /*
  282.  * Sample routine for JPEG decompression.  We assume that the source file name
  283.  * is passed in.  We want to return 1 on success, 0 on error.
  284.  */
  285.  
  286.  
  287. unsigned char *
  288. read_JPEG_file (char * f_hab,char * filename, unsigned char *image,int *im_width, int *im_height)
  289. {
  290.   /* This struct contains the JPEG decompression parameters and pointers to
  291.    * working space (which is allocated as needed by the JPEG library).
  292.    */
  293.   struct jpeg_decompress_struct cinfo;
  294.   int i, j;
  295.   FILE *f;
  296.   /* We use our private extension JPEG error handler.
  297.    * Note that this struct must live as long as the main JPEG parameter
  298.    * struct, to avoid dangling-pointer problems.
  299.    */
  300.   struct my_error_mgr jerr;
  301.   /* More stuff */
  302.   int lgn_num = 0;
  303.   FILE * infile;        /* source file */
  304.   JSAMPARRAY buffer;        /* Output row buffer */
  305.   int row_stride;        /* physical row width in output buffer */
  306.  
  307.   /* initialize the im_width, im_height in case the file cannot be opened */
  308.   im_width[0] = 2;
  309.   im_height[0] = 4;
  310.  
  311.   /* In this example we want to open the input file before doing anything else,
  312.    * so that the setjmp() error recovery below can assume the file is open.
  313.    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
  314.    * requires it in order to read binary files.
  315.    */
  316.  
  317.   if ((infile = fopen(filename, "rb")) == NULL) {
  318.     fprintf(stderr, "je ne peux pas open %s\n", filename);
  319.     if ((image = (unsigned char *)malloc (im_width[0]*im_height[0]*3) ) == NULL){
  320.       printf ("Malloc error here 9384993838 \n" );
  321.       return 0;
  322.     }
  323.     image [0]  = image[3]  = image[6] = image [9] = image[12] = image[15] = 230;
  324.     image [18] = image[21] = 230;
  325.     return 0;
  326.   }
  327.  
  328.   /* Step 1: allocate and initialize JPEG decompression object */
  329.  
  330.   /* We set up the normal JPEG error routines, then override error_exit. */
  331.   cinfo.err = jpeg_std_error(&jerr.pub);
  332.   jerr.pub.error_exit = my_error_exit;
  333.   /* Establish the setjmp return context for my_error_exit to use. */
  334.   if (setjmp(jerr.setjmp_buffer)) {
  335.     /* If we get here, the JPEG code has signaled an error.
  336.      * We need to clean up the JPEG object, close the input file, and return.
  337.      */
  338.     jpeg_destroy_decompress(&cinfo);
  339.     fclose(infile);
  340.     return 0;
  341.   }
  342.   /* Now we can initialize the JPEG decompression object. */
  343.   jpeg_create_decompress(&cinfo);
  344.  
  345.   /* Step 2: specify data source (eg, a file) */
  346.  
  347.   jpeg_stdio_src(&cinfo, infile);
  348.  
  349.   /* Step 3: read file parameters with jpeg_read_header() */
  350.  
  351.   (void) jpeg_read_header(&cinfo, TRUE);
  352.   /* We can ignore the return value from jpeg_read_header since
  353.    *   (a) suspension is not possible with the stdio data source, and
  354.    *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
  355.    * See libjpeg.doc for more info.
  356.    */
  357.  
  358.   /* Step 4: set parameters for decompression */
  359.  
  360.   /* In this example, we don't need to change any of the defaults set by
  361.    * jpeg_read_header(), so we do nothing here.
  362.    */
  363.  
  364.   /* Step 5: Start decompressor */
  365.  
  366.   (void) jpeg_start_decompress(&cinfo);
  367.   /* We can ignore the return value since suspension is not possible
  368.    * with the stdio data source.
  369.    */
  370.  
  371.   /* We may need to do some setup of our own at this point before reading
  372.    * the data.  After jpeg_start_decompress() we have the correct scaled
  373.    * output image dimensions available, as well as the output colormap
  374.    * if we asked for color quantization.
  375.    * In this example, we need to make an output work buffer of the right size.
  376.    */ 
  377.   /* JSAMPLEs per row in output buffer */
  378.   row_stride = cinfo.output_width * cinfo.output_components;
  379.   
  380.   /* Make a one-row-high sample array that will go away when done with image */
  381.   buffer = (*cinfo.mem->alloc_sarray)
  382.         ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
  383.  
  384.   /* Step 6: while (scan lines remain to be read) */
  385.   /*           jpeg_read_scanlines(...); */
  386.  
  387.   /* Here we use the library's state variable cinfo.output_scanline as the
  388.    * loop counter, so that we don't have to keep track ourselves.
  389.    */
  390.   /* Habib's Code : Allocate my image array buffer. */
  391.   im_width[0] = row_stride /3;
  392.   im_height[0] = cinfo.output_height;
  393.   image = (unsigned char *)calloc( im_height[0]*im_width[0]*3, sizeof( char ) );
  394.  
  395.   while (cinfo.output_scanline < cinfo.output_height) {
  396.     /* jpeg_read_scanlines expects an array of pointers to scanlines.
  397.      * Here the array is only one element long, but you could ask for
  398.      * more than one scanline at a time if that's more convenient.
  399.      */
  400.     (void) jpeg_read_scanlines(&cinfo, buffer, 1);
  401.     /* Assume put_scanline_someplace wants a pointer and sample count. */
  402.     /* put_scanline_someplace(buffer[0], row_stride); */
  403.     for (i = 0; i< 3* im_width[0]; i++)
  404.             image[(im_height[0]-1-lgn_num)*3*im_width[0]+i] = buffer[0][i]; 
  405.             /*printf ("%d ", buffer[0][3*i+j]);*/
  406.         
  407.     
  408.     lgn_num = lgn_num + 1;
  409.   }
  410.  
  411.   /* Step 7: Finish decompression */
  412.  
  413.   (void) jpeg_finish_decompress(&cinfo);
  414.   /* We can ignore the return value since suspension is not possible
  415.    * with the stdio data source.
  416.    */
  417.  
  418.   /* Step 8: Release JPEG decompression object */
  419.  
  420.   /* This is an important step since it will release a good deal of memory. */
  421.   jpeg_destroy_decompress(&cinfo);
  422.  
  423.   /* After finish_decompress, we can close the input file.
  424.    * Here we postpone it until after no more JPEG errors are possible,
  425.    * so as to simplify the setjmp error logic above.  (Actually, I don't
  426.    * think that jpeg_destroy can do an error exit, but why assume anything...)
  427.    */
  428.   fclose(infile);
  429.  
  430.   /* At this point you may want to check to see whether any corrupt-data
  431.    * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
  432.    */
  433.  
  434.   /* And we're done! */
  435.   /*if ((f = fopen(f_hab,"wb")) == NULL){
  436.     printf ("f_hab not opened\n");
  437.     return 0;
  438.   }
  439.   fwrite (im_width , sizeof(int), 1,f);
  440.   fwrite (im_height, sizeof(int), 1,f);
  441.   fwrite (image, sizeof(unsigned char), im_width[0]*im_height[0]*3,f);
  442.   fclose (f); */
  443.   return image;
  444. }
  445.  
  446. /*
  447.  * SOME FINE POINTS:
  448.  *
  449.  * In the above code, we ignored the return value of jpeg_read_scanlines,
  450.  * which is the number of scanlines actually read.  We could get away with
  451.  * this because we asked for only one line at a time and we weren't using
  452.  * a suspending data source.  See libjpeg.doc for more info.
  453.  *
  454.  * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
  455.  * we should have done it beforehand to ensure that the space would be
  456.  * counted against the JPEG max_memory setting.  In some systems the above
  457.  * code would risk an out-of-memory error.  However, in general we don't
  458.  * know the output image dimensions before jpeg_start_decompress(), unless we
  459.  * call jpeg_calc_output_dimensions().  See libjpeg.doc for more about this.
  460.  *
  461.  * Scanlines are returned in the same order as they appear in the JPEG file,
  462.  * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
  463.  * you can use one of the virtual arrays provided by the JPEG memory manager
  464.  * to invert the data.  See wrbmp.c for an example.
  465.  *
  466.  * As with compression, some operating modes may require temporary files.
  467.  * On some systems you may need to set up a signal handler to ensure that
  468.  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
  469.  */
  470.  
  471.  /*
  472.  main ()
  473.  {
  474.      unsigned char ***image;
  475.      int im_width[1];
  476.      int im_height[1];
  477.      int i, j,k;
  478.      image = read_JPEG_file ("D:\\C\\jpeg-6b\\Read_Jpeg\\tt.jpg", image, im_width, im_height);
  479.     
  480.      /* for (i= 0; i< 20; i++)
  481.          for (j=0; j< im_height[0]; j++)
  482.          {
  483.              image[i][j][0] = 255;
  484.              image[i][j][1] = 0;
  485.              image[i][j][2] = 0;
  486.          }
  487.      for (i= 21; i< 70; i++)
  488.          for (j=0; j< im_height[0]; j++)
  489.          {
  490.              image[i][j][0] = 0;
  491.              image[i][j][1] = 250;
  492.              image[i][j][2] = 0;
  493.          }
  494.      for (i= 71; i< 100; i++)
  495.          for (j=0; j< im_height[0]; j++)
  496.          {
  497.              image[i][j][0] = 0;
  498.              image[i][j][1] = 0;
  499.              image[i][j][2] = 250;
  500.          } */
  501.  
  502.      /* fill image_buffer */
  503. /*     image_buffer = malloc (im_height[0]*im_width[0]*3);
  504.      for (i=0; i< im_height[0]; i++)
  505.          for (j=0; j<im_width[0]; j++)
  506.              for (k=0;k<3; k++)
  507.                  image_buffer[k+j*3+i*image_height] = image[i][j][k];
  508.  
  509.      image_height = im_height[0];    /* Number of rows in image    */
  510. /*   image_width  = im_width [0];    /* Number of columns in image */
  511.      
  512. /*     write_JPEG_file ("majid.jpg",0);
  513.      free (image_buffer);
  514.      getchar();
  515.  
  516.      
  517.  } */
  518.  
  519.  
  520.