示例#1
0
int
main(void)
{
	gdImagePtr im;
	int white, black, r;
	gdPointPtr points;

	im = gdImageCreate(100, 100);
	if (!im) exit(EXIT_FAILURE);
	white = gdImageColorAllocate(im, 0xff, 0xff, 0xff);
	black = gdImageColorAllocate(im, 0, 0, 0);
	gdImageFilledRectangle(im, 0, 0, 99, 99, white);
	points = (gdPointPtr)gdCalloc(3, sizeof(gdPoint));
	if (!points) {
		gdImageDestroy(im);
		exit(EXIT_FAILURE);
	}
	points[0].x = 10;
	points[0].y = 10;
	points[1].x = 50;
	points[1].y = 70;
	points[2].x = 90;
	points[2].y = 30;
	gdImageOpenPolygon(im, points, 3, black);
	r = gdAssertImageEqualsToFile(GDTEST_TOP_DIR "/gdimageopenpolygon/gdimageopenpolygon3.png", im);
	gdFree(points);
	gdImageDestroy(im);
	if (!r) exit(EXIT_FAILURE);
	return EXIT_SUCCESS;
}
示例#2
0
static void
_gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
{
  int ncx, ncy, cx, cy;
  int x, y, ylo, yhi, xlo, xhi;
  int chunkLen;
  int chunkNum = 0;
  char *chunkData = NULL;	/* So we can gdFree it with impunity. */
  char *compData = NULL;	/* So we can gdFree it with impunity. */
  uLongf compLen;
  int idxPos = 0;
  int idxSize;
  t_chunk_info *chunkIdx = NULL;
  int posSave;
  int bytesPerPixel = im->trueColor ? 4 : 1;
  int compMax = 0;

  /*printf("Trying to write GD2 file\n"); */

  /* */
  /* Force fmt to a valid value since we don't return anything. */
  /* */
  if ((fmt != GD2_FMT_RAW) && (fmt != GD2_FMT_COMPRESSED))
    {
      fmt = im->trueColor ? GD2_FMT_TRUECOLOR_COMPRESSED : GD2_FMT_COMPRESSED;
    };
  if (im->trueColor)
    {
      fmt += 2;
    }
  /* */
  /* Make sure chunk size is valid. These are arbitrary values; 64 because it seems */
  /* a little silly to expect performance improvements on a 64x64 bit scale, and  */
  /* 4096 because we buffer one chunk, and a 16MB buffer seems a little large - it may be */
  /* OK for one user, but for another to read it, they require the buffer. */
  /* */
  if (cs == 0)
    {
      cs = GD2_CHUNKSIZE;
    }
  else if (cs < GD2_CHUNKSIZE_MIN)
    {
      cs = GD2_CHUNKSIZE_MIN;
    }
  else if (cs > GD2_CHUNKSIZE_MAX)
    {
      cs = GD2_CHUNKSIZE_MAX;
    };

  /* Work out number of chunks. */
  ncx = im->sx / cs + 1;
  ncy = im->sy / cs + 1;

  /* Write the standard header. */
  _gd2PutHeader (im, out, cs, fmt, ncx, ncy);

  if (gd2_compressed (fmt))
    {
      /* */
      /* Work out size of buffer for compressed data, If CHUNKSIZE is large, */
      /* then these will be large! */
      /* */
      /* The zlib notes say output buffer size should be (input size) * 1.01 * 12 */
      /* - we'll use 1.02 to be paranoid. */
      /* */
      compMax = cs * bytesPerPixel * cs * 1.02 + 12;

      /* */
      /* Allocate the buffers.  */
      /* */
      chunkData = gdCalloc (cs * bytesPerPixel * cs, 1);
			if (!chunkData) {
				goto fail;
			}
      compData = gdCalloc (compMax, 1);
			if (!compData) {
				goto fail;
			}

      /* */
      /* Save the file position of chunk index, and allocate enough space for */
      /* each chunk_info block . */
      /* */
      idxPos = gdTell (out);
      idxSize = ncx * ncy * sizeof (t_chunk_info);
      GD2_DBG (printf ("Index size is %d\n", idxSize));
      gdSeek (out, idxPos + idxSize);

      chunkIdx = gdCalloc (idxSize * sizeof (t_chunk_info), 1);
      if (!chunkIdx) {
        goto fail;
      }
    };

  _gdPutColors (im, out);

  GD2_DBG (printf ("Size: %dx%d\n", im->sx, im->sy));
  GD2_DBG (printf ("Chunks: %dx%d\n", ncx, ncy));

  for (cy = 0; (cy < ncy); cy++)
    {
      for (cx = 0; (cx < ncx); cx++)
	{

	  ylo = cy * cs;
	  yhi = ylo + cs;
	  if (yhi > im->sy)
	    {
	      yhi = im->sy;
	    };

	  GD2_DBG (printf
		   ("Processing Chunk (%dx%d), y from %d to %d\n", cx, cy,
		    ylo, yhi));
	  chunkLen = 0;
	  for (y = ylo; (y < yhi); y++)
	    {

	      /*GD2_DBG(printf("y=%d: ",y)); */

	      xlo = cx * cs;
	      xhi = xlo + cs;
	      if (xhi > im->sx)
		{
		  xhi = im->sx;
		};

	      if (gd2_compressed (fmt))
		{
		  for (x = xlo; x < xhi; x++)
		    {
		      /* 2.0.11: use truecolor pixel array. TBB */
		      /*GD2_DBG(printf("%d...",x)); */
		      if (im->trueColor)
			{
			  int p = im->tpixels[y][x];
			  chunkData[chunkLen++] = gdTrueColorGetAlpha (p);
			  chunkData[chunkLen++] = gdTrueColorGetRed (p);
			  chunkData[chunkLen++] = gdTrueColorGetGreen (p);
			  chunkData[chunkLen++] = gdTrueColorGetBlue (p);
			}
		      else
			{
			  int p = im->pixels[y][x];
			  chunkData[chunkLen++] = p;
			}
		    };
		}
	      else
		{
		  for (x = xlo; x < xhi; x++)
		    {
		      /*GD2_DBG(printf("%d, ",x)); */

		      if (im->trueColor)
			{
			  gdPutInt (im->tpixels[y][x], out);
			}
		      else
			{
			  gdPutC ((unsigned char) im->pixels[y][x], out);
			}
		    };
		};
	      /*GD2_DBG(printf("y=%d done.\n",y)); */
	    };
	  if (gd2_compressed (fmt))
	    {
	      compLen = compMax;
	      if (compress ((unsigned char *)
			    &compData[0], &compLen,
			    (unsigned char *) &chunkData[0],
			    chunkLen) != Z_OK)
		{
		  printf ("Error from compressing\n");
		}
	      else
		{
		  chunkIdx[chunkNum].offset = gdTell (out);
		  chunkIdx[chunkNum++].size = compLen;
		  GD2_DBG (printf
			   ("Chunk %d size %d offset %d\n", chunkNum,
			    chunkIdx[chunkNum - 1].size,
			    chunkIdx[chunkNum - 1].offset));

		  if (gdPutBuf (compData, compLen, out) <= 0)
		    {
			fprintf(stderr, "gd write error\n");
		    };
		};
	    };
	};
    };
  if (gd2_compressed (fmt))
    {
      /* Save the position, write the index, restore position (paranoia). */
      GD2_DBG (printf ("Seeking %d to write index\n", idxPos));
      posSave = gdTell (out);
      gdSeek (out, idxPos);
      GD2_DBG (printf ("Writing index\n"));
      for (x = 0; x < chunkNum; x++)
	{
	  GD2_DBG (printf
		   ("Chunk %d size %d offset %d\n", x, chunkIdx[x].size,
		    chunkIdx[x].offset));
	  gdPutInt (chunkIdx[x].offset, out);
	  gdPutInt (chunkIdx[x].size, out);
	};
      /* We don't use fwrite for *endian reasons. */
      /*fwrite(chunkIdx, sizeof(int)*2, chunkNum, out); */
      gdSeek (out, posSave);
    };

  /*printf("Memory block size is %d\n",gdTell(out)); */
fail:
  GD2_DBG (printf ("Freeing memory\n"));

	if (chunkData) {
		gdFree (chunkData);
	}
	if (compData) {
		gdFree (compData);
	} 
	if (chunkIdx) {
		gdFree (chunkIdx);
	}
  GD2_DBG (printf ("Done\n"));

}
示例#3
0
static int
_gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
	       int *cs, int *vers, int *fmt, int *ncx, int *ncy,
	       t_chunk_info ** chunkIdx)
{
  int i;
  int ch;
  char id[5];
  t_chunk_info *cidx;
  int sidx;
  int nc;

  GD2_DBG (printf ("Reading gd2 header info\n"));

  for (i = 0; i < 4; i++)
    {
      ch = gdGetC (in);
      if (ch == EOF)
	{
	  goto fail1;
	};
      id[i] = ch;
    };
  id[4] = 0;

  GD2_DBG (printf ("Got file code: %s\n", id));

  /* Equiv. of 'magick'.  */
  if (strcmp (id, GD2_ID) != 0)
    {
      GD2_DBG (printf ("Not a valid gd2 file\n"));
      goto fail1;
    };

  /* Version */
  if (gdGetWord (vers, in) != 1)
    {
      goto fail1;
    };
  GD2_DBG (printf ("Version: %d\n", *vers));

  if ((*vers != 1) && (*vers != 2))
    {
      GD2_DBG (printf ("Bad version: %d\n", *vers));
      goto fail1;
    };

  /* Image Size */
  if (!gdGetWord (sx, in))
    {
      GD2_DBG (printf ("Could not get x-size\n"));
      goto fail1;
    }
  if (!gdGetWord (sy, in))
    {
      GD2_DBG (printf ("Could not get y-size\n"));
      goto fail1;
    }
  GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));

  /* Chunk Size (pixels, not bytes!) */
  if (gdGetWord (cs, in) != 1)
    {
      goto fail1;
    };
  GD2_DBG (printf ("ChunkSize: %d\n", *cs));

  if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX))
    {
      GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
      goto fail1;
    };

  /* Data Format */
  if (gdGetWord (fmt, in) != 1)
    {
      goto fail1;
    };
  GD2_DBG (printf ("Format: %d\n", *fmt));

  if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
      (*fmt != GD2_FMT_TRUECOLOR_RAW) &&
      (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED))
    {
      GD2_DBG (printf ("Bad data format: %d\n", *fmt));
      goto fail1;
    };


  /* # of chunks wide */
  if (gdGetWord (ncx, in) != 1)
    {
      goto fail1;
    };
  GD2_DBG (printf ("%d Chunks Wide\n", *ncx));

  /* # of chunks high */
  if (gdGetWord (ncy, in) != 1)
    {
      goto fail1;
    };
  GD2_DBG (printf ("%d Chunks vertically\n", *ncy));

  if (gd2_compressed (*fmt))
    {
      nc = (*ncx) * (*ncy);
      GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
      sidx = sizeof (t_chunk_info) * nc;
      cidx = gdCalloc (sidx, 1);
			if (!cidx) {
				goto fail1;
			}
      for (i = 0; i < nc; i++)
	{
	  if (gdGetInt (&cidx[i].offset, in) != 1)
	    {
	      goto fail1;
	    };
	  if (gdGetInt (&cidx[i].size, in) != 1)
	    {
	      goto fail1;
	    };
	};
      *chunkIdx = cidx;
    };

  GD2_DBG (printf ("gd2 header complete\n"));

  return 1;

fail1:
  return 0;
}
示例#4
0
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
{
  int scx, scy, ecx, ecy, fsx, fsy;
  int nc, ncx, ncy, cs, cx, cy;
  int x, y, ylo, yhi, xlo, xhi;
  int dstart, dpos;
  int i;
  /* 2.0.12: unsigned is correct; fixes problems with color munging.
     Thanks to Steven Brown. */
  unsigned int ch;
  int vers, fmt;
  t_chunk_info *chunkIdx = NULL;
  unsigned char *chunkBuf = NULL;
  int chunkNum;
  int chunkMax = 0;
  uLongf chunkLen;
  int chunkPos = 0;
  int compMax;
  char *compBuf = NULL;

  gdImagePtr im;

  /* */
  /* The next few lines are basically copied from gd2CreateFromFile */
  /* - we change the file size, so don't want to use the code directly. */
  /*   but we do need to know the file size. */
  /* */
  if (_gd2GetHeader (in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx)
      != 1)
    {
      goto fail1;
    }

  GD2_DBG (printf ("File size is %dx%d\n", fsx, fsy));

  /* This is the difference - make a file based on size of chunks. */
  if (gd2_truecolor (fmt))
    {
      im = gdImageCreateTrueColor (w, h);
    }
  else
    {
      im = gdImageCreate (w, h);
    }
  if (im == NULL)
    {
      goto fail1;
    };

  if (!_gdGetColors (in, im, vers == 2))
    {
      goto fail2;
    }
  GD2_DBG (printf ("Image palette completed: %d colours\n", im->colorsTotal));

  /* Process the header info */
  nc = ncx * ncy;

  if (gd2_compressed (fmt))
    {
      /* Find the maximum compressed chunk size. */
      compMax = 0;
      for (i = 0; (i < nc); i++)
	{
	  if (chunkIdx[i].size > compMax)
	    {
	      compMax = chunkIdx[i].size;
	    };
	};
      compMax++;

      if (im->trueColor)
	{
	  chunkMax = cs * cs * 4;
	}
      else
	{
	  chunkMax = cs * cs;
	}
      chunkBuf = gdCalloc (chunkMax, 1);
			if (!chunkBuf) {
				goto fail2;
			}
      compBuf = gdCalloc (compMax, 1);
			if (!compBuf) {
				goto fail2;
			}

    };

/*      Don't bother with this... */
/*      if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/*              goto fail2; */
/*      }; */


  /* Work out start/end chunks */
  scx = srcx / cs;
  scy = srcy / cs;
  if (scx < 0)
    {
      scx = 0;
    };
  if (scy < 0)
    {
      scy = 0;
    };

  ecx = (srcx + w) / cs;
  ecy = (srcy + h) / cs;
  if (ecx >= ncx)
    {
      ecx = ncx - 1;
    };
  if (ecy >= ncy)
    {
      ecy = ncy - 1;
    };

  /* Remember file position of image data. */
  dstart = gdTell (in);
  GD2_DBG (printf ("Data starts at %d\n", dstart));

  /* Loop through the chunks. */
  for (cy = scy; (cy <= ecy); cy++)
    {

      ylo = cy * cs;
      yhi = ylo + cs;
      if (yhi > fsy)
	{
	  yhi = fsy;
	};

      for (cx = scx; (cx <= ecx); cx++)
	{

	  xlo = cx * cs;
	  xhi = xlo + cs;
	  if (xhi > fsx)
	    {
	      xhi = fsx;
	    };

	  GD2_DBG (printf
		   ("Processing Chunk (%d, %d), from %d to %d\n", cx, cy, ylo,
		    yhi));

	  if (!gd2_compressed (fmt))
	    {
	      GD2_DBG (printf ("Using raw format data\n"));
	      if (im->trueColor)
		{
		  dpos =
		    (cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) +
		    dstart;
		}
	      else
		{
		  dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart;
		}
	      /* gd 2.0.11: gdSeek returns TRUE on success, not 0.
	         Longstanding bug. 01/16/03 */
	      if (!gdSeek (in, dpos))
		{
		  fprintf (stderr, "Seek error\n");
		  goto fail2;
		};
	      GD2_DBG (printf
		       ("Reading (%d, %d) from position %d\n", cx, cy,
			dpos - dstart));
	    }
	  else
	    {
	      chunkNum = cx + cy * ncx;

	      chunkLen = chunkMax;
	      if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
				  compBuf,
				  chunkIdx[chunkNum].size,
				  (char *) chunkBuf, &chunkLen, in))
		{
		  printf ("Error reading comproessed chunk\n");
		  goto fail2;
		};
	      chunkPos = 0;
	      GD2_DBG (printf
		       ("Reading (%d, %d) from chunk %d\n", cx, cy,
			chunkNum));
	    };

	  GD2_DBG (printf
		   ("   into (%d, %d) - (%d, %d)\n", xlo, ylo, xhi, yhi));
	  for (y = ylo; (y < yhi); y++)
	    {

	      for (x = xlo; x < xhi; x++)
		{
		  if (!gd2_compressed (fmt))
		    {
		      if (im->trueColor)
			{
			  if (!gdGetInt ((int *) &ch, in))
			    {
			      ch = 0;
			      /*printf("EOF while reading file\n"); */
			      /*goto fail2; */
			    }
			}
		      else
			{
			  ch = gdGetC (in);
			  if ((int) ch == EOF)
			    {
			      ch = 0;
			      /*printf("EOF while reading file\n"); */
			      /*goto fail2; */
			    }
			}
		    }
		  else
		    {
		      if (im->trueColor)
			{
			  ch = chunkBuf[chunkPos++];
			  ch = (ch << 8) + chunkBuf[chunkPos++];
			  ch = (ch << 8) + chunkBuf[chunkPos++];
			  ch = (ch << 8) + chunkBuf[chunkPos++];
			}
		      else
			{
			  ch = chunkBuf[chunkPos++];
			}
		    };

		  /* Only use a point that is in the image. */
		  if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0)
		      && (y >= srcy) && (y < (srcy + h)) && (y < fsy)
		      && (y >= 0))
		    {
		      /* 2.0.11: tpixels */
		      if (im->trueColor)
			{
			  im->tpixels[y - srcy][x - srcx] = ch;
			}
		      else
			{
			  im->pixels[y - srcy][x - srcx] = ch;
			}
		    }
		};
	    };
	};
    };

  gdFree (chunkBuf);
  gdFree (compBuf);
  gdFree (chunkIdx);

  return im;

fail2:
  gdImageDestroy (im);
fail1:
	if (chunkBuf) {
	  gdFree (chunkBuf);
	}
	if (compBuf) {
	  gdFree (compBuf);
	}
	if (chunkIdx) {
  	gdFree (chunkIdx);
	}
  return 0;

}
示例#5
0
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
  int sx, sy;
  int i;
  int ncx, ncy, nc, cs, cx, cy;
  int x, y, ylo, yhi, xlo, xhi;
  int vers, fmt;
  t_chunk_info *chunkIdx = NULL;	/* So we can gdFree it with impunity. */
  unsigned char *chunkBuf = NULL;	/* So we can gdFree it with impunity. */
  int chunkNum = 0;
  int chunkMax = 0;
  uLongf chunkLen;
  int chunkPos = 0;
  int compMax = 0;
  int bytesPerPixel;
  char *compBuf = NULL;		/* So we can gdFree it with impunity. */

  gdImagePtr im;

  /* Get the header */
  im =
    _gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
			&chunkIdx);

  if (im == NULL)
    {
      return 0;
    }

  bytesPerPixel = im->trueColor ? 4 : 1;
  nc = ncx * ncy;

  if (gd2_compressed (fmt))
    {
      /* Find the maximum compressed chunk size. */
      compMax = 0;
      for (i = 0; (i < nc); i++)
	{
	  if (chunkIdx[i].size > compMax)
	    {
	      compMax = chunkIdx[i].size;
	    };
	};
      compMax++;

      /* Allocate buffers */
      chunkMax = cs * bytesPerPixel * cs;
      chunkBuf = gdCalloc (chunkMax, 1);
			if (!chunkBuf) {
				goto fail;
			}
      compBuf = gdCalloc (compMax, 1);
			if (!compBuf) {
				goto fail;
			}

      GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
    };

/*      if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/*              goto fail2; */
/*      }; */

  /* Read the data... */
  for (cy = 0; (cy < ncy); cy++)
    {
      for (cx = 0; (cx < ncx); cx++)
	{

	  ylo = cy * cs;
	  yhi = ylo + cs;
	  if (yhi > im->sy)
	    {
	      yhi = im->sy;
	    };

	  GD2_DBG (printf
		   ("Processing Chunk %d (%d, %d), y from %d to %d\n",
		    chunkNum, cx, cy, ylo, yhi));

	  if (gd2_compressed (fmt))
	    {

	      chunkLen = chunkMax;

	      if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
				  compBuf,
				  chunkIdx[chunkNum].size,
				  (char *) chunkBuf, &chunkLen, in))
		{
		  GD2_DBG (printf ("Error reading comproessed chunk\n"));
		  goto fail;
		};

	      chunkPos = 0;
	    };

	  for (y = ylo; (y < yhi); y++)
	    {

	      xlo = cx * cs;
	      xhi = xlo + cs;
	      if (xhi > im->sx)
		{
		  xhi = im->sx;
		};
	      /*GD2_DBG(printf("y=%d: ",y)); */
	      if (!gd2_compressed (fmt))
		{
		  for (x = xlo; x < xhi; x++)
		    {

		      if (im->trueColor)
			{
			  if (!gdGetInt (&im->tpixels[y][x], in))
			    {
			      /*printf("EOF while reading\n"); */
			      /*gdImageDestroy(im); */
			      /*return 0; */
			      im->tpixels[y][x] = 0;
			    }
			}
		      else
			{
			  int ch;
			  if (!gdGetByte (&ch, in))
			    {
			      /*printf("EOF while reading\n"); */
			      /*gdImageDestroy(im); */
			      /*return 0; */
			      ch = 0;
			    }
			  im->pixels[y][x] = ch;
			}
		    }
		}
	      else
		{
		  for (x = xlo; x < xhi; x++)
		    {
		      if (im->trueColor)
			{
			  /* 2.0.1: work around a gcc bug by being verbose.
			     TBB */
			  int a = chunkBuf[chunkPos++] << 24;
			  int r = chunkBuf[chunkPos++] << 16;
			  int g = chunkBuf[chunkPos++] << 8;
			  int b = chunkBuf[chunkPos++];
			  /* 2.0.11: tpixels */
			  im->tpixels[y][x] = a + r + g + b;
			}
		      else
			{
			  im->pixels[y][x] = chunkBuf[chunkPos++];
			}
		    };
		};
	      /*GD2_DBG(printf("\n")); */
	    };
	  chunkNum++;
	};
    };

  GD2_DBG (printf ("Freeing memory\n"));

  gdFree (chunkBuf);
  gdFree (compBuf);
  gdFree (chunkIdx);

  GD2_DBG (printf ("Done\n"));

  return im;

fail:
  gdImageDestroy (im);
	if (chunkBuf) {
		gdFree (chunkBuf);
	}
	if (compBuf) {
		gdFree (compBuf);
	} 
	if (chunkIdx) {
		gdFree (chunkIdx);
	}
  return 0;
}
示例#6
0
文件: gd_jpeg.c 项目: ebichu/dd-wrt
BGD_DECLARE(gdImagePtr) gdImageCreateFromJpegCtxEx(gdIOCtx *infile, int ignore_warning)
{
	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;
	jmpbuf_wrapper jmpbufw;
	/* volatile so we can gdFree them after longjmp */
	volatile JSAMPROW row = 0;
	volatile gdImagePtr im = 0;
	JSAMPROW rowptr[1];
	JDIMENSION i, j;
	int retval;
	JDIMENSION nrows;
	int channels = 3;
	int inverted = 0;

#ifdef JPEG_DEBUG
	gd_error_ex(GD_DEBUG, "gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION);
	gd_error_ex(GD_DEBUG, "gd-jpeg: JPEG library version %d, %d-bit sample values\n", JPEG_LIB_VERSION, BITS_IN_JSAMPLE);
	gd_error_ex(GD_DEBUG, "sizeof: %d\n", sizeof(struct jpeg_decompress_struct));
#endif

	memset(&cinfo, 0, sizeof(cinfo));
	memset(&jerr, 0, sizeof(jerr));

	jmpbufw.ignore_warning = ignore_warning;

	cinfo.err = jpeg_std_error(&jerr);
	cinfo.client_data = &jmpbufw;

	cinfo.err->emit_message = jpeg_emit_message;

	if(setjmp(jmpbufw.jmpbuf) != 0) {
		/* we're here courtesy of longjmp */
		if(row) {
			gdFree(row);
		}
		if(im) {
			gdImageDestroy(im);
		}
		return 0;
	}

	cinfo.err->error_exit = fatal_jpeg_error;

	jpeg_create_decompress(&cinfo);

	jpeg_gdIOCtx_src(&cinfo, infile);

	/* 2.0.22: save the APP14 marker to check for Adobe Photoshop CMYK
	 * files with inverted components.
	 */
	jpeg_save_markers(&cinfo, JPEG_APP0 + 14, 256);

	retval = jpeg_read_header(&cinfo, TRUE);
	if(retval != JPEG_HEADER_OK) {
		gd_error("gd-jpeg: warning: jpeg_read_header returns"
		         " %d, expected %d\n", retval, JPEG_HEADER_OK);
	}

	if(cinfo.image_height > INT_MAX) {
		gd_error("gd-jpeg: warning: JPEG image height (%u) is"
		         " greater than INT_MAX (%d) (and thus greater than"
		         " gd can handle)", cinfo.image_height, INT_MAX);
	}

	if(cinfo.image_width > INT_MAX) {
		gd_error("gd-jpeg: warning: JPEG image width (%u) is"
		         " greater than INT_MAX (%d) (and thus greater than"
		         " gd can handle)\n", cinfo.image_width, INT_MAX);
	}

	im = gdImageCreateTrueColor((int)cinfo.image_width, (int)cinfo.image_height);
	if(im == 0) {
		gd_error("gd-jpeg error: cannot allocate gdImage struct\n");
		goto error;
	}

	/* check if the resolution is specified */
	switch (cinfo.density_unit) {
	case 1:
		im->res_x = cinfo.X_density;
		im->res_y = cinfo.Y_density;
		break;
	case 2:
		im->res_x = DPCM2DPI(cinfo.X_density);
		im->res_y = DPCM2DPI(cinfo.Y_density);
		break;
	}

	/* 2.0.22: very basic support for reading CMYK colorspace files. Nice for
	 * thumbnails but there's no support for fussy adjustment of the
	 * assumed properties of inks and paper.
	 */
	if((cinfo.jpeg_color_space == JCS_CMYK) || (cinfo.jpeg_color_space == JCS_YCCK)) {
		cinfo.out_color_space = JCS_CMYK;
	} else {
		cinfo.out_color_space = JCS_RGB;
	}

	if(jpeg_start_decompress(&cinfo) != TRUE) {
		gd_error("gd-jpeg: warning: jpeg_start_decompress"
		        " reports suspended data source\n");
	}

#ifdef JPEG_DEBUG
	gd_error_ex(GD_DEBUG, "gd-jpeg: JPEG image information:");
	if(cinfo.saw_JFIF_marker) {
		gd_error_ex(GD_DEBUG, " JFIF version %d.%.2d", (int)cinfo.JFIF_major_version, (int)cinfo.JFIF_minor_version);
	} else if(cinfo.saw_Adobe_marker) {
		gd_error_ex(GD_DEBUG, " Adobe format");
	} else {
		gd_error_ex(GD_DEBUG, " UNKNOWN format");
	}

	gd_error_ex(GD_DEBUG, " %ux%u (raw) / %ux%u (scaled) %d-bit", cinfo.image_width,
		    cinfo.image_height, cinfo.output_width,
		    cinfo.output_height, cinfo.data_precision
		);
	gd_error_ex(GD_DEBUG, " %s", (cinfo.progressive_mode ? "progressive" : "baseline"));
	gd_error_ex(GD_DEBUG, " image, %d quantized colors, ", cinfo.actual_number_of_colors);

	switch(cinfo.jpeg_color_space) {
	case JCS_GRAYSCALE:
		gd_error_ex(GD_DEBUG, "grayscale");
		break;

	case JCS_RGB:
		gd_error_ex(GD_DEBUG, "RGB");
		break;

	case JCS_YCbCr:
		gd_error_ex(GD_DEBUG, "YCbCr (a.k.a. YUV)");
		break;

	case JCS_CMYK:
		gd_error_ex(GD_DEBUG, "CMYK");
		break;

	case JCS_YCCK:
		gd_error_ex(GD_DEBUG, "YCbCrK");
		break;

	default:
		gd_error_ex(GD_DEBUG, "UNKNOWN (value: %d)", (int)cinfo.jpeg_color_space);
		break;
	}

	gd_error_ex(GD_DEBUG, " colorspace\n");
	fflush(stdout);
#endif /* JPEG_DEBUG */

	/* REMOVED by TBB 2/12/01. This field of the structure is
	 * documented as private, and sure enough it's gone in the
	 * latest libjpeg, replaced by something else. Unfortunately
	 * there is still no right way to find out if the file was
	 * progressive or not; just declare your intent before you
	 * write one by calling gdImageInterlace(im, 1) yourself.
	 * After all, we're not really supposed to rework JPEGs and
	 * write them out again anyway. Lossy compression, remember? */
#if 0
	gdImageInterlace (im, cinfo.progressive_mode != 0);
#endif
	if(cinfo.out_color_space == JCS_RGB) {
		if(cinfo.output_components != 3) {
			gd_error("gd-jpeg: error: JPEG color quantization"
			         " request resulted in output_components == %d"
			         " (expected 3 for RGB)\n", cinfo.output_components);
			goto error;
		}
		channels = 3;
	} else if(cinfo.out_color_space == JCS_CMYK) {
		jpeg_saved_marker_ptr marker;
		if(cinfo.output_components != 4) {
			gd_error("gd-jpeg: error: JPEG color quantization"
			         " request resulted in output_components == %d"
			         " (expected 4 for CMYK)\n", cinfo.output_components);
			goto error;
		}
		channels = 4;

		marker = cinfo.marker_list;
		while(marker) {
			if(	(marker->marker == (JPEG_APP0 + 14)) &&
			        (marker->data_length >= 12) &&
			        (!strncmp((const char *)marker->data, "Adobe", 5))) {
				inverted = 1;
				break;
			}
			marker = marker->next;
		}
	} else {
		gd_error("gd-jpeg: error: unexpected colorspace\n");
		goto error;
	}
#if BITS_IN_JSAMPLE == 12
	gd_error_ex(GD_ERROR,
		    "gd-jpeg: error: jpeg library was compiled for 12-bit\n"
		    "precision. This is mostly useless, because JPEGs on the web are\n"
		    "8-bit and such versions of the jpeg library won't read or write\n"
		    "them. GD doesn't support these unusual images. Edit your\n"
		    "jmorecfg.h file to specify the correct precision and completely\n"
		    "'make clean' and 'make install' libjpeg again. Sorry.\n");
	goto error;
#endif /* BITS_IN_JSAMPLE == 12 */

	row = gdCalloc(cinfo.output_width *channels, sizeof(JSAMPLE));
	if(row == 0) {
		gd_error("gd-jpeg: error: unable to allocate row for"
		         " JPEG scanline: gdCalloc returns NULL\n");
		goto error;
	}
	rowptr[0] = row;
	if(cinfo.out_color_space == JCS_CMYK) {
		for(i = 0; i < cinfo.output_height; i++) {
			register JSAMPROW currow = row;
			register int *tpix = im->tpixels[i];
			nrows = jpeg_read_scanlines(&cinfo, rowptr, 1);
			if(nrows != 1) {
				gd_error("gd-jpeg: error: jpeg_read_scanlines"
				         " returns %u, expected 1\n", nrows);
				goto error;
			}
			for(j = 0; j < cinfo.output_width; j++, currow += 4, tpix++) {
				*tpix = CMYKToRGB(currow[0], currow[1], currow[2], currow[3], inverted);
			}
		}
	} else {
		for(i = 0; i < cinfo.output_height; i++) {
			register JSAMPROW currow = row;
			register int *tpix = im->tpixels[i];
			nrows = jpeg_read_scanlines(&cinfo, rowptr, 1);
			if(nrows != 1) {
				gd_error("gd-jpeg: error: jpeg_read_scanlines"
				         " returns %u, expected 1\n", nrows);
				goto error;
			}
			for(j = 0; j < cinfo.output_width; j++, currow += 3, tpix++) {
				*tpix = gdTrueColor(currow[0], currow[1], currow[2]);
			}
		}
	}

	if(jpeg_finish_decompress (&cinfo) != TRUE) {
		gd_error("gd-jpeg: warning: jpeg_finish_decompress"
		         " reports suspended data source\n");
	}
	/* TBB 2.0.29: we should do our best to read whatever we can read, and a
	 * warning is a warning. A fatal error on warnings doesn't make sense. */
#if 0
	/* This was originally added by Truxton Fulton */
	if (cinfo.err->num_warnings > 0)
		goto error;
#endif

	jpeg_destroy_decompress(&cinfo);
	gdFree(row);
	return im;

error:
	jpeg_destroy_decompress(&cinfo);

	if(row) {
		gdFree(row);
	}
	if(im) {
		gdImageDestroy(im);
	}

	return 0;
}
示例#7
0
文件: gd_jpeg.c 项目: ebichu/dd-wrt
BGD_DECLARE(void) gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality)
{
	struct jpeg_compress_struct cinfo;
	struct jpeg_error_mgr jerr;
	int i, j, jidx;
	/* volatile so we can gdFree it on return from longjmp */
	volatile JSAMPROW row = 0;
	JSAMPROW rowptr[1];
	jmpbuf_wrapper jmpbufw;
	JDIMENSION nlines;
	char comment[255];

#ifdef JPEG_DEBUG
	gd_error_ex(GD_DEBUG, "gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION);
	gd_error_ex(GD_DEBUG, "gd-jpeg: JPEG library version %d, %d-bit sample values\n", JPEG_LIB_VERSION, BITS_IN_JSAMPLE);
	if (!im->trueColor) {
		for(i = 0; i < im->colorsTotal; i++) {
			if(!im->open[i]) {
				gd_error_ex(GD_DEBUG, "gd-jpeg: gd colormap index %d: (%d, %d, %d)\n", i, im->red[i], im->green[i], im->blue[i]);
			}
		}
	}
#endif /* JPEG_DEBUG */

	memset(&cinfo, 0, sizeof(cinfo));
	memset(&jerr, 0, sizeof(jerr));

	cinfo.err = jpeg_std_error(&jerr);
	cinfo.client_data = &jmpbufw;

	if(setjmp(jmpbufw.jmpbuf) != 0) {
		/* we're here courtesy of longjmp */
		if(row) {
			gdFree(row);
		}
		return;
	}

	cinfo.err->emit_message = jpeg_emit_message;
	cinfo.err->error_exit = fatal_jpeg_error;

	jpeg_create_compress(&cinfo);

	cinfo.image_width = im->sx;
	cinfo.image_height = im->sy;
	cinfo.input_components = 3; /* # of color components per pixel */
	cinfo.in_color_space = JCS_RGB; /* colorspace of input image */

	jpeg_set_defaults(&cinfo);

	cinfo.density_unit = 1;
	cinfo.X_density = im->res_x;
	cinfo.Y_density = im->res_y;

	if(quality >= 0) {
		jpeg_set_quality(&cinfo, quality, TRUE);
	}

	/* If user requests interlace, translate that to progressive JPEG */
	if(gdImageGetInterlaced(im)) {
#ifdef JPEG_DEBUG
		gd_error_ex(GD_DEBUG, "gd-jpeg: interlace set, outputting progressive JPEG image\n");
#endif
		jpeg_simple_progression(&cinfo);
	}

	jpeg_gdIOCtx_dest(&cinfo, outfile);

	row = (JSAMPROW)gdCalloc(1, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE));
	if(row == 0) {
		gd_error("gd-jpeg: error: unable to allocate JPEG row structure: gdCalloc returns NULL\n");
		jpeg_destroy_compress(&cinfo);
		return;
	}

	rowptr[0] = row;

	jpeg_start_compress(&cinfo, TRUE);

	sprintf(comment, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d),", GD_JPEG_VERSION, JPEG_LIB_VERSION);

	if(quality >= 0) {
		sprintf (comment + strlen(comment), " quality = %d\n", quality);
	} else {
		strcat(comment + strlen(comment), " default quality\n");
	}

	jpeg_write_marker(&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int)strlen(comment));

	if(im->trueColor) {
#if BITS_IN_JSAMPLE == 12
		gd_error(
		        "gd-jpeg: error: jpeg library was compiled for 12-bit\n"
		        "precision. This is mostly useless, because JPEGs on the web are\n"
		        "8-bit and such versions of the jpeg library won't read or write\n"
		        "them. GD doesn't support these unusual images. Edit your\n"
		        "jmorecfg.h file to specify the correct precision and completely\n"
		        "'make clean' and 'make install' libjpeg again. Sorry.\n"
		       );
		goto error;
#endif /* BITS_IN_JSAMPLE == 12 */
		for(i = 0; i < im->sy; i++) {
			for(jidx = 0, j = 0; j < im->sx; j++) {
				int val = im->tpixels[i][j];
				row[jidx++] = gdTrueColorGetRed(val);
				row[jidx++] = gdTrueColorGetGreen(val);
				row[jidx++] = gdTrueColorGetBlue(val);
			}

			nlines = jpeg_write_scanlines(&cinfo, rowptr, 1);

			if(nlines != 1) {
				gd_error("gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1\n", nlines);
			}
		}
	} else {
		for(i = 0; i < im->sy; i++) {
			for(jidx = 0, j = 0; j < im->sx; j++) {
				int idx = im->pixels[i][j];

				/*
				 * NB: Although gd RGB values are ints, their max value is
				 * 255 (see the documentation for gdImageColorAllocate())
				 * -- perfect for 8-bit JPEG encoding (which is the norm)
				 */
#if BITS_IN_JSAMPLE == 8
				row[jidx++] = im->red[idx];
				row[jidx++] = im->green[idx];
				row[jidx++] = im->blue[idx];
#elif BITS_IN_JSAMPLE == 12
				row[jidx++] = im->red[idx] << 4;
				row[jidx++] = im->green[idx] << 4;
				row[jidx++] = im->blue[idx] << 4;
#else
#error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
#endif
			}

			nlines = jpeg_write_scanlines(&cinfo, rowptr, 1);
			if(nlines != 1) {
				gd_error("gd_jpeg: warning: jpeg_write_scanlines"
				         " returns %u -- expected 1\n", nlines);
			}
		}
	}

	jpeg_finish_compress(&cinfo);
	jpeg_destroy_compress(&cinfo);
	gdFree(row);
}
示例#8
0
文件: gd_gd2.c 项目: amery/clip-itk
gdImagePtr gdImageCreateFromGd2Ctx(gdIOCtxPtr in)
{
        int sx, sy;
        int i;
        int ncx, ncy, nc, cs, cx, cy;
        int x, y, ylo, yhi, xlo, xhi;
	int ch, vers, fmt;
	t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
	char	*chunkBuf = NULL; /* So we can gdFree it with impunity. */
	int	chunkNum = 0;
	int	chunkMax = 0;
	uLongf 	chunkLen;
	int	chunkPos = 0;
	int 	compMax;
	char	*compBuf = NULL; /* So we can gdFree it with impunity. */

        gdImagePtr im;

	/* Get the header */
        im = _gd2CreateFromFile(in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx);

        if (im == NULL) {
                return 0;
        };

	nc = ncx * ncy;

	if (fmt == GD2_FMT_COMPRESSED) {
		/* Find the maximum compressed chunk size. */
	        compMax = 0;
	        for (i=0; (i < nc) ; i++) {
			if ( chunkIdx[i].size > compMax) {
				compMax = chunkIdx[i].size;
			};
		};
		compMax++;

		/* Allocate buffers */
		chunkMax = cs * cs;
		chunkBuf = gdCalloc(chunkMax,1);
		compBuf = gdCalloc(compMax,1);
		GD2_DBG(printf("Largest compressed chunk is %d bytes\n",compMax));
	};

/*	if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/*		goto fail2; */
/*	}; */

	/* Read the data... */
        for (cy=0; (cy < ncy); cy++) {
                for (cx=0; (cx < ncx); cx++) {

                        ylo = cy * cs;
                        yhi = ylo + cs;
                        if (yhi > im->sy) {
                                yhi = im->sy;
                        };

                        GD2_DBG(printf("Processing Chunk %d (%d, %d), y from %d to %d\n",chunkNum, cx, cy, ylo, yhi));

			if (fmt == GD2_FMT_COMPRESSED) {

				chunkLen = chunkMax;

				if (!_gd2ReadChunk(	chunkIdx[chunkNum].offset,
							compBuf, 
							chunkIdx[chunkNum].size, 
							chunkBuf, &chunkLen, in))
				{
                                        GD2_DBG(printf("Error reading comproessed chunk\n"));
                                        goto fail2;
                                };

				chunkPos = 0;
			};

                        for (y= ylo ; (y < yhi); y++) {

                                xlo = cx * cs;
                                xhi = xlo + cs;
                                if (xhi > im->sx) {
                                        xhi = im->sx;
                                };
				/*GD2_DBG(printf("y=%d: ",y)); */
				if (fmt == GD2_FMT_RAW) {
                                	for (x= xlo ; x < xhi; x++) {

						ch = gdGetC(in);
						if (ch == EOF) {
							ch = 0;
							/*printf("EOF while reading\n"); */
							/*gdImageDestroy(im); */
							/*return 0; */
						}
						/*GD2_DBG(printf(" (%d, %d)", x, y)); */
						im->pixels[y][x] = ch;
					}
				} else {
					for (x= xlo ; x < xhi; x++) {
                                                im->pixels[y][x] = chunkBuf[chunkPos++];
                                        };
                                };
				/*GD2_DBG(printf("\n")); */
                        };
			chunkNum++;
                };
        };

	GD2_DBG(printf("Freeing memory\n"));

	gdFree(chunkBuf);
	gdFree(compBuf);
	gdFree(chunkIdx);

	GD2_DBG(printf("Done\n"));

        return im;

fail2:
        gdImageDestroy(im);
        gdFree(chunkBuf);
        gdFree(compBuf);
	gdFree(chunkIdx);
        return 0;

}
示例#9
0
void
gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality)
{
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    int i, j, jidx;
    /* volatile so we can gdFree it on return from longjmp */
    volatile JSAMPROW row = 0;
    JSAMPROW rowptr[1];
    jmpbuf_wrapper jmpbufw;
    JDIMENSION nlines;
    char comment[255];

#ifdef JPEG_DEBUG
    printf("gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION);
    printf("gd-jpeg: JPEG library version %d, %d-bit sample values\n",
	   JPEG_LIB_VERSION, BITS_IN_JSAMPLE);

    for (i = 0; i < im->colorsTotal; i++) {
	if (!im->open[i])
	    printf("gd-jpeg: gd colormap index %d: (%d, %d, %d)\n", i,
		   im->red[i], im->green[i], im->blue[i]);
    }
#endif /* JPEG_DEBUG */

    memset(&cinfo, 0, sizeof(cinfo));
    memset(&jerr, 0, sizeof(jerr));

    cinfo.err = jpeg_std_error(&jerr);
    cinfo.client_data = &jmpbufw;
    if (setjmp(jmpbufw.jmpbuf) != 0) {
	/* we're here courtesy of longjmp */
	if (row)
	    gdFree(row);
	return;
    }

    cinfo.err->error_exit = fatal_jpeg_error;

    jpeg_create_compress(&cinfo);

    cinfo.image_width = im->sx;
    cinfo.image_height = im->sy;
    cinfo.input_components = 3;	/* # of color components per pixel */
    cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
    jpeg_set_defaults(&cinfo);
    if (quality >= 0)
	jpeg_set_quality(&cinfo, quality, TRUE);

    /* If user requests interlace, translate that to progressive JPEG */
    if (gdImageGetInterlaced(im)) {
#ifdef JPEG_DEBUG
	printf("gd-jpeg: interlace set, outputting progressive"
	       " JPEG image\n"); 
#endif	
	jpeg_simple_progression(&cinfo);
    }

    jpeg_gdIOCtx_dest(&cinfo, outfile);

    row = (JSAMPROW)gdCalloc(1, cinfo.image_width * cinfo.input_components
			   * sizeof(JSAMPLE));
    if (row == 0) {
	fprintf(stderr, "gd-jpeg: error: unable to allocate JPEG row "
		"structure: gdCalloc returns NULL\n");
	jpeg_destroy_compress(&cinfo);
	return;
    }

    rowptr[0] = row;

    jpeg_start_compress(&cinfo, TRUE);

    sprintf(comment, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d),",
	    GD_JPEG_VERSION, JPEG_LIB_VERSION);
    if (quality >= 0)
	sprintf(comment + strlen(comment), " quality = %d\n",
		quality);
    else
	strcat(comment + strlen(comment), " default quality\n");
    jpeg_write_marker(&cinfo, JPEG_COM, (unsigned char *)comment,
		      (unsigned int)strlen(comment));

    for (i = 0; i < im->sy; i++) {
	for (jidx = 0, j = 0; j < im->sx; j++) {
	    int idx = im->pixels[i][j];

	    /*
	     * NB: Although gd RGB values are ints, their max value is
	     * 255 (see the documentation for gdImageColorAllocate())
	     * -- perfect for 8-bit JPEG encoding (which is the norm)
	     */
#if BITS_IN_JSAMPLE == 8
	    row[jidx++] = im->red[idx];
	    row[jidx++] = im->green[idx];
	    row[jidx++] = im->blue[idx];
#elif BITS_IN_JSAMPLE == 12
	    row[jidx++] = im->red[idx] << 4;
	    row[jidx++] = im->green[idx] << 4;
	    row[jidx++] = im->blue[idx] << 4;
#else
#error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
#endif
	}

	nlines = jpeg_write_scanlines(&cinfo, rowptr, 1);
	if (nlines != 1)
	    fprintf(stderr, "gd_jpeg: warning: jpeg_write_scanlines"
		    " returns %u -- expected 1\n", nlines);
    }

    jpeg_finish_compress(&cinfo);
    jpeg_destroy_compress(&cinfo);
    gdFree(row);
}
示例#10
0
/* 
 * Create a gd-format image from the JPEG-format INFILE.  Returns the
 * image, or NULL upon error.
*/
gdImagePtr
gdImageCreateFromJpegCtx(gdIOCtx *infile)
{
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    jmpbuf_wrapper jmpbufw;
    /* volatile so we can gdFree them after longjmp */
    volatile JSAMPROW row = 0;
    volatile gdImagePtr im = 0;
    JSAMPROW rowptr[1];
    int i, j, retval;
    JDIMENSION nrows;

#ifdef JPEG_DEBUG
    printf("gd-jpeg: gd JPEG version %s\n", GD_JPEG_VERSION);
    printf("gd-jpeg: JPEG library version %d, %d-bit sample values\n",
	   JPEG_LIB_VERSION, BITS_IN_JSAMPLE);
#endif

    memset(&cinfo, 0, sizeof(cinfo));
    memset(&jerr, 0, sizeof(jerr));

    cinfo.err = jpeg_std_error(&jerr);
    cinfo.client_data = &jmpbufw;
    if (setjmp(jmpbufw.jmpbuf) != 0) {
	/* we're here courtesy of longjmp */
	if (row)
	    gdFree(row);
	if (im)
	    gdImageDestroy(im);
	return 0;
    }

    cinfo.err->error_exit = fatal_jpeg_error;

    jpeg_create_decompress(&cinfo);

    jpeg_gdIOCtx_src(&cinfo, infile);

    retval = jpeg_read_header(&cinfo, TRUE);
    if (retval != JPEG_HEADER_OK)
	fprintf(stderr, "gd-jpeg: warning: jpeg_read_header returns"
		" %d, expected %d\n", retval, JPEG_HEADER_OK);

    if (cinfo.image_height > INT_MAX)
	fprintf(stderr, "gd-jpeg: warning: JPEG image height (%u) is"
		" greater than INT_MAX (%d) (and thus greater than"
		" gd can handle)", cinfo.image_height,
		INT_MAX);

    if (cinfo.image_width > INT_MAX)
	fprintf(stderr, "gd-jpeg: warning: JPEG image width (%u) is"
		" greater than INT_MAX (%d) (and thus greater than"
		" gd can handle)\n", cinfo.image_width, INT_MAX);

    im = gdImageCreate((int)cinfo.image_width,
		       (int)cinfo.image_height);
    if (im == 0) {
        fprintf(stderr, "gd-jpeg error: cannot allocate gdImage"
		" struct\n");
	goto error;
    }

    /*
     * Have the JPEG library quantize the number of image colors to
     * 256 maximum; force into RGB colorspace
     */
    cinfo.out_color_space = JCS_RGB;
    cinfo.quantize_colors = TRUE;
    cinfo.desired_number_of_colors = gdMaxColors;

    if (jpeg_start_decompress(&cinfo) != TRUE)
	fprintf(stderr, "gd-jpeg: warning: jpeg_start_decompress"
		" reports suspended data source\n");

#ifdef JPEG_DEBUG
    printf("gd-jpeg: JPEG image information:");
    if (cinfo.saw_JFIF_marker)
	printf(" JFIF version %d.%.2d",
	       (int)cinfo.JFIF_major_version,
	       (int)cinfo.JFIF_minor_version);
    else if (cinfo.saw_Adobe_marker)
	printf(" Adobe format");
    else
	printf(" UNKNOWN format");

    printf(" %ux%u (raw) / %ux%u (scaled) %d-bit", cinfo.image_width,
	   cinfo.image_height, cinfo.output_width,
	   cinfo.output_height, cinfo.data_precision);
    printf(" %s", (cinfo.progressive_mode ? "progressive" :
		   "baseline"));
    printf(" image, %d quantized colors, ",
	   cinfo.actual_number_of_colors);

    switch (cinfo.jpeg_color_space) {
    case JCS_GRAYSCALE:
	printf("grayscale");
	break;

    case JCS_RGB:
	printf("RGB");
	break;

    case JCS_YCbCr:
	printf("YCbCr (a.k.a. YUV)");
	break;

    case JCS_CMYK:
	printf("CMYK");
	break;

    case JCS_YCCK:
	printf("YCbCrK");
	break;

    default:
	printf("UNKNOWN (value: %d)", (int)cinfo.jpeg_color_space);
	break;
    }
    printf(" colorspace\n");
    fflush(stdout);
#endif /* JPEG_DEBUG */

    gdImageInterlace(im, cinfo.progressive_mode != 0);

    im->colorsTotal = cinfo.actual_number_of_colors;
    if (cinfo.output_components != 1) {
	fprintf(stderr, "gd-jpeg: error: JPEG color quantization"
		" request resulted in output_components == %d"
		" (expected 1)\n",  cinfo.output_components);
	goto error;
    }

    for (i = 0; i < im->colorsTotal; i++) {
#if BITS_IN_JSAMPLE == 8
	im->red[i] = cinfo.colormap[0][i];
	im->green[i] = cinfo.colormap[1][i];
	im->blue[i] = cinfo.colormap[2][i];
#elif BITS_IN_JSAMPLE == 12
	im->red[i] = (cinfo.colormap[0][i] >> 4) & 0xff;
	im->green[i] = (cinfo.colormap[1][i] >> 4) & 0xff;
	im->blue[i] = (cinfo.colormap[2][i] >> 4) & 0xff;
#else
#error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
#endif
	im->open[i] = 0;
#ifdef JPEG_DEBUG
	printf("gd-jpeg: gd colormap index %d set to (%d, %d, %d)\n", i,
	       im->red[i], im->green[i], im->blue[i]);
#endif
    }

    row = gdCalloc(cinfo.output_width, sizeof(JSAMPLE));
    if (row == 0) {
	fprintf(stderr, "gd-jpeg: error: unable to allocate row for"
		" JPEG scanline: gdCalloc returns NULL\n");
	goto error;
    }
    rowptr[0] = row;

    for (i = 0; i < cinfo.output_height; i++) {
	nrows = jpeg_read_scanlines(&cinfo, rowptr, 1);
	if (nrows != 1) {
	    fprintf(stderr, "gd-jpeg: error: jpeg_read_scanlines"
		    " returns %u, expected 1\n", nrows);
	    goto error;
	}

	for (j = 0; j < cinfo.output_width; j++)
	    im->pixels[i][j] = row[j];
    }

    if (jpeg_finish_decompress(&cinfo) != TRUE)
	fprintf(stderr, "gd-jpeg: warning: jpeg_finish_decompress"
		" reports suspended data source\n");


    jpeg_destroy_decompress(&cinfo);
    gdFree(row);
    return im;

error:
    jpeg_destroy_decompress(&cinfo);
    if (row)
	gdFree(row);
    if (im)
	gdImageDestroy(im);
    return 0;
}