Beispiel #1
0
/*
 * Save fftwf-complex matrix to PNG files via gd
 *  spectrum = 1       -> save complex spectrum to <basename>-spectrum.png
 *  phase_angle = 1    -> save complex phase angle to <basename>-phaseang.png
 *  power_spectrum = 1 -> save complex phase angle to <basename>-powspect.png
 * 
 * return -1 on error, 0 otherwise
 */
int fftwf_result_save( fftwf_complex *data, int spectrum, int phase_angle, int power_spectrum, uint32_t w, uint32_t h, char *basename )
{
	FILE *f_s, *f_pa, *f_ps;
	gdImage *image_s, *image_pa, *image_ps;
	uint32_t i, j, g, color;
	fftwf_complex *dat;
	float d, max_s, max_pa, max_ps, power;
	
	char fn_s[256],fn_pa[256],fn_ps[256];
	
	if( !spectrum && !phase_angle && !power_spectrum )
	{
		WARN("nothing to do");
		return(0);
	}
	
	if( spectrum )
	{
		snprintf( fn_s, 255, "%s-spectrum.png", basename);
		f_s = fopen(fn_s,"wb");
		if(!f_s)
		{
			ERROR("Error opening file for output: %s", fn_s);
			ERROR("fopen: %s", strerror(errno));
			return(-1);
		}

		image_s = gdImageCreateTrueColor(w,h);
		if(!image_s)
		{
			ERROR("Cannot create image");
			fclose(f_s);
			return(-1);
		}
	}

	if( phase_angle )
	{
		snprintf( fn_pa, 255, "%s-phaseang.png", basename);
		f_pa = fopen(fn_pa,"wb");
		if(!f_pa)
		{
			ERROR("Error opening file for output: %s", fn_pa);
			ERROR("fopen: %s", strerror(errno));
			return(-1);
		}

		image_pa = gdImageCreateTrueColor(w,h);
		if(!image_pa)
		{
			ERROR("Cannot create image");
			fclose(f_pa);
			return(-1);
		}
	}

	if( phase_angle )
	{
		snprintf( fn_ps, 255, "%s-powspect.png", basename);
		f_ps = fopen(fn_ps,"wb");
		if(!f_ps)
		{
			ERROR("Error opening file for output: %s", fn_ps);
			ERROR("fopen: %s", strerror(errno));
			return(-1);
		}

		image_ps = gdImageCreateTrueColor(w,h);
		if(!image_ps)
		{
			ERROR("Cannot create image");
			fclose(f_ps);
			return(-1);
		}
	}

	
	max_s = max_pa = max_ps =0;
	dat = data;
	for(j=0;j<h;j++)
		for(i=0;i<w;i++,dat++)
		{
			if( spectrum || power_spectrum )
				power = powf(creal(*dat),2) + powf(cimag(*dat),2);
			if( spectrum ) {
				d = sqrtf(power);
				if( d> max_s )
					max_s = d;
			}
			if( phase_angle ) {
				d = atan2(cimag(*dat), creal(*dat));
				if( d> max_pa )
					max_pa = d;
			}
			if( power_spectrum ) {
				d = power;
				if( d> max_ps )
					max_ps = d;
			}
		}		
	


	dat = data;
	for(j=0; j<h; j++){
		for(i=0; i<w; i++)
		{
			if( spectrum || power_spectrum )
				power = powf(creal(*dat),2) + powf(cimag(*dat),2);


			if( spectrum ){
				d = sqrtf(power);
				g = round(255.0 * d/max_s);
				color = g + (g<<8) + (g<<16);
				color &= 0xffffff; 
				gdImageSetPixel(image_s,i,j,color);
			}
			if( phase_angle ){
				d = atan2(cimag(*dat), creal(*dat));
				g = round(255.0 * d/max_pa);
				color = g + (g<<8) + (g<<16);
				color &= 0xffffff; 
				gdImageSetPixel(image_pa,i,j,color);
			}
			if( power_spectrum ){
				d = power;
				g = round(255.0 * d/max_ps);
				color = g + (g<<8) + (g<<16);
				color &= 0xffffff; 
				gdImageSetPixel(image_ps,i,j,color);
			}

			dat++;
		}
	}
	
	if( spectrum ){ 
		gdImagePng(image_s, f_s);
		fclose( f_s );
		gdImageDestroy(image_s);
	}
	if( phase_angle ){ 
		gdImagePng(image_pa, f_pa);
		fclose( f_pa );
		gdImageDestroy(image_pa);
	}
	if( power_spectrum ){ 
		gdImagePng(image_ps, f_ps);
		fclose( f_ps );
		gdImageDestroy(image_ps);
	}

	return(0);
}
Beispiel #2
0
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 */
	if (!(im = _gd2CreateFromFile(in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx))) {
		 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;
		if (chunkMax <= 0) {
			return 0;
		}
		chunkBuf = gdCalloc(chunkMax, 1);
		compBuf = gdCalloc(compMax, 1);

		GD2_DBG(php_gd_error("Largest compressed chunk is %d bytes", compMax));
	}

	/* 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(php_gd_error("Processing Chunk %d (%d, %d), y from %d to %d", 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(php_gd_error("Error reading comproessed chunk"));
					goto fail2;
				}

				chunkPos = 0;
			}

			for (y = ylo; (y < yhi); y++) {
				xlo = cx * cs;
				xhi = xlo + cs;
				if (xhi > im->sx) {
					xhi = im->sx;
				}

				if (!gd2_compressed(fmt)) {
					for (x = xlo; x < xhi; x++) {
						if (im->trueColor) {
							if (!gdGetInt(&im->tpixels[y][x], in)) {
								im->tpixels[y][x] = 0;
							}
						} else {
							int ch;
							if (!gdGetByte(&ch, in)) {
								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++];
							im->tpixels[y][x] = a + r + g + b;
						} else {
							im->pixels[y][x] = chunkBuf[chunkPos++];
						}
					}
				}
			}
			chunkNum++;
		}
	}

	GD2_DBG(php_gd_error("Freeing memory"));

	if (chunkBuf) {
		gdFree(chunkBuf);
	}
	if (compBuf) {
		gdFree(compBuf);
	}
	if (chunkIdx) {
		gdFree(chunkIdx);
	}

	GD2_DBG(php_gd_error("Done"));

	return im;

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

	return 0;
}
Beispiel #3
0
/* This routine is based in part on the Chapter 13 demo code in "PNG: The
 *  Definitive Guide" (http://www.cdrom.com/pub/png/pngbook.html).
 */
gdImagePtr gdImageCreateFromPngCtx (gdIOCtx * infile)
{
	png_byte sig[8];
	png_structp png_ptr;
	png_infop info_ptr;
	png_uint_32 width, height, rowbytes, w, h;
	int bit_depth, color_type, interlace_type;
	int num_palette, num_trans;
	png_colorp palette;
	png_color_16p trans_gray_rgb;
	png_color_16p trans_color_rgb;
	png_bytep trans;
	png_bytep image_data = NULL;
	png_bytepp row_pointers = NULL;
	gdImagePtr im = NULL;
	int i, j, *open = NULL;
	volatile int transparent = -1;
	volatile int palette_allocated = FALSE;

	/* Make sure the signature can't match by dumb luck -- TBB */
	/* GRR: isn't sizeof(infile) equal to the size of the pointer? */
	memset (sig, 0, sizeof(sig));

	  /* first do a quick check that the file really is a PNG image; could
	   * have used slightly more general png_sig_cmp() function instead
	   */
	if (gdGetBuf(sig, 8, infile) < 8) {
		return NULL;
	}

	if (!png_check_sig (sig, 8)) { /* bad signature */
		return NULL;
	}

#ifndef PNG_SETJMP_NOT_SUPPORTED
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, &gdPngJmpbufStruct, gdPngErrorHandler, NULL);
#else
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
#endif
	if (png_ptr == NULL) {
		php_gd_error("gd-png error: cannot allocate libpng main struct");
		return NULL;
	}

	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL) {
		php_gd_error("gd-png error: cannot allocate libpng info struct");
		png_destroy_read_struct (&png_ptr, NULL, NULL);

		return NULL;
	}

	/* we could create a second info struct here (end_info), but it's only
	 * useful if we want to keep pre- and post-IDAT chunk info separated
	 * (mainly for PNG-aware image editors and converters)
	 */

	/* setjmp() must be called in every non-callback function that calls a
	 * PNG-reading libpng function
	 */
#ifndef PNG_SETJMP_NOT_SUPPORTED
	if (setjmp(gdPngJmpbufStruct.jmpbuf)) {
		php_gd_error("gd-png error: setjmp returns error condition");
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

		return NULL;
	}
#endif

	png_set_sig_bytes(png_ptr, 8);	/* we already read the 8 signature bytes */

	png_set_read_fn(png_ptr, (void *) infile, gdPngReadData);
	png_read_info(png_ptr, info_ptr);	/* read all PNG info up to image data */

	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
	if ((color_type == PNG_COLOR_TYPE_RGB) || (color_type == PNG_COLOR_TYPE_RGB_ALPHA)) {
		im = gdImageCreateTrueColor((int) width, (int) height);
	} else {
		im = gdImageCreate((int) width, (int) height);
	}
	if (im == NULL) {
		php_gd_error("gd-png error: cannot allocate gdImage struct");
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
		gdFree(image_data);
		gdFree(row_pointers);

		return NULL;
	}

	if (bit_depth == 16) {
		png_set_strip_16(png_ptr);
	} else if (bit_depth < 8) {
		png_set_packing (png_ptr); /* expand to 1 byte per pixel */
	}

	/* setjmp() must be called in every non-callback function that calls a
	 * PNG-reading libpng function
	 */
#ifndef PNG_SETJMP_NOT_SUPPORTED
	if (setjmp(gdPngJmpbufStruct.jmpbuf)) {
		php_gd_error("gd-png error: setjmp returns error condition");
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
		gdFree(image_data);
		gdFree(row_pointers);
		if (im) {
			gdImageDestroy(im);
		}
		return NULL;
	}
#endif


	switch (color_type) {
		case PNG_COLOR_TYPE_PALETTE:
			png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
#ifdef DEBUG
			php_gd_error("gd-png color_type is palette, colors: %d", num_palette);
#endif /* DEBUG */
			if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS)) {
				/* gd 2.0: we support this rather thoroughly now. Grab the
				 * first fully transparent entry, if any, as the value of
				 * the simple-transparency index, mostly for backwards
				 * binary compatibility. The alpha channel is where it's
				 * really at these days.
				 */
				int firstZero = 1;
				png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
				for (i = 0; i < num_trans; ++i) {
					im->alpha[i] = gdAlphaMax - (trans[i] >> 1);
					if ((trans[i] == 0) && (firstZero)) {
						transparent = i;
						firstZero = 0;
					}
				}
			}
			break;
		case PNG_COLOR_TYPE_GRAY:
		case PNG_COLOR_TYPE_GRAY_ALPHA:
			/* create a fake palette and check for single-shade transparency */
			if ((palette = (png_colorp) gdMalloc (256 * sizeof (png_color))) == NULL) {
				php_gd_error("gd-png error: cannot allocate gray palette");
				png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

				return NULL;
			}
			palette_allocated = TRUE;
			if (bit_depth < 8) {
				num_palette = 1 << bit_depth;
				for (i = 0; i < 256; ++i) {
					j = (255 * i) / (num_palette - 1);
					palette[i].red = palette[i].green = palette[i].blue = j;
				}
			} else {
				num_palette = 256;
				for (i = 0; i < 256; ++i) {
					palette[i].red = palette[i].green = palette[i].blue = i;
				}
			}
			if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
				png_get_tRNS(png_ptr, info_ptr, NULL, NULL, &trans_gray_rgb);
				if (bit_depth == 16) {	/* png_set_strip_16() not yet in effect */
					transparent = trans_gray_rgb->gray >> 8;
				} else {
					transparent = trans_gray_rgb->gray;
				}
				/* Note slight error in 16-bit case:  up to 256 16-bit shades
				 * may get mapped to a single 8-bit shade, and only one of them
				 * is supposed to be transparent.  IOW, both opaque pixels and
				 * transparent pixels will be mapped into the transparent entry.
				 * There is no particularly good way around this in the case
				 * that all 256 8-bit shades are used, but one could write some
				 * custom 16-bit code to handle the case where there are gdFree
				 * palette entries.  This error will be extremely rare in
				 * general, though.  (Quite possibly there is only one such
				 * image in existence.)
				 */
			}
int
main(int argc, char *argv[])
{
	FILE *fin = NULL;
	FILE *fout = NULL;
	gdImagePtr im_in = NULL, im = NULL;
	char *buf = NULL;
	int bufsize, ret = 0;
	/* FIXME get these from the cmdline */
	int width = 128, height = 128;

	if (argc != 4) {
		fprintf (stderr,
			 "Usage: %s <-d|-c> <inputfile> <outputfile>\n",
			 argv[0]);
		ret = 1;
		goto exit;
	}

	fin = fopen(argv[2], "r");
	if (!fin) {
		fprintf (stderr, "Error opening: %s: %s\n", argv[2],
			 strerror(errno));
		ret = 1;
		goto exit;
	}

	fout = fopen(argv[3], "w");
	if (!fout) {
		fprintf (stderr, "Error opening: %s: %s\n", argv[3],
			 strerror(errno));
		ret = 1;
		goto exit;
	}

	bufsize = width * height;
	buf = malloc(bufsize);
	if (!buf) {
		fprintf (stderr, "Error allocating memory\n");
		ret = 1;
		goto exit;
	}

	im = gdImageCreateTrueColor(width, height);
	if (!im) {
		fprintf (stderr, "Error allocating memory\n");
		ret = 1;
		goto exit;
	}

	if (!strcmp(argv[1], "-d")) {
		if (fread(buf, 1, bufsize, fin) != bufsize) {
			fprintf (stderr, "Error reading: %s: %s\n", argv[2],
				 strerror(errno));
			ret = 1;
			goto exit;
		}
		ax203_decode2(buf, im->tpixels, width, height);
		gdImagePng (im, fout);
	} else if (!strcmp(argv[1], "-c")) {
		im_in = gdImageCreateFromPng(fin);
		if (im_in == NULL) {
			rewind(fin);
			im_in = gdImageCreateFromGif(fin);
		}
		if (im_in == NULL) {
			rewind(fin);
			im_in = gdImageCreateFromWBMP(fin);
		}
		/* gdImageCreateFromJpegPtr is chatty on error,
		   so call it last */
		if (im_in == NULL) {
			rewind(fin);
			im_in = gdImageCreateFromJpeg(fin);
		}
		if (im_in == NULL) {
			fprintf (stderr,
			       "Error unrecognized file format for file: %s\n",
			       argv[2]);
			ret = 1;
			goto exit;
		}

		gdImageCopyResampled (im, im_in, 0, 0, 0, 0,
				      im->sx, im->sy,
				      im_in->sx, im_in->sy);
		gdImageSharpen(im, 100);
		ax203_encode2(im->tpixels, buf, width, height);

		if (fwrite (buf, 1, bufsize, fout) != bufsize) {
			fprintf (stderr, "Error writing: %s: %s\n", argv[3],
				 strerror(errno));
			ret = 1;
			goto exit;
		}
	} else {
		fprintf (stderr, "%s: unkown option: %s\n", argv[0], argv[1]);
		ret = 1;
		goto exit;
	}

exit:
	if (fin)
		fclose (fin);
	if (fout)
		fclose (fout);
	if (buf)
		free (buf);
	if (im)
		gdImageDestroy (im);
	if (im_in)
		gdImageDestroy (im_in);
	return ret;
}
Beispiel #5
0
int main()
{
	gdImagePtr im;
	int error = 0;
	int c, c1, c2, c3, c4, color;

	im = gdImageCreateTrueColor(5, 5);
	c = gdImageColorResolve(im, 255, 0, 255);
	c2 = gdImageColorResolveAlpha(im, 255, 0, 255, 100);
	gdImageDestroy(im);

	if (gdTestAssert(c == 0xFF00FF) != 1) {
		error = -1;
	}
	if (gdTestAssert(c2 == 0x64FF00FF) != 1) {
		error = -1;
	}

	im = gdImageCreate(5, 5);

	c1 = gdImageColorResolve(im, 255, 0, 255);
	c2 = gdImageColorResolve(im, 255, 200, 0);
	c3 = gdImageColorResolveAlpha(im, 255, 0, 255, 100);
	c4 = gdImageColorResolveAlpha(im, 255, 34, 255, 100);

	if (gdTestAssert(c1 == 0) != 1) {
		error = -1;
	}
	if (gdTestAssert(c2 == 1) != 1) {
		error = -1;
	}
	if (gdTestAssert(c3 == 2) != 1) {
		error = -1;
	}
	if (gdTestAssert(c4 == 3) != 1) {
		error = -1;
	}

	color = gdTrueColorAlpha(gdImageRed(im, c1), gdImageGreen(im, c1),
					gdImageBlue(im, c1), 0);
	if (gdTestAssert(color == 0xFF00FF) != 1) {
		error = -1;
	}
	color = gdTrueColorAlpha(gdImageRed(im, c2), gdImageGreen(im, c2),
					gdImageBlue(im, c2), 0);
	if (gdTestAssert(color == 0xFFC800) != 1) {
		error = -1;
	}
	color = gdTrueColorAlpha(gdImageRed(im, c3), gdImageGreen(im, c3),
					gdImageBlue(im, c3), 0);
	if (gdTestAssert(color == 0xFF00FF) != 1) {
		error = -1;
	}
	color = gdTrueColorAlpha(gdImageRed(im, c4), gdImageGreen(im, c4),
					gdImageBlue(im, c4), 0);
	if (gdTestAssert(color == 0xFF22FF) != 1) {
		error = -1;
	}
	gdImageDestroy(im);

	return error;
}
Beispiel #6
0
/*
  Function: gdImageCreateFromXbm

    <gdImageCreateFromXbm> is called to load images from X bitmap
    format files. Invoke <gdImageCreateFromXbm> with an already opened
    pointer to a file containing the desired
    image. <gdImageCreateFromXbm> returns a <gdImagePtr> to the new
    image, or NULL if unable to load the image (most often because the
    file is corrupt or does not contain an X bitmap format
    image). <gdImageCreateFromXbm> does not close the file.

    You can inspect the sx and sy members of the image to determine
    its size. The image must eventually be destroyed using
    <gdImageDestroy>.

  Parameters:

    fd - The input FILE pointer

  Returns:

    A pointer to the new image or NULL if an error occurred.

  Example:

    > gdImagePtr im;
    > FILE *in;
    > in = fopen("myxbm.xbm", "rb");
    > im = gdImageCreateFromXbm(in);
    > fclose(in);
    > // ... Use the image ...
    > gdImageDestroy(im);
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromXbm(FILE * fd)
{
	char fline[MAX_XBM_LINE_SIZE];
	char iname[MAX_XBM_LINE_SIZE];
	char *type;
	int value;
	unsigned int width = 0, height = 0;
	int fail = 0;
	int max_bit = 0;

	gdImagePtr im;
	int bytes = 0, i;
	int bit, x = 0, y = 0;
	int ch;
	char h[8];
	unsigned int b;

	rewind(fd);
	while (fgets(fline, MAX_XBM_LINE_SIZE, fd)) {
		fline[MAX_XBM_LINE_SIZE-1] = '\0';
		if (strlen(fline) == MAX_XBM_LINE_SIZE-1) {
			return 0;
		}
		if (sscanf(fline, "#define %s %d", iname, &value) == 2) {
			if (!(type = strrchr(iname, '_'))) {
				type = iname;
			} else {
				type++;
			}

			if (!strcmp("width", type)) {
				width = (unsigned int) value;
			}
			if (!strcmp("height", type)) {
				height = (unsigned int) value;
			}
		} else {
			if ( sscanf(fline, "static unsigned char %s = {", iname) == 1
			  || sscanf(fline, "static char %s = {", iname) == 1)
			{
				max_bit = 128;
			} else if (sscanf(fline, "static unsigned short %s = {", iname) == 1
					|| sscanf(fline, "static short %s = {", iname) == 1)
			{
				max_bit = 32768;
			}
			if (max_bit) {
				bytes = (width * height / 8) + 1;
				if (!bytes) {
					return 0;
				}
				if (!(type = strrchr(iname, '_'))) {
					type = iname;
				} else {
					type++;
				}
				if (!strcmp("bits[]", type)) {
					break;
				}
			}
 		}
	}
	if (!bytes || !max_bit) {
		return 0;
	}

	if(!(im = gdImageCreate(width, height))) {
		return 0;
	}
	gdImageColorAllocate(im, 255, 255, 255);
	gdImageColorAllocate(im, 0, 0, 0);
	h[2] = '\0';
	h[4] = '\0';
	for (i = 0; i < bytes; i++) {
		while (1) {
			if ((ch=getc(fd)) == EOF) {
				fail = 1;
				break;
			}
			if (ch == 'x') {
				break;
			}
		}
		if (fail) {
			break;
		}
		/* Get hex value */
		if ((ch=getc(fd)) == EOF) {
			break;
		}
		h[0] = ch;
		if ((ch=getc(fd)) == EOF) {
			break;
		}
		h[1] = ch;
		if (max_bit == 32768) {
			if ((ch=getc(fd)) == EOF) {
				break;
			}
			h[2] = ch;
			if ((ch=getc(fd)) == EOF) {
				break;
			}
			h[3] = ch;
		}
		sscanf(h, "%x", &b);
		for (bit = 1; bit <= max_bit; bit = bit << 1) {
			gdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0);
			if (x == im->sx) {
				x = 0;
				y++;
				if (y == im->sy) {
					return im;
				}
				break;
			}
		}
	}

	gd_error("EOF before image was complete");
	gdImageDestroy(im);
	return 0;
}
Beispiel #7
0
int main(int argc, char * argv[]){
  gdImagePtr im;
  int black;
  int white;

  int imagex = 500,imagey=500;

  if(argc < 3) {
    printf("usage: ./pdplot code.p out.png [width px] [height px] < data.d\n");
    exit(0);
  } else if(argc > 3){
    imagex = atoi(argv[3]);
    if(argc > 4)
      imagey = atoi(argv[4]);
  }

  FILE * infile, *outfile;
  infile = fopen(argv[1],"r");
  if(infile == NULL){
    perror("Unable to open input file.");
    exit(1);
  }

  outfile = fopen(argv[2],"wb");
  if(outfile == NULL){
    perror("Unable to open output file.");
    exit(1);
  }

  short int PDPmem[65536]; // Memory
  unsigned short int IP=0,SP,FP,GP; // Set up the internal registers
  unsigned short int x=0,y=0; // Current pen location
  char pen=1,N=0,Z=0; // Whether the pen is up or down, and the test bits

  char c;
  char buffer[8],*ptr;
  int i;

  buffer[7] = 0;

  while(1){
    while(!feof(infile) && isspace(c=fgetc(infile)));
    
    ungetc(c,infile);
    
    ptr = buffer;
    while(!feof(infile) && !isspace(c=fgetc(infile))){
      *ptr++ = c;
      if(ptr == buffer+7){
	printf("Invalid input file\n");
	exit(1);
      }
    }
    *ptr = '\0';

    if(!buffer[0]){
      break;
    }
    PDPmem[IP++]=(short int) strtol(buffer,NULL,10);

    if(feof(infile)){
      break;
    }
  }

  fclose(infile);

  GP = IP-1;
  SP = IP-1;
  FP = IP-1;
  IP = 0;

  im =gdImageCreate(imagex,imagey); // Create the canvas.
  
  white = gdImageColorAllocate(im,255,255,255);
  black = gdImageColorAllocate(im,0,0,0);

  // Main loop begins here
  
  while(1){
    switch(PDPmem[IP] & HIGHBYTE){
    case up:
      pen = 0;
      break;
    case down:
      pen = 1;
      break;
    case move:
      if(pen){
	gdImageLine(im,x,imagey-y-1,PDPmem[SP-1],imagey - PDPmem[SP]-1,black);
      }
      x = PDPmem[SP-1];
      y = PDPmem[SP];
      SP-=2;
      break;
    case add:
      PDPmem[SP-1] += PDPmem[SP];
      SP-=1;
      break;
    case sub:
      PDPmem[SP-1] -= PDPmem[SP];
      SP-=1;
      break;
    case neg:
      PDPmem[SP] *= -1;
      break;
    case mul:
      PDPmem[SP-1] *= (signed short int)PDPmem[SP];
      SP-=1;
      break;
    case test:
      Z = PDPmem[SP] == 0;
      N = PDPmem[SP] < 0;
      break;
    case ret:
      SP=FP-2;
      IP= PDPmem[FP];
      FP = PDPmem[FP-1];
      continue;
    case loadg:
      PDPmem[++SP] = PDPmem[GP+(signed char)(PDPmem[IP] & LOWBYTE)];
      break;
    case loadf:
      PDPmem[++SP] = PDPmem[FP+(signed char)(PDPmem[IP] & LOWBYTE)];
      break;
    case storeg:
      PDPmem[GP+(signed char)(PDPmem[IP] & LOWBYTE)] = PDPmem[SP--];
      break;
    case storef:
      PDPmem[FP+(signed char)(PDPmem[IP] & LOWBYTE)] = PDPmem[SP--];
      break;
    case readg:
      scanf("%hd",PDPmem +GP+(signed char)(PDPmem[IP] & LOWBYTE));
      break;
    case readf:
      scanf("%hd",PDPmem +FP+(signed char)(PDPmem[IP] & LOWBYTE));
      break;
    case jsr:
      PDPmem[++SP] = FP;
      PDPmem[++SP] = IP+2; // Pass this instruction and the jump;
      FP = SP;
      IP = PDPmem[IP+1];
      continue;
    case jmp:
      IP = PDPmem[IP+1];
      continue;
    case jeq:
      if(Z){
	IP = PDPmem[IP+1];
	continue;
      }
      IP++;
      break;
    case jlt:
      if(N){
	IP = PDPmem[IP+1];
	continue;
      }
      IP++;
      break;
    case push:
      PDPmem[++SP]= PDPmem[IP+1];
      IP++;
      break;
    case pop:
      SP -= PDPmem[IP+1];
      IP++;
      break;
    case halt:
      pen = 2;
      break;
    default:
      printf("Invalid instruction: %hd at %hd\n",PDPmem[IP],IP);
      exit(1);
    }
    if(pen == 2){
      break;
    }
    if(IP == 65535){
      printf("Instruction pointer out of bounds\n");
      exit(1);
    }
    IP++;
  }
  
  
  gdImagePng(im,outfile);
  fclose(outfile);

  gdImageDestroy(im);
  return 0;
}
Beispiel #8
0
static void gd_freeimage(usershape_t *us)
{
    gdImageDestroy((gdImagePtr)us->data);
}
int main(int argc, char **argv)
{

	int ret, verbose = 0; unsigned int i;
	char *affix = NULL;
	char *prefix = NULL;
	int opt = 0;
	int len = 0;
	char *png_filename = NULL;
	unsigned int entries = DEFAULT_ENTRIES;
	unsigned int table_size = DEFAULT_HASHTABLE_SIZE;
	hi_handle_t *hi_handle;
	uint32_t (*hashf)(const uint8_t *, uint32_t);
	const char *hashfname;

	hashf = NULL;

	while ((opt = getopt(argc, argv, "hqn:l:p:t:a:g:f:v")) != -1) {
		switch (opt) {
		case 'q':
			{
			int max_fd, std_fd, j;
			if ((max_fd = (int) sysconf(_SC_OPEN_MAX)) < 0) {
				max_fd = 256;
			}
			for (j = max_fd - 1; j >= 0; --j) {
				close(j);
			}
			std_fd = open("/dev/null", O_RDWR);
			dup(std_fd);
			dup(std_fd);
			}
			break;
		case 'f':
			if (!(strcasecmp(optarg, "elf"))) {
				hashf = lhi_hash_elf;
				hashfname = "lhi_hash_elf";
			} else if (!(strcasecmp(optarg, "torek"))) {
				hashf = lhi_hash_torek;
				hashfname = "lhi_hash_torek";
			} else if (!(strcasecmp(optarg, "dumb1"))) {
				hashf = lhi_hash_dumb1;
				hashfname = "lhi_hash_dumb1";
			} else if (!(strcasecmp(optarg, "phong"))) {
				hashf = lhi_hash_phong;
				hashfname = "lhi_hash_phong";
			} else {
				fprintf(stderr, "Hashing function not supported: %s\n",
						optarg);
				usage(EXIT_FAILURE, argv[0]);
			}
			break;
		case 'h':
			usage(EXIT_SUCCESS, argv[0]);
			break;
		case 'n':
			entries = atoi(optarg);
			break;
		case 'l':
			len = atoi(optarg);
			break;
		case 'p':
			prefix = strdup(optarg);
			break;
		case 't':
			table_size = atoi(optarg);
			break;
		case 'v':
			verbose++;
			break;
		case 'a':
			affix = strdup(optarg);
			break;
		case 'g':
#ifdef HAVE_LIBGD
			png_filename = strdup(optarg);
# else
			fprintf(stderr, "sorry - you build without gd library support\n");
			usage(EXIT_FAILURE, argv[0]);
#endif
			break;
		case '?':
			fprintf(stderr, "No such option: `%c'\n\n", optopt);
			usage(EXIT_FAILURE, argv[0]);
			break;
		}
	}

	fputs("# String Distribution Hash Test\n", stderr);

	/* initialize secure[tm] rand() seed */
	init_seed();

	/* initialize hash table */
	ret = hi_init_str(&hi_handle, table_size);

	if (hashf != NULL) {
		lhi_sethashfunc(hi_handle, hashf);
		fprintf(stderr, "# take %s as hash function\n", hashfname);
	}

	/* fill hash table */
	for(i = 0; i < entries; i++) {

		char *key = NULL, *tmp_key;
		size_t key_len = 0;

		/* compound key */
		if (len == 0) {
			len = (rand() % (MAX_STRING_LEN - MIN_STRING_LEN + 1)) + MIN_STRING_LEN;
		}
		if (random_string(len, &tmp_key) < 0)
			exit(EXIT_FAILURE);

		if (prefix)
			key_len += strlen(prefix);
		key_len += strlen(tmp_key);
		if (affix)
			key_len += strlen(affix);


		key = malloc(key_len + 1);
		if (key == NULL) {
			fprintf(stderr, "malloc %s\n", strerror(errno));
			exit(1);
		}

		if (prefix != NULL) {
			sprintf(&key[0], "%s%s", prefix, tmp_key);
		} else {
			sprintf(key, "%s", tmp_key);
		}

		free(tmp_key);
		tmp_key = NULL;

		if (affix)
			strcat(key, affix);

		if (verbose >= 1)
			fprintf(stdout, "key: %s\n", key);

		ret = hi_insert_str(hi_handle, (void *) key, NULL);
		if (ret < 0)
			fprintf(stderr, "# WARNING: Can't insert key (maybe a duplicated key: %s)!\n", key);
	}

	/* print statistic */
	ret = hi_size(hi_handle);
	fprintf(stderr, "# hash table entries: %d\n", ret);

	if (png_filename) { /* grapical output */

#ifdef HAVE_LIBGD
# define RECT_SIZE 5
# define RECT_BODER_SIZE 1

		int j;
		uint32_t x, y;
		gdImagePtr im;
		FILE *pngout;
		int black, white, red, max_list_len = 0;


		/* calculate maximum listsize */
		for(i = 0; i < table_size; i++) {
			int tmp_bucket_size = hi_bucket_size(hi_handle, i);
			max_list_len = max(max_list_len, tmp_bucket_size);
		}


		/* create a image with max_list_len X table_size */
		im = gdImageCreate((max_list_len * (RECT_SIZE + RECT_BODER_SIZE * 2)) + 2,
				(table_size * ((RECT_SIZE + RECT_BODER_SIZE * 2)) + 2));

		black = gdImageColorAllocate(im, 255, 231, 186);
		white = gdImageColorAllocate(im, 255, 165, 79);
		red   = gdImageColorAllocate(im, 205, 102, 29);

		x = 1;
		y = 1;

		for (i = 0; i < table_size; i++) {
			int bucket_size =  hi_bucket_size(hi_handle, i);
			for (j = 0; j < bucket_size; j++) {
				gdImageFilledRectangle(im, x + 1, y + 1, x + RECT_SIZE, y + RECT_SIZE, white);
				gdImageRectangle(im, x, y, x + RECT_SIZE + (RECT_BODER_SIZE << 1), y + RECT_SIZE + (RECT_BODER_SIZE << 1), red);
				x += RECT_SIZE + (RECT_BODER_SIZE << 1);
			}
			x = 1;
			y += RECT_SIZE + (RECT_BODER_SIZE << 1);
		}

		pngout = fopen(png_filename, "wb");
		gdImagePng(im, pngout);
		fclose(pngout);
		gdImageDestroy(im);

# undef RECT_SIZE
# undef RECT_BODER_SIZE
#endif /* HAVE_LIBGD */

	}

	if (verbose >= 1) {  /* terminal output */
		for(i = 0; i < table_size; i++) {
			fprintf(stderr, "bucket no: %d bucket size: %d\n",
					i, hi_bucket_size(hi_handle, i));
		}

	}

	/* delete table */
	hi_fini(hi_handle);

	return 0;
}
JBDungeonPainterGD::~JBDungeonPainterGD() {
  gdImageDestroy( m_image );
}
Beispiel #11
0
/*
  Function: gdImageGifAnimAddCtx

    Adds an animation frame via a <gdIOCtxPtr>.  See gdImageGifAnimAdd>.

  Parameters:

    im          - The image to add.
    out         - The output <gdIOCtxPtr>.
    LocalCM     - Flag.  If 1, use a local color map for this frame.
    LeftOfs     - Left offset of image in frame.
    TopOfs      - Top offset of image in frame.
    Delay       - Delay before next frame (in 1/100 seconds)
    Disposal    - MODE: How to treat this frame when the next one loads.
    previm      - NULL or a pointer to the previous image written.

  Returns:

    Nothing.

*/
BGD_DECLARE(void) gdImageGifAnimAddCtx(gdImagePtr im, gdIOCtxPtr out,
                                       int LocalCM, int LeftOfs, int TopOfs,
                                       int Delay, int Disposal,
                                       gdImagePtr previm)
{
	gdImagePtr pim = NULL, tim = im;
	int interlace, transparent, BitsPerPixel;
	interlace = im->interlace;
	transparent = im->transparent;

	/* Default is no local color map */
	if(LocalCM < 0) {
		LocalCM = 0;
	}

	if(im->trueColor) {
		/* Expensive, but the only way that produces an
			acceptable result: mix down to a palette
			based temporary image. */
		pim = gdImageCreatePaletteFromTrueColor(im, 1, 256);
		if (!pim) {
			return;
		}
		tim = pim;
	}

	if (previm) {
		/* create optimized animation.  Compare this image to
		   the previous image and crop the temporary copy of
		   current image to include only changed rectangular
		   area.  Also replace unchanged pixels inside this
		   area with transparent color.  Transparent color
		   needs to be already allocated!
		   Preconditions:
		   TopOfs, LeftOfs are assumed 0

		   Images should be of same size.  If not, a temporary
		   copy is made with the same size as previous image.

		*/
		gdImagePtr prev_pim = 0, prev_tim = previm;
		int x, y;
		int min_x = 0;
		int min_y = tim->sy;
		int max_x = 0;
		int max_y = 0;
		int colorMap[256];

		if (previm->trueColor) {
			prev_pim = gdImageCreatePaletteFromTrueColor(previm, 1, 256);
			if (!prev_pim) {
				goto fail_end;
			}
			prev_tim = prev_pim;
		}

		for (x = 0; x < 256; ++x) {
			colorMap[x] = -2;
		}

		/* First find bounding box of changed areas. */
		/* first find the top changed row */
		for (y = 0; y < tim->sy; ++y) {
			for (x = 0; x < tim->sx; ++x) {
				if (!comparewithmap(prev_tim, tim,
				                    prev_tim->pixels[y][x],
				                    tim->pixels[y][x],
				                    colorMap)) {
					min_y = max_y = y;
					min_x = max_x = x;
					goto break_top;
				}
			}
		}

break_top:
		if (tim->sy == min_y) {
			/* No changes in this frame!! Encode empty image. */
			transparent = 0;
			min_x = min_y = 1;
			max_x = max_y = 0;
		} else {
			/* Then the bottom row */
			for (y = tim->sy - 1; y > min_y; --y) {
				for (x = 0; x < tim->sx; ++x) {
					if (!comparewithmap
					        (prev_tim, tim,
					         prev_tim->pixels[y][x],
					         tim->pixels[y][x],
					         colorMap)) {
						max_y = y;
						if(x < min_x) {
							min_x = x;
						}
						if(x > max_x) {
							max_x = x;
						}
						goto break_bot;
					}
				}
			}

break_bot:
			/* left side */
			for (x = 0; x < min_x; ++x) {
				for (y = min_y; y <= max_y; ++y) {
					if (!comparewithmap
					        (prev_tim, tim,
					         prev_tim->pixels[y][x],
					         tim->pixels[y][x],
					         colorMap)) {
						min_x = x;
						goto break_left;
					}
				}
			}

break_left:
			/* right side */
			for (x = tim->sx - 1; x > max_x; --x) {
				for (y = min_y; y <= max_y; ++y) {
					if (!comparewithmap
					        (prev_tim, tim,
					         prev_tim->pixels[y][x],
					         tim->pixels[y][x],
					         colorMap)) {
						max_x = x;
						goto break_right;
					}
				}
			}

break_right:
			;
		}

		LeftOfs = min_x;
		TopOfs = min_y;
		Disposal = 1;

		/* Make a copy of the image with the new offsets.
		   But only if necessary. */
		if (min_x != 0 || max_x != tim->sx - 1
		        || min_y != 0 || max_y != tim->sy - 1
		        || transparent >= 0) {

			gdImagePtr pim2 = gdImageCreate(max_x-min_x + 1, max_y-min_y + 1);

			if (!pim2) {
				if (prev_pim) {
					gdImageDestroy(prev_pim);
				}
				goto fail_end;
			}

			gdImagePaletteCopy(pim2, LocalCM ? tim : prev_tim);
			gdImageCopy(pim2, tim, 0, 0, min_x, min_y,
			            max_x - min_x + 1, max_y - min_y + 1);

			if (pim) {
				gdImageDestroy(pim);
			}

			tim = pim = pim2;
		}

		/* now let's compare pixels for transparent
		   optimization.  But only if transparent is set. */
		if (transparent >= 0) {
			for(y = 0; y < tim->sy; ++y) {
				for (x = 0; x < tim->sx; ++x) {
					if(comparewithmap
					        (prev_tim, tim,
					         prev_tim->pixels[min_y + y][min_x + x],
					         tim->pixels[y][x], 0)) {
						gdImageSetPixel(tim, x, y, transparent);
						break;
					}
				}
			}
		}

		if(prev_pim) {
			gdImageDestroy(prev_pim);
		}
	}

	BitsPerPixel = colorstobpp(tim->colorsTotal);

	/* All set, let's do it. */
	GIFAnimEncode(
	    out, tim->sx, tim->sy, LeftOfs, TopOfs, interlace, transparent,
	    Delay, Disposal, BitsPerPixel,
	    LocalCM ? tim->red : 0, tim->green, tim->blue, tim);

fail_end:
	if(pim) {
		/* Destroy palette based temporary image. */
		gdImageDestroy(pim);
	}
}
static void water_mark(void *conf)
{
	ngx_image_conf_t *info = conf;
	int water_w=0;//水印宽度
	int water_h=0;//水印高度
	int posX = 0;//X位置
	int posY = 0;//Y位置
	int water_color = 0;//文字水印GD颜色值
	char *water_text;//图片文字
	char *water_font;//文字字体
	char *water_color_text;//图片颜色值
	water_text = NULL;
	water_font = NULL;
	water_color_text = NULL;

	if(info->water_status)//如果水印功能打开了
	{

		if(info->water_type == 0)//如果为图片水印
		{
			if(file_exists((char *)info->water_image.data) == 0)//判断水印图片是否存在
			{
				water_image_from(conf);//获取水印图片信息
				if(info->water_im != NULL)//判断对象是否为空
				{
					water_w = info->water_im->sx;
					water_h = info->water_im->sy;
				}
			}
			else
			{
				return;//水印图片不存在
			}
		}
		else//文字水印
		{
			water_text = (char *) info->water_text.data;
			water_color_text = (char *) info->water_color.data;
			water_font = (char *)info->water_font.data;
			if(file_exists((char *)water_font) == 0)//如果水印字体存在
			{
				int R,G,B;
				char R_str[3],G_str[3],B_str[3];
				int brect[8];
				gdImagePtr font_im;
				font_im = gdImageCreateTrueColor(info->dst_im->sx,info->dst_im->sy);
				sprintf(R_str,"%.*s",2,water_color_text+1);
				sprintf(G_str,"%.*s",2,water_color_text+3);
				sprintf(B_str,"%.*s",2,water_color_text+5);
				sscanf(R_str,"%x",&R);
				sscanf(G_str,"%x",&G);
				sscanf(B_str,"%x",&B);
				water_color = gdImageColorAllocate(info->dst_im,R,G,B);
				gdImageStringFT(font_im, &brect[0], water_color, water_font, info->water_font_size, 0.0, 0, 0,water_text/*, &strex*/);
				//water_w = abs(brect[2] - brect[6] + 10);
				water_w = abs(brect[2] - brect[6] + 10);
				water_h = abs(brect[3] - brect[7]);
				gdImageDestroy(font_im);
			}

		}
		if( (info->width < info->water_width_min) || info->height < info->water_height_min)
		{
			return;//如果图片宽度/高度比配置文件里规定的宽度/高度宽度小
		}
		if ((info->width < water_w) || (info->height < water_h))
		{
			return;//如果图片宽度/高度比水印宽度/高度宽度小
		}
		if(info->water_pos < 1 ||info->water_pos > 9)
		{
			srand((unsigned)time(NULL));
			//info->water_pos = rand() % 9 + 1;
			info->water_pos = 1+(int)(9.0*rand()/(RAND_MAX+1.0));
			//info->water_pos = rand() % 9;
		}
		switch(info->water_pos)
		{
		case 1:
			posX = 10;
			posY = 15;
			break;
		case 2:
			posX = (info->width - water_w) / 2;
			posY = 15;
			break;
		case 3:
			posX = info->width - water_w;
			posY = 15;
			break;
		case 4:
			posX = 0;
			posY = (info->height - water_h) / 2;
			break;
		case 5:
			posX = (info->width - water_w) / 2;
			posY = (info->height - water_h) / 2;
			break;
		case 6:
			posX = info->width - water_w;
			posY = (info->height - water_h) / 2;
			break;
		case 7:
			posX = 0;
			posY = (info->height - water_h);
			break;
		case 8:
			posX = (info->width - water_w) /2;
			posY = info->width - water_h;
			break;
		case 9:
			posX = info->width - water_w;
			posY = info->height - water_h;
			break;
		default:
			posX = info->width - water_w;
			posY = info->height - water_h;
			break;
		}
		if(info->water_type == 0)
		{
			gdImagePtr tmp_im;
			tmp_im = NULL;
			tmp_im = gdImageCreateTrueColor(water_w, water_h);
			gdImageCopy(tmp_im, info->dst_im, 0, 0, posX, posY, water_w, water_h);
			gdImageCopy(tmp_im, info->water_im, 0, 0, 0, 0, water_w, water_h);
			gdImageCopyMerge(info->dst_im, tmp_im,posX, posY, 0, 0, water_w,water_h,info->water_transparent);
			gdImageDestroy(tmp_im);
		}
		else
		{
			gdImageAlphaBlending(info->dst_im,-1);
			gdImageSaveAlpha(info->dst_im,0);
			gdImageStringFT(info->dst_im,0,water_color,water_font,info->water_font_size, 0.0, posX, posY,water_text);
		}
	}
}
static ngx_int_t ngx_http_image_handler(ngx_http_request_t *r)
{
	u_char                    *last;
	size_t                     root;
	ngx_int_t                  rc;
	ngx_str_t                  path;
	char                       request_uri[255];
	int                        request_uri_len;
	ngx_image_conf_t  *conf;
	conf = ngx_http_get_module_loc_conf(r, ngx_http_image_module);
	if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD)))
	{
		return NGX_HTTP_NOT_ALLOWED;
	}
	if (r->headers_in.if_modified_since)
	{
		return NGX_HTTP_NOT_MODIFIED;
	}

	if (r->uri.data[r->uri.len - 1] == '/')
	{
		return NGX_DECLINED;
	}

	rc = ngx_http_discard_request_body(r);
	if (rc != NGX_OK)
	{
		return rc;
	}
	last = ngx_http_map_uri_to_path(r, &path, &root, 0);
	if (last == NULL)
	{
		return NGX_HTTP_INTERNAL_SERVER_ERROR;
	}
	if(file_exists((char*) path.data) == -1)
	{
		request_uri_len = strlen((char *)r->uri_start) - strlen((char *)r->uri_end);
		strncpy(request_uri, (char *)r->uri_start, request_uri_len);
		request_uri[request_uri_len] = '\0';
		conf->request_dir = dirname(request_uri);
		conf->url = request_uri;//请求的URL地址
		conf->dest_file = (char *)path.data;
		check_image_type(conf);//检查图片类型(根据后缀进行简单判断)
		if( conf->dest_type > 0 )
		{

			if (parse_image_info(conf) == 0)//解析并处理请求的图片URL
			{

				make_thumb(conf);//生成图片缩略图
				water_mark(conf);//图片打上水印
				thumb_to_string(conf);//GD对象转换成二进制字符串
				if(conf->image_output == 0)
				{
					write_img(conf);//保存图片缩略图到文件
				}
				if(conf->src_im != NULL){
					gdImageDestroy(conf->src_im);
				}
				if(conf->dst_im != NULL)
				{
					gdImageDestroy(conf->dst_im);
				}
				if(conf->water_im != NULL)
				{
					gdImageDestroy(info->water_im);
				}
				if(conf->w_margin > 0 && conf->w_im != NULL)
				{
			        	gdImageDestroy(conf->w_im);//释放补白边的对象
				}
				if(conf->image_output == 1)
				{
					return output(r,conf,ngx_http_image_types[conf->dest_type]);
				}
			}
		}
	}
	return NGX_DECLINED;
}
Beispiel #14
0
/*
 * Save GPU FFT-complex matrix to PNG files via gd
 *  spectrum = 1       -> save complex spectrum to <basename>-spectrum.png
 *  phase_angle = 1    -> save complex phase angle to <basename>-phaseang.png
 *  power_spectrum = 1 -> save complex phase angle to <basename>-powspect.png
 * 
 * return -1 on error, 0 otherwise
 */
int gpufft_result_save( struct GPU_FFT_COMPLEX *data, int step, int spectrum, int phase_angle, int power_spectrum, uint32_t w, uint32_t h, char *basename )
{
	FILE *f_s, *f_pa, *f_ps;
	gdImage *image_s, *image_pa, *image_ps;
	uint32_t i, j, g, color;
	struct GPU_FFT_COMPLEX *dat;
	float d, max_s, max_pa, max_ps, power;
	
	char fn_s[256],fn_pa[256],fn_ps[256];
	
	if( !spectrum && !phase_angle && !power_spectrum )
	{
		WARN("nothing to do");
		return(0);
	}
	
	if( spectrum )
	{
		snprintf( fn_s, 255, "%s-spectrum.png", basename);
		f_s = fopen(fn_s,"wb");
		if(!f_s)
		{
			ERROR("Error opening file for output: %s", fn_s);
			ERROR("fopen: %s", strerror(errno));
			return(-1);
		}

		image_s = gdImageCreateTrueColor(w,h);
		if(!image_s)
		{
			ERROR("Cannot create image");
			fclose(f_s);
			return(-1);
		}
	}

	if( phase_angle )
	{
		snprintf( fn_pa, 255, "%s-phaseang.png", basename);
		f_pa = fopen(fn_pa,"wb");
		if(!f_pa)
		{
			ERROR("Error opening file for output: %s", fn_pa);
			ERROR("fopen: %s", strerror(errno));
			return(-1);
		}

		image_pa = gdImageCreateTrueColor(w,h);
		if(!image_pa)
		{
			ERROR("Cannot create image");
			fclose(f_pa);
			return(-1);
		}
	}

	if( phase_angle )
	{
		snprintf( fn_ps, 255, "%s-powspect.png", basename);
		f_ps = fopen(fn_ps,"wb");
		if(!f_ps)
		{
			ERROR("Error opening file for output: %s", fn_ps);
			ERROR("fopen: %s", strerror(errno));
			return(-1);
		}

		image_ps = gdImageCreateTrueColor(w,h);
		if(!image_ps)
		{
			ERROR("Cannot create image");
			fclose(f_ps);
			return(-1);
		}
	}

	
	max_s = max_pa = max_ps =0;
	for(j=0;j<h;j++)
	{
		dat = data + j*step;
		for(i=0;i<w;i++,dat++)
		{
			if( spectrum || power_spectrum )
				power = powf(dat[i].re,2) + powf(dat[i].im,2);
			if( spectrum ) {
				d = sqrtf(power);
				if( d> max_s )
					max_s = d;
			}
			if( phase_angle ) {
				d = atan2(dat[i].im, dat[i].re);
				if( d> max_pa )
					max_pa = d;
			}
			if( power_spectrum ) {
				d = power;
				if( d> max_ps )
					max_ps = d;
			}
		}		
	}
	

	
	
	for( j = 0; j < h; j++ )
	{
		dat = data + j*step;
		for( i = 0; i < w; i++,dat++ )
		{
			if( spectrum || power_spectrum )
				power = powf(dat->re,2) + powf(dat->im,2);
			if( spectrum )
			{
				d = sqrtf(power);
				g = round(0xff * d/max_s);
				color = g | (g<<8) | (g<<16);
				gdImageSetPixel( image_s, i, j, color & 0xffffffl );
			}
			if( phase_angle )
			{
				d = atan2(dat->im, dat->re);
				g = round(0xff * d/max_pa);
				color = g | (g<<8) | (g<<16);
				gdImageSetPixel(image_pa, i, j, color & 0xffffffl );
			}
			if( power_spectrum )
			{
				d = power;
				g = round(0xff * d/max_ps);
				color = g | (g<<8) | (g<<16);
				gdImageSetPixel(image_ps, i, j, color & 0xffffffl );
			}
		}
	}
	

	
	if( spectrum ){ 
		gdImagePng(image_s, f_s);
		fclose( f_s );
		gdImageDestroy(image_s);
	}
	if( phase_angle ){ 
		gdImagePng(image_pa, f_pa);
		fclose( f_pa );
		gdImageDestroy(image_pa);
	}
	if( power_spectrum ){ 
		gdImagePng(image_ps, f_ps);
		fclose( f_ps );
		gdImageDestroy(image_ps);
	}

	return(0);
}
Beispiel #15
0
gdImage *fx_crop(gdImage *src, char *options)
{
	char arg[32];
	int w, h, x, y;
	gdImage *im;
	
	if(argncpy(arg, 32, options, ", \t", 0, 0))
	{
		WARN("Invalid area to crop: %s", arg);
		return(src);
	}
	
	w = argtol(arg, "x ", 0, 0, 10);
	h = argtol(arg, "x ", 1, 0, 10);
	
	if(w < 0 || h < 0)
	{
		WARN("Invalid area to crop: %s", arg);
		return(src);
	}
	
	/* Make sure crop area resolution is smaller than the source image. */
	if(w > gdImageSX(src) ||
	   h > gdImageSY(src))
	{
		WARN("Crop area is larger than the image!");
		return(src);
	}
	
	/* Get the offset. */
	x = -1;
	y = -1;
	
	if(!argncpy(arg, 32, options, ", \t", 1, 0))
	{
		x = argtol(arg, "x ", 0, 0, 10);
		y = argtol(arg, "x ", 1, 0, 10);
	}
	
	if(x < 0 || y < 0)
	{
		/* By default crop the center of the image. */
		x = (gdImageSX(src) - w) / 2;
		y = (gdImageSY(src) - h) / 2;
	}
	
	MSG("Cropping image from %ix%i [offset: %ix%i] -> %ix%i.",
	    gdImageSX(src), gdImageSY(src), x, y, w, h);
	
	im = gdImageCreateTrueColor(w, h);
	if(!im)
	{
		WARN("Out of memory.");
		return(src);
	}
	
	gdImageCopy(im, src, 0, 0, x, y, w, h);
	
	gdImageDestroy(src);
	
	return(im);
}
Beispiel #16
0
/*------------------------------------------------------------*/
void
gifi_finish_output (void)
{
    int row, col, value, r, g, b, error, right, leftbelow, below;
    unsigned char *buffer, *buf;
    int *rcurr, *gcurr, *bcurr, *rnext, *gnext, *bnext, *swap;

    image_render();

    buffer = malloc (output_width * 3 * sizeof (unsigned char));
    rcurr = malloc ((output_width + 1) * sizeof (int));
    gcurr = malloc ((output_width + 1) * sizeof (int));
    bcurr = malloc ((output_width + 1) * sizeof (int));
    rnext = calloc (output_width + 1, sizeof (int));
    gnext = calloc (output_width + 1, sizeof (int));
    bnext = calloc (output_width + 1, sizeof (int));

    for (row = 0; row < output_height; row++) {

        swap = rnext;
        rnext = rcurr;
        rcurr = swap;
        swap = gnext;
        gnext = gcurr;
        gcurr = swap;
        swap = bnext;
        bnext = bcurr;
        bcurr = swap;
        for (col = 0; col < output_width; col++) {
            rnext[col] = 0;
            gnext[col] = 0;
            bnext[col] = 0;
        }

        glReadPixels (0, output_height - row - 1, output_width, 1,
                      GL_RGB, GL_UNSIGNED_BYTE, buffer);
        buf = buffer;
        for (col = 0; col < output_width; col++) {
            rcurr[col] += *buf++;
            gcurr[col] += *buf++;
            bcurr[col] += *buf++;
        }

        for (col = 0; col < output_width; col++) { /* error diffusion */

            value = rcurr[col];
            for (r = 0; 51 * (r + 1) - 26 < value; r++);
            error = value - r * 51;
            right = (7 * error) / 16;
            leftbelow = (3 * error) / 16;
            below = (5 * error) / 16;
            rcurr[col+1] += right;
            if (col > 0) rnext[col-1] += leftbelow;
            rnext[col] += below;
            rnext[col+1] = error - right - leftbelow - below;

            value = gcurr[col];
            for (g = 0; 51 * (g + 1) - 26 < value; g++);
            error = value - g * 51;
            right = (7 * error) / 16;
            leftbelow = (3 * error) / 16;
            below = (5 * error) / 16;
            gcurr[col+1] += right;
            if (col > 0) gnext[col-1] += leftbelow;
            gnext[col] += below;
            gnext[col+1] = error - right - leftbelow - below;

            value = bcurr[col];
            for (b = 0; 51 * (b + 1) - 26 < value; b++);
            error = value - b * 51;
            right = (7 * error) / 16;
            leftbelow = (3 * error) / 16;
            below = (5 * error) / 16;
            bcurr[col+1] += right;
            if (col > 0) bnext[col-1] += leftbelow;
            bnext[col] += below;
            bnext[col+1] = error - right - leftbelow - below;

            gdImageSetPixel (image, col, row, ((r * 6) + g) * 6 + b);
        }
    }

    free (rnext);
    free (gnext);
    free (bnext);
    free (rcurr);
    free (gcurr);
    free (bcurr);
    free (buffer);

    gdImageGif (image, outfile);
    gdImageDestroy (image);

    image_close();
}
Beispiel #17
0
gdImage *fx_flip(gdImage *src, char *options)
{
	int i;
	char d[32];
	
	i = 0;
	while(!argncpy(d, 32, options, ", \t", i++, 0))
	{
		if(*d == 'v')
		{
			int y, h;
			gdImage *line;
			
			MSG("Flipping image vertically.");
			
			line = gdImageCreateTrueColor(gdImageSX(src), 1);
			h = gdImageSY(src) / 2;
			
			for(y = 0; y < h; y++)
			{
				/* Copy bottom line into buffer. */
				gdImageCopy(line, src,
				   0, 0,
				   0, gdImageSY(src) - y - 1,
				   gdImageSX(src), 1);
				
				/* Copy the top line onto the bottom. */
				gdImageCopy(src, src,
				   0, gdImageSY(src) - y - 1,
				   0, y,
				   gdImageSX(src), 1);
				
				/* Copy the buffer into the top. */
				gdImageCopy(src, line,
				   0, y,
				   0, 0,
				   gdImageSX(src), 1);
			}
			
			gdImageDestroy(line);
		}
		else if(*d == 'h')
		{
			int x, w;
			gdImage *line;
			
			MSG("Flipping image horizontally.");
			
			line = gdImageCreateTrueColor(1, gdImageSY(src));
			w = gdImageSX(src) / 2;
			
			for(x = 0; x < w; x++)
			{
				/* Copy right line into buffer. */
				gdImageCopy(line, src,
				   0, 0,
				   gdImageSX(src) - x - 1, 0,
				   1, gdImageSY(src));
				
				/* Copy the left line onto the right. */
				gdImageCopy(src, src,
				   gdImageSX(src) - x - 1, 0,
				   x, 0,
				   1, gdImageSY(src));
				
				/* Copy the buffer into the left. */
				gdImageCopy(src, line,
				   x, 0,
				   0, 0,
				   1, gdImageSY(src));
			}
			
			gdImageDestroy(line);
		}
		else WARN("Unknown flip direction: %s", d);
	}
	
	return(src);
}
Beispiel #18
0
int main(int argc, char *argv[])
{
   FILE *out;
   gdImage *im = NULL;
   int dc, bc;

   int c, i, arrdef[MAXAD];
   int width = 0, height = 0, iwidth = 0, iheight = 0;
   char *file = NULL, *s;

   if (argc < 2)
      usage(argv[0]), exit(1);

   opterr = 0;
   while ((c = getopt(argc, argv, "f:h:nw:W:H:")) != -1)
      switch (c)
      {
         case 'f':
            file = optarg;
            break;

         case 'h':
            height = atoi(optarg);
            break;

         case 'n':
            windf_station_circle(0);
            break;

         case 'w':
            width = atoi(optarg);
            break;

         case 'H':
            iheight = atoi(optarg);
            break;

         case 'W':
            iwidth = atoi(optarg);
            break;
      }

   //for (; argv[optind]; optind++) fprintf(stderr, "%s,", argv[optind]);

   //if (!width) width = DEF_W;
   //if (!height) height = DEF_H;

   if (!iwidth) iwidth = DEF_W;
   if (!iheight) iheight = DEF_H;
   if (!width) width = iwidth;
   if (!height) height = iheight;

   if (file == NULL)
      out = stdout;
   else if ((out = fopen(file, "r")) == NULL)
   {
      if (errno != ENOENT)
         perror("fopen(r)"), exit(1);
   }
   else
   {
      im = gdImageCreateFromPng(out);
      fclose(out);
   }

   if (im == NULL)
   {
      //im = gdImageCreate(width << 1, height << 1);
      im = gdImageCreateTrueColor(iwidth, iheight);
      bc = gdImageColorAllocate(im, 255, 255, 255);
      gdImageColorTransparent(im, bc);
      gdImageFilledRectangle(im, 0, 0, iwidth, iheight, bc);
   }

   for (; argv[optind]; optind++)
   {
      memset(arrdef, -1, sizeof(arrdef));
      s = strtok(argv[optind], ":");
      for (i = 0; s && (i < MAXAD); i++)
      {
         if (*s == '#')
         {
            arrdef[C] = strtol(s + 1, NULL, 16);
            continue;
         }
         arrdef[i] = strtol(s, NULL, 0);
         s = strtok(NULL, ":");
      }

      if (i < 2)
         fprintf(stderr, "ill wind_def\n"), exit(1);

      if (arrdef[CL] > 8)
         arrdef[CL] = 8;
      if (arrdef[CL] < 0)
         arrdef[CL] = 0;

      if (arrdef[X] == -1)
         arrdef[X] = im->sx >> 1;
      if (arrdef[Y] == -1)
         arrdef[Y] = im->sy >> 1;
      if (arrdef[W] == -1)
         arrdef[W] = width;
      if (arrdef[H] == -1)
         arrdef[H] = height;

      /*
   if (argc >= 4)
   {
      if ((out = fopen(argv[3], "w")) == NULL)
         perror("fopen"), exit(1);
   }
   else
      out = stdout;
      */

      if (arrdef[C] == -1)
         arrdef[C] = 0;

      dc = gdImageColorAllocate(im, (arrdef[C] >> 16) & 0xff, (arrdef[C] >> 8) & 0xff, arrdef[C] & 0xff);
      gdImageSetAntiAliased(im, dc);
      windf_col(gdAntiAliased);
      windf_drawc0(im, arrdef[X], arrdef[Y], arrdef[W], arrdef[H], arrdef[WDIR], arrdef[WS], dc, arrdef[CL]);
   }

   if (file == NULL)
      out = stdout;
   else
   {
      if ((out = fopen(file, "w")) == NULL)
         perror("fopen(w)"), exit(1);
   }

   gdImagePng(im, out);
   gdImageDestroy(im);

   fclose(out);

   return 0;
}
static ngx_buf_t *
ngx_http_image_resize(ngx_http_request_t *r, ngx_http_image_filter_ctx_t *ctx)
{
    int                            sx, sy, dx, dy, ox, oy, ax, ay, size,
                                   colors, palette, transparent, sharpen,
                                   red, green, blue, t;
    u_char                        *out;
    ngx_buf_t                     *b;
    ngx_uint_t                     resize;
    gdImagePtr                     src, dst;
    ngx_pool_cleanup_t            *cln;
    ngx_http_image_filter_conf_t  *conf;

    src = ngx_http_image_source(r, ctx);

    if (src == NULL) {
        return NULL;
    }

    sx = gdImageSX(src);
    sy = gdImageSY(src);

    conf = ngx_http_get_module_loc_conf(r, ngx_http_image_filter_module);

    if (!ctx->force
        && ctx->angle == 0
        && (ngx_uint_t) sx <= ctx->max_width
        && (ngx_uint_t) sy <= ctx->max_height)
    {
        gdImageDestroy(src);
        return ngx_http_image_asis(r, ctx);
    }

    colors = gdImageColorsTotal(src);

    if (colors && conf->transparency) {
        transparent = gdImageGetTransparent(src);

        if (transparent != -1) {
            palette = colors;
            red = gdImageRed(src, transparent);
            green = gdImageGreen(src, transparent);
            blue = gdImageBlue(src, transparent);

            goto transparent;
        }
    }

    palette = 0;
    transparent = -1;
    red = 0;
    green = 0;
    blue = 0;

transparent:

    gdImageColorTransparent(src, -1);

    dx = sx;
    dy = sy;

    if (conf->filter == NGX_HTTP_IMAGE_RESIZE) {

        if ((ngx_uint_t) dx > ctx->max_width) {
            dy = dy * ctx->max_width / dx;
            dy = dy ? dy : 1;
            dx = ctx->max_width;
        }

        if ((ngx_uint_t) dy > ctx->max_height) {
            dx = dx * ctx->max_height / dy;
            dx = dx ? dx : 1;
            dy = ctx->max_height;
        }

        resize = 1;

    } else if (conf->filter == NGX_HTTP_IMAGE_ROTATE) {

        resize = 0;

    } else { /* NGX_HTTP_IMAGE_CROP */

        resize = 0;

        if ((double) dx / dy < (double) ctx->max_width / ctx->max_height) {
            if ((ngx_uint_t) dx > ctx->max_width) {
                dy = dy * ctx->max_width / dx;
                dy = dy ? dy : 1;
                dx = ctx->max_width;
                resize = 1;
            }

        } else {
            if ((ngx_uint_t) dy > ctx->max_height) {
                dx = dx * ctx->max_height / dy;
                dx = dx ? dx : 1;
                dy = ctx->max_height;
                resize = 1;
            }
        }
    }

    if (resize) {
        dst = ngx_http_image_new(r, dx, dy, palette);
        if (dst == NULL) {
            gdImageDestroy(src);
            return NULL;
        }

        if (colors == 0) {
            gdImageSaveAlpha(dst, 1);
            gdImageAlphaBlending(dst, 0);
        }

        gdImageCopyResampled(dst, src, 0, 0, 0, 0, dx, dy, sx, sy);

        if (colors) {
            gdImageTrueColorToPalette(dst, 1, 256);
        }

        gdImageDestroy(src);

    } else {
        dst = src;
    }

    if (ctx->angle) {
        src = dst;

        ax = (dx % 2 == 0) ? 1 : 0;
        ay = (dy % 2 == 0) ? 1 : 0;

        switch (ctx->angle) {

        case 90:
        case 270:
            dst = ngx_http_image_new(r, dy, dx, palette);
            if (dst == NULL) {
                gdImageDestroy(src);
                return NULL;
            }
            if (ctx->angle == 90) {
                ox = dy / 2 + ay;
                oy = dx / 2 - ax;

            } else {
                ox = dy / 2 - ay;
                oy = dx / 2 + ax;
            }

            gdImageCopyRotated(dst, src, ox, oy, 0, 0,
                               dx + ax, dy + ay, ctx->angle);
            gdImageDestroy(src);

            t = dx;
            dx = dy;
            dy = t;
            break;

        case 180:
            dst = ngx_http_image_new(r, dx, dy, palette);
            if (dst == NULL) {
                gdImageDestroy(src);
                return NULL;
            }
            gdImageCopyRotated(dst, src, dx / 2 - ax, dy / 2 - ay, 0, 0,
                               dx + ax, dy + ay, ctx->angle);
            gdImageDestroy(src);
            break;
        }
    }

    if (conf->filter == NGX_HTTP_IMAGE_CROP) {

        src = dst;

        if ((ngx_uint_t) dx > ctx->max_width) {
            ox = dx - ctx->max_width;

        } else {
            ox = 0;
        }

        if ((ngx_uint_t) dy > ctx->max_height) {
            oy = dy - ctx->max_height;

        } else {
            oy = 0;
        }

        if (ox || oy) {

            dst = ngx_http_image_new(r, dx - ox, dy - oy, colors);

            if (dst == NULL) {
                gdImageDestroy(src);
                return NULL;
            }

            ox /= 2;
            oy /= 2;

            ngx_log_debug4(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "image crop: %d x %d @ %d x %d",
                           dx, dy, ox, oy);

            if (colors == 0) {
                gdImageSaveAlpha(dst, 1);
                gdImageAlphaBlending(dst, 0);
            }

            gdImageCopy(dst, src, 0, 0, ox, oy, dx - ox, dy - oy);

            if (colors) {
                gdImageTrueColorToPalette(dst, 1, 256);
            }

            gdImageDestroy(src);
        }
    }

    if (transparent != -1 && colors) {
        gdImageColorTransparent(dst, gdImageColorExact(dst, red, green, blue));
    }

    sharpen = ngx_http_image_filter_get_value(r, conf->shcv, conf->sharpen);
    if (sharpen > 0) {
        gdImageSharpen(dst, sharpen);
    }

    gdImageInterlace(dst, (int) conf->interlace);

    out = ngx_http_image_out(r, ctx->type, dst, &size);

    ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                   "image: %d x %d %d", sx, sy, colors);

    gdImageDestroy(dst);
    ngx_pfree(r->pool, ctx->image);

    if (out == NULL) {
        return NULL;
    }

    cln = ngx_pool_cleanup_add(r->pool, 0);
    if (cln == NULL) {
        gdFree(out);
        return NULL;
    }

    b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
    if (b == NULL) {
        gdFree(out);
        return NULL;
    }

    cln->handler = ngx_http_image_cleanup;
    cln->data = out;

    b->pos = out;
    b->last = out + size;
    b->memory = 1;
    b->last_buf = 1;

    ngx_http_image_length(r, b);

    return b;
}
Beispiel #20
0
int
main (int argc, char *argv[])
{
#ifndef HAVE_LIBFREETYPE
  /* 2.0.12 */
  fprintf (stderr, "annotate is not useful without freetype.\n"
	   "Install freetype, then './configure; make clean; make install'\n"
	   "the gd library again.\n");
  return 1;
#else
  gdImagePtr im;
  char *iin, *iout;
  FILE *in, *out;
  char s[1024];
  int bounds[8];
  int lines = 1;
  int color = gdTrueColor (0, 0, 0);
  char font[1024];
  int size = 12;
  int align = left;
  int x = 0, y = 0;
  char *fontError;
  strcpy (font, "times");
  if (argc != 3)
    {
      fprintf (stderr, "Usage: annotate imagein.jpg imageout.jpg\n\n");
      fprintf (stderr, "Standard input should consist of\n");
      fprintf (stderr, "lines in the following formats:\n");
      fprintf (stderr, "color r g b (0-255 each) [a (0-127, 0 is opaque)]\n");
      fprintf (stderr, "font fontname\n");
      fprintf (stderr, "size pointsize\n");
      fprintf (stderr, "align (left|right|center)\n");
      fprintf (stderr, "move x y\n");
      fprintf (stderr, "text actual-output-text\n\n");
      fprintf (stderr,
	       "If the file 'paris.ttf' exists in /usr/share/fonts/truetype or in a\n");
      fprintf (stderr,
	       "location specified in the GDFONTPATH environment variable, 'font paris' is\n");
      fprintf (stderr,
	       "sufficient. You may also specify the full, rooted path of a font file.\n");
      exit (1);
    }
  iin = argv[1];
  iout = argv[2];
  in = fopen (iin, "rb");
  if (!in)
    {
      fprintf (stderr, "Couldn't open %s\n", iin);
      exit (2);
    }
#ifdef HAVE_LIBJPEG
  im = gdImageCreateFromJpeg (in);
#else
  fprintf (stderr, "No JPEG library support available.\n");
#endif
  fclose (in);
  if (!im)
    {
      fprintf (stderr, "%s did not load properly\n", iin);
      exit (3);
    }
  while (fgets (s, sizeof (s), stdin))
    {
      char *st;
      char *text;
      st = strtok (s, " \t\r\n");
      if (!st)
	{
	  /* Be nice about blank lines */
	  continue;
	}
      if (!strcmp (st, "font"))
	{
	  char *st = strtok (0, " \t\r\n");
	  if (!st)
	    {
	      goto badLine;
	    }
	  strcpy (font, st);
	}
      else if (!strcmp (st, "align"))
	{
	  char *st = strtok (0, " \t\r\n");
	  if (!st)
	    {
	      goto badLine;
	    }
	  if (!strcmp (st, "left"))
	    {
	      align = 0;
	    }
	  else if (!strcmp (st, "center"))
	    {
	      align = 1;
	    }
	  else if (!strcmp (st, "right"))
	    {
	      align = 2;
	    }
	}
      else if (!strcmp (st, "size"))
	{
	  char *st = strtok (0, " \t\r\n");
	  if (!st)
	    {
	      goto badLine;
	    }
	  size = atoi (st);
	}
      else if (!strcmp (st, "color"))
	{
	  char *st = strtok (0, "\r\n");
	  int r, g, b, a = 0;
	  if (!st)
	    {
	      goto badLine;
	    }
	  if (sscanf (st, "%d %d %d %d", &r, &g, &b, &a) < 3)
	    {
	      fprintf (stderr, "Bad color at line %d\n", lines);
	      exit (2);
	    }
	  color = gdTrueColorAlpha (r, g, b, a);
	}
      else if (!strcmp (st, "move"))
	{
	  char *st = strtok (0, "\r\n");
	  if (!st)
	    {
	      goto badLine;
	    }
	  if (sscanf (st, "%d %d", &x, &y) != 2)
	    {
	      fprintf (stderr, "Missing coordinates at line %d\n", lines);
	      exit (3);
	    }
	}
      else if (!strcmp (st, "text"))
	{
	  int rx = x;
	  text = strtok (0, "\r\n");
	  if (!text)
	    {
	      text = "";
	    }
	  gdImageStringFT (0, bounds, color, font, size, 0, x, y, text);
	  switch (align)
	    {
	    case left:
	      break;
	    case center:
	      rx -= (bounds[2] - bounds[0]) / 2;
	      break;
	    case right:
	      rx -= (bounds[2] - bounds[0]);
	      break;
	    }
	  fontError = gdImageStringFT (im, 0, color, font,
				       size, 0, rx, y, text);
	  if (fontError)
	    {
	      fprintf (stderr, "font error at line %d: %s\n", lines,
		       fontError);
	      exit (7);
	    }
	  y -= (bounds[7] - bounds[1]);
	}
      else
	{
	  goto badLine;
	}
      lines++;
      continue;
    badLine:
      fprintf (stderr, "Bad syntax, line %d\n", lines);
      exit (4);
    }
  out = fopen (iout, "wb");
  if (!out)
    {
      fprintf (stderr, "Cannot create %s\n", iout);
      exit (5);
    }
#ifdef HAVE_LIBJPEG
  gdImageJpeg (im, out, 95);
#else
  fprintf (stderr, "No JPEG library support available.\n");
#endif
  gdImageDestroy (im);
  fclose (out);
  return 0;
#endif /* HAVE_LIBFREETYPE */
}
Beispiel #21
0
main(int argc, char *argv[]){
  FILE *fp;
  gdImagePtr im, im2;
  int i,x,y,xsize,ysize,c;

  if(argc<7){
    fprintf(stderr, "[%s] compiled [%s/%s]\n", argv[0], __DATE__, __TIME__);
    fprintf(stderr, "Usage : %s x1 x2 y1 y2 in-gif out-gif [-blue]\n", argv[0]);
    exit(1);
  }
  if(argc>7){
    if(strcmp(argv[7], "-blue")==0) blueMode = 1;
  }

  x1 = atoi(argv[1]);
  x2 = atoi(argv[2]);
  y1 = atoi(argv[3]);
  y2 = atoi(argv[4]);
  infile  = argv[5];
  outfile = argv[6];

  fp = fopen(infile, "rb");
  if(!fp){
    fprintf(stderr, "Can't open [%s]\n", infile);
    exit(1);
  }
  im = gdImageCreateFromGif(fp);
  fclose(fp);

  xsize = gdImageSX(im);
  ysize = gdImageSY(im);

  im2 = gdImageCreate(xsize, ysize);

  if(blueMode){		// use bluish gradation for low index value
    int j;
    for(i=0; i<256; i++){
      j = (i-blueValue)*255/(255-blueValue); 	//////////////// blueValue --> 0, 255 --> 255
      j = (j<0)?0:j;
      j=  (j>255)?255:j;
      gdImageColorAllocate(im2, j, j, i);
    }
  } else {
    for(i=0; i<256; i++)
      gdImageColorAllocate(im2, i, i, i);
  }


  for(y=0; y<ysize; y++){
    for(x=0; x<xsize; x++){
      c = gdImageGetPixel(im, x, y);
      { int r,g,b;			// fixed 2001.07.09
	r = gdImageRed(im, c);
	g = gdImageGreen(im, c);
	b = gdImageBlue(im, c);
	c = ( g + g + r + b )/4;
      }
      indexMap(&c);
      gdImageSetPixel(im2, x, y, c);
    }
  }
  gdImageDestroy(im);

  fp = fopen(outfile, "wb");
  if(!fp){
    fprintf(stderr, "Can't open [%s]\n", outfile);
    exit(1);
  }
  gdImageGif(im2, fp);
  fclose(fp);
}
Beispiel #22
0
int main(int argc, char *argv[]) {
    int width        = DEFAULT_WIDTH;
    int generations  = DEFAULT_HEIGHT;
    unsigned long ruleset = DEFAULT_RULES;
    FILE *output_fh  = stdout;
    char start_row[CA_MAX_WIDTH];
    char start_str[CA_MAX_WIDTH];
    CA *ca_ptr; 
    gdImagePtr image;
    int idx;

    int opt;
    int init_cntr = 0;
    int blk_r = 0, 
        blk_g = 0, 
        blk_b = 0;
    int wht_r = 255, 
        wht_g = 255, 
        wht_b = 255;
    char *filename = NULL;
    long hexval;
    int  dimension;
    int  percentage=0;

    while( (opt = getopt(argc, argv, "s:p:x:y:b:w:o:r:123")) != -1 ) {
         switch(opt) {
             case 's':
                 strncpy(start_str, optarg,CA_MAX_WIDTH);
                 break;
             case 'p':
                 sscanf(optarg, "%d", &percentage);
                 if ( (percentage > 100) || (percentage < 0) ) {
                     percentage = 50;
                 }
                 break;
             case 'x':
                 sscanf(optarg, "%d", &dimension);
                 if (dimension <= 0) {
                     fprintf(stderr, "Width too small! Using default.\n");
                     width = DEFAULT_WIDTH;
                 } else if( dimension > CA_MAX_WIDTH) {
                     fprintf(stderr, "Width too big! Using default.\n");
                     width = DEFAULT_WIDTH;
                 } else {
                     width = dimension;
                 }
                 break;
             case 'y':
                 sscanf(optarg, "%d", &dimension);
                 if (dimension <= 0) {
                     fprintf(stderr, "Height too small! Using default.\n");
                     generations = DEFAULT_HEIGHT;
                     break;
                 } else {
                     generations = dimension;
                 }
                 break;
             case 'b': 
                 sscanf(optarg,"%lx", &hexval);
                 blk_r  = hexval & 0xff0000; blk_r = blk_r >> 16;
                 blk_g  = hexval & 0x00ff00; blk_g = blk_g >> 8;
                 blk_b  = hexval & 0x0000ff;
                 break; 
             case 'w': 
                 sscanf(optarg,"%lx", &hexval);
                 wht_r  = hexval & 0xff0000; wht_r = wht_r >> 16;
                 wht_g  = hexval & 0x00ff00; wht_g = wht_g >> 8;
                 wht_b  = hexval & 0x0000ff; 
                 break;
             case 'o': 
                 filename = optarg;
                 break;
             case 'r': 
                 sscanf(optarg, "%lu", &ruleset);
                 if (ruleset < 0 || ruleset > (unsigned long)(~0)) {
                     fprintf(stderr, "Bad rule [%lu] specified!\n", ruleset);
                     exit(1);
                 }
                 break; 
             case '1':
                 init_cntr = 1;
                 break; 
             case '2':
                 init_cntr = 2;
                 break; 
             case '3':
                 init_cntr = 3;
                 break; 
             case ':':
                 fprintf(stderr,"Option '%c' requires a value.\n", optopt);
                 exit(1);
             case '?': 
                 fprintf(stderr,"Unknown option '%c'.\n", optopt);
                 exit(1);
         }
    } /* End of command line processing. */


    srand(0);
    for (idx = 0; idx < width; idx++) {
        start_row[idx] = rand() % 2; 
    }

    if( ! init_cntr) {
        fill_row_random(start_row, percentage, 0, width, 0);
    } else if ( init_cntr == 1) {
        fill_row_center(start_row, start_str, 0, width);
    } else if (init_cntr == 2) {
        fill_row_center(start_row, start_str, 1, width);
    } else if (init_cntr == 3) {
        fill_row_repeat(start_row, start_str, width);
    } else {
        fill_row(start_row, 0, width);
    }

    ca_ptr = new_ca(width,ruleset,start_row);
    image = ca_make_gif(ca_ptr, generations, 
                        blk_r,blk_g,blk_b, wht_r,wht_g,wht_b);

    if (filename) {
        output_fh = fopen(filename, "w");
        if (! output_fh) {
            fprintf(stderr,"Unable to open %s for writing: %s\n", 
                    filename, strerror(errno));
            exit(errno);
        }
    }
    gdImagePng(image, output_fh);
    gdImageDestroy(image);
    free_ca(ca_ptr);
    exit(0);
}
Beispiel #23
0
int renderLineGD(imageObj *img, shapeObj *p, strokeStyleObj *stroke) 
{
  gdImagePtr ip;
  int c;
  gdImagePtr brush=NULL;
  
  if(!img || !p || !stroke) return MS_FAILURE;
  if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;

  SETPEN(ip, stroke->color);
  c = stroke->color->pen;

  if(stroke->patternlength > 0) {
    int *style;
    int i, j, k=0;
    int sc;

    for(i=0; i<stroke->patternlength; i++)
      k += MS_NINT(stroke->pattern[i]);
    style = (int *) malloc (k * sizeof(int));
    MS_CHECK_ALLOC(style, k * sizeof(int), MS_FAILURE);

    sc = c; /* start with the color */    

    k=0;
    for(i=0; i<stroke->patternlength; i++) {
      for(j=0; j<MS_NINT(stroke->pattern[i]); j++, k++) {
        style[k] = sc;
      }
      sc = ((sc==c)?gdTransparent:c);
    }

    gdImageSetStyle(ip, style, k);
    free(style);

    c = gdStyled;
  }

  if(stroke->width > 1) {
     int brush_fc;
     brush = gdImageCreate(ceil(stroke->width), ceil(stroke->width));
     gdImageColorAllocate(brush, gdImageRed(ip,0), gdImageGreen(ip, 0), gdImageBlue(ip, 0));
     gdImageColorTransparent(brush,0);
     brush_fc = gdImageColorAllocate(brush, gdImageRed(ip,stroke->color->pen),
           gdImageGreen(ip,stroke->color->pen), gdImageBlue(ip,stroke->color->pen));
     gdImageFilledEllipse(brush,MS_NINT(brush->sx/2),MS_NINT(brush->sy/2),
           MS_NINT(stroke->width),MS_NINT(stroke->width), brush_fc);
     gdImageSetBrush(ip, brush);
     if(stroke->patternlength > 0) {
       c = gdStyledBrushed;
     } else {
       c = gdBrushed;
     }
  }
    
  /* finally draw something */
  imagePolyline(ip, p, c);

  /* clean up */
  if(stroke->width>1) {
     gdImageDestroy(brush);
  }
  return MS_SUCCESS;
}
Beispiel #24
0
int
main (int argc, char ** argv)
{
  if (argc != 3) {
    usage ();
  }
  #ifdef DEBUG_WIN_X
  if (fork() != 0) {
    printf ("Forked to background, exiting.\n");
    exit (0);
  }
  #endif
  log_open (LOGPATH);
  int fill_color = gdTrueColorAlpha (100, 100, 100, gdAlphaTransparent / 2);
  int line_color = gdTrueColorAlpha (175, 175, 175, gdAlphaOpaque);
  int text_color = gdTrueColorAlpha (255, 255, 255, gdAlphaOpaque);
  FILE * img_out;
  int img_time;
  char img_filename[64];
  gdImagePtr camera_1;
  gdImagePtr camera_2;
  gdImagePtr output;
  int numloops = 0;
  int fpstimer;
  double a1, a2;
  tolerance_file_t * tol;
  int alliance;
  tol = get_tolerance (TOLPATH);
  log_write ("Got tolerance values from %s.", TOLPATH);
  if (argv[1][0] == 98) {
    log_write ("Seeking blue targets.");
    alliance = ALLIANCE_BLUE;
  } else {
    log_write ("Seeking red targets.");
    alliance = ALLIANCE_RED;
  }
  char * jpeg_buff;
  char * jpeg_buff_2;
  int jpeg_buff_size;
  int jpeg_buff_size_2;
  int x, y;
  blob * cam1_green;
  blob * cam2_green;
  blob * cam1_red;
  blob * cam2_red;
  blob * target_blob;
  int loop_ctr;
  loop_ctr = 0;
  float lastfps;
  log_write ("Beginning main loop.");
  while (1) {
    #ifndef DISABLE_IMG
    output = gdImageCreateTrueColor (1280, 480);
    #endif

    #ifndef DEBUG_WIN
    
    log_write ("Getting first jpeg.");
    jpeg_buff = get_jpeg (CAM1, &jpeg_buff_size);
    if (jpeg_buff == NULL) {
      log_write ("First jpeg buffer is null!");
      exit (1);
    }
    if (jpeg_buff_size <= 0) {
      log_write ("First jpeg buffer size is invalid!");
      exit (1);
    }
    log_write ("First jpeg received. Size: %d", jpeg_buff_size);
    camera_1 = gdImageCreateFromJpegPtr (jpeg_buff_size, jpeg_buff);
    if (camera_1 == NULL) {
      log_write ("gdImageCreateFromJpegPtr () failed for jpeg 1!");
      exit (1);
    }
    log_write ("Getting second jpeg.");
    jpeg_buff_2 = get_jpeg (CAM2, &jpeg_buff_size_2);
    if (jpeg_buff_2 == NULL) {
      log_write ("Second jpeg buffer is null!");
      exit (1);
    }
    if (jpeg_buff_size_2 <= 0) {
      log_write ("Second jpeg buffer size is invalid!");
      exit (1);
    }
    log_write ("Second jpeg received. Size: %d", jpeg_buff_size_2);
    camera_2 = gdImageCreateFromJpegPtr (jpeg_buff_size_2, jpeg_buff_2);
    if (camera_2 == NULL) {
      log_write ("gdImageCreateFromJpegPtr () failed for jpeg 2!");
      exit (1);
    }
    
    #endif // !DEBUG_WIN
    
    #ifdef DEBUG_WIN
    
    img_out = fopen ("cam1.jpg", "rb");
    camera_1 = gdImageCreateFromJpeg (img_out);
    fclose (img_out);
    img_out = fopen ("cam2.jpg", "rb");
    camera_2 = gdImageCreateFromJpeg (img_out);
    fclose (img_out);
    if (camera_1 == NULL) {
      log_write ("Camera 1 image did not load properly.");
      exit (1);
    }
    if (camera_2 == NULL) {
      log_write ("Camera 2 image did not load properly.");
      exit (1);
    }
    
    #endif // DEBUG_WIN
    
    log_write ("Detecting blobs on camera 1.");
    cam1_red = find (camera_1, &(tol->cam1_red));
    cam1_green = find (camera_1, &(tol->cam1_green));
    log_write ("Detecting blobs on camera 2.");
    cam2_red = find (camera_2, &(tol->cam2_red));
    cam2_green = find (camera_2, &(tol->cam2_green));
    if ((target_blob = target (cam1_red, cam1_green, alliance)) != NULL) {
      if ((target_blob->center_x + 50) > 400) {
        log_write ("Sending left motor command.");
        gpio (59, GPIO_ON);
        gpio (58, GPIO_OFF);
      }
      else if ((target_blob->center_x + 50) < 240) {
        log_write ("Sending right motor command.");
        gpio (58, GPIO_ON);
        gpio (59, GPIO_OFF);
      }
      else {
        log_write ("Sending left & right motor commands.");
        gpio (58, GPIO_ON);
        gpio (59, GPIO_ON);
      }
      #ifndef DISABLE_IMG
      //print_blobs (camera_1, target_blob, 100, 100, 100);
      #endif
      free_blobs (target_blob);
    } else {
      log_write ("EE: No targets found.");
    }
    if (cam1_red != NULL && cam1_green != NULL) {
      log_write ("Blob detection completed.  Building image.");
      #ifndef DISABLE_IMG
      print_blobs (camera_1, cam1_red, 200, 0, 0);
      //print_blobs (camera_2, cam2_red, 200, 0, 0);
      print_blobs (camera_1, cam1_green, 0, 180, 20);
      //print_blobs (camera_2, cam2_green, 0, 180, 20);
      #endif
      free_blobs (cam1_red);
      free_blobs (cam2_red);
      free_blobs (cam1_green);
      free_blobs (cam2_green);
      #ifndef DISABLE_IMG
      gdImageCopy (output, camera_1, 0, 0, 0, 0, 640, 480);
      gdImageCopy (output, camera_2, 640, 0, 0, 0, 640, 480);
      #endif
      /*gdImageFilledRectangle (output, 540, 340, 760, 450, fill_color);
      gdImageRectangle (output, 540, 340, 760, 450, line_color);
      time_t rawtime;
      time (&rawtime);
      char * time_str = ctime (&rawtime);
      time_str[strlen(time_str)-1] = '\0';
      render_text (output, text_color, 550, 360, "%s", time_str);
      if (cam1_red != NULL && cam2_red != NULL) {
        render_text (output, text_color, 550, 375, "Left Centroid: 300, 424", cam1_red->center_x, cam1_red->center_y);
        render_text (output, text_color, 550, 390, "Right Centroid: 422, 233", cam2_red->center_x, cam2_red->center_y);
        a1 = image_angle (cam1_red->center_x);
        a2 = image_angle (cam2_red->center_x);
        render_text (output, text_color, 550, 405, "Left Angle: %f", a1 * (180/PI));
        render_text (output, text_color, 550, 420, "Right Angle: %f", a2 * (180/PI));
        render_text (output, text_color, 550, 435, "Depth: %f", find_depth (a1, a2));
      }*/
      #ifndef DISABLE_IMG
      img_time = time (NULL);
      snprintf (img_filename, sizeof (img_filename), "%s%s%d.jpg", OUTPATH, argv[2], img_time);
      log_write ("Image built. Writing to file: %s", img_filename);
      img_out = fopen (img_filename, "wb");
      gdImageJpeg (output, img_out, 100);
      fclose (img_out);
      #endif
    } else {
      log_write ("EE: Some cams didn't detect red+green blobs.");
    }
    #ifndef DISABLE_IMG
    gdImageDestroy (output);
    #endif
    gdImageDestroy (camera_1);
    gdImageDestroy (camera_2);
    log_write ("Loop %d finished.", loop_ctr);
    loop_ctr++;
  }
  return 0;
}
ngx_int_t ngx_http_small_light_gd_process(ngx_http_request_t *r, ngx_http_small_light_ctx_t *ctx)
{
    ngx_http_small_light_gd_ctx_t     *ictx;
    ngx_http_small_light_image_size_t  sz;
    gdImagePtr                         src, dst, canvas;
    ngx_int_t                          colors, transparent, palette, red, green, blue;
    ngx_int_t                          ax, ay, ox, oy, type;
    int                                iw, ih, radius, ccolor, bcolor;
    char                              *sharpen, *of;
    u_char                            *out;
    int                                size;
    double                             q;

    ictx = (ngx_http_small_light_gd_ctx_t *)ctx->ictx;
    src  = ngx_http_small_light_gd_src(ictx);
    if (src == NULL) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                      "failed to get image source %s:%d",
                      __FUNCTION__,
                      __LINE__);
        return NGX_ERROR;
    }

    /* adjust image size */
    iw = gdImageSX(src);
    ih = gdImageSY(src);
    ngx_http_small_light_calc_image_size(r, ctx, &sz, iw, ih);

    colors      = gdImageColorsTotal(src);
    palette     = 0;
    transparent = -1;
    red         = 0;
    green       = 0;
    blue        = 0;

    if (colors) {
        transparent = gdImageGetTransparent(src);

        if (transparent != -1) {
            palette = colors;
            red     = gdImageRed(src,   transparent);
            green   = gdImageGreen(src, transparent);
            blue    = gdImageBlue(src,  transparent);
        }
    }

    gdImageColorTransparent(src, -1);

    /* rotate. */
    if (sz.angle) {
        dst = src;
        ax  = (iw % 2 == 0) ? 1 : 0;
        ay  = (ih % 2 == 0) ? 1 : 0;
        switch (sz.angle) {
        case 90:
        case 270:
            dst = ngx_http_small_light_gd_new(ih, iw, palette);
            if (dst == NULL) {
                gdImageDestroy(src);
                return NGX_ERROR;
            }

            if (sz.angle == 90) {
                ox = ih / 2 - ay;
                oy = iw / 2 + ax;
            } else {
                ox = ih / 2 + ay;
                oy = iw / 2 - ax;
            }

            gdImageCopyRotated(dst, src, ox, oy, 0, 0,
                               iw, ih, -sz.angle);
            gdImageDestroy(src);

            break;
        case 180:
            dst = ngx_http_small_light_gd_new(iw, ih, palette);
            if (dst == NULL) {
                gdImageDestroy(src);
                return NGX_ERROR;
            }
            gdImageCopyRotated(dst, src, iw / 2 - ax, ih / 2 - ay, 0, 0,
                               iw + ax, ih + ay, sz.angle);
            gdImageDestroy(src);
            break;
        default:
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "image not rotated. 'angle'(%ui) must be 90 or 180 or 270. %s:%d",
                          sz.angle,
                          __FUNCTION__,
                          __LINE__);
            break;
        }
        src = dst;
    }

    /* calc size. */
    iw = gdImageSX(src);
    ih = gdImageSY(src);
    ngx_http_small_light_calc_image_size(r, ctx, &sz, iw, ih);

    /* pass through. */
    if (sz.pt_flg != 0) {
        gdImageDestroy(src);
        ctx->of = ctx->inf;
        return NGX_OK;
    }

    /* crop, scale. */
    if (sz.scale_flg != 0) {
        dst = ngx_http_small_light_gd_new(sz.dw, sz.dh, palette);
        if (dst == NULL) {
            gdImageDestroy(src);
            return NGX_ERROR;
        }

        if (colors == 0) {
            gdImageSaveAlpha(dst, 1);
            gdImageAlphaBlending(dst, 0);
        }

        gdImageCopyResampled(dst, src, 0, 0, sz.sx, sz.sy, sz.dw, sz.dh, sz.sw, sz.sh);

        if (colors) {
            gdImageTrueColorToPalette(dst, 1, 256);
        }

        gdImageDestroy(src);
    } else {
        dst = src;
    }

    if (transparent != -1 && colors) {
        gdImageColorTransparent(dst, gdImageColorExact(dst, red, green, blue));
    }

    /* effects. */
    sharpen = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "sharpen");
    if (sharpen != NULL) {
        radius = ngx_http_small_light_parse_int(sharpen);
        if (radius > 0) {
            gdImageSharpen(dst, radius);
        }
    }

    /* interlace */
    gdImageInterlace(dst, 1);

    /* create canvas then draw image to the canvas. */
    if (sz.cw > 0.0 && sz.ch > 0.0) {
        canvas = gdImageCreateTrueColor(sz.cw, sz.ch);
        if (canvas == NULL) {
            gdImageDestroy(dst);
            return NGX_ERROR;
        }
        ccolor = gdImageColorAllocateAlpha(canvas, sz.cc.r, sz.cc.g, sz.cc.b, sz.cc.a);
        gdImageFilledRectangle(canvas, 0, 0, sz.cw, sz.ch, ccolor);
        gdImageCopy(canvas, dst, sz.dx, sz.dy, 0, 0, sz.dw, sz.dh);
        gdImageDestroy(dst);
        dst = canvas;
    }

    /* border. */
    if (sz.bw > 0.0 || sz.bh > 0.0) {
        bcolor = gdImageColorAllocateAlpha(dst, sz.bc.r, sz.bc.g, sz.bc.b, sz.bc.a);
        if (sz.cw > 0.0 && sz.ch > 0.0) {
            gdImageFilledRectangle(dst, 0, 0, sz.cw, sz.bh, bcolor);
            gdImageFilledRectangle(dst, 0, 0, sz.bw, sz.ch, bcolor);
            gdImageFilledRectangle(dst, 0, sz.ch - sz.bh, sz.cw - 1, sz.ch - 1, bcolor);
            gdImageFilledRectangle(dst, sz.cw - sz.bw, 0, sz.cw - 1, sz.ch - 1, bcolor);
        } else {
            gdImageFilledRectangle(dst, 0, 0, sz.dw, sz.bh, bcolor);
            gdImageFilledRectangle(dst, 0, 0, sz.bw, sz.dh, bcolor);
            gdImageFilledRectangle(dst, 0, sz.dh - sz.bh, sz.dw - 1, sz.dh - 1, bcolor);
            gdImageFilledRectangle(dst, sz.dw - sz.bw, 0, sz.dw - 1, sz.dh - 1, bcolor);
        }
    }

    of = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "of");
    if (ngx_strlen(of) > 0) {
        type = ngx_http_small_light_type(of);
        if (type == NGX_HTTP_SMALL_LIGHT_IMAGE_NONE) {
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "of is invalid(%s) %s:%d",
                          of,
                          __FUNCTION__,
                          __LINE__);
        } else if (type == NGX_HTTP_SMALL_LIGHT_IMAGE_WEBP) {
#ifdef NGX_HTTP_SMALL_LIGHT_GD_WEBP_ENABLED
            ictx->type = type;
#else
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "WebP is not supported %s:%d",
                          __FUNCTION__,
                          __LINE__);
#endif
        } else {
            ictx->type = type;
        }
    }

    ctx->of = ngx_http_small_light_image_types[ictx->type - 1];

    q = ngx_http_small_light_parse_double(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "q"));
    if (q == 0) {
        q = 100;
    }
    out = ngx_http_small_light_gd_out(dst, ictx->type, (int *)&size, q);
    gdImageDestroy(dst);

    if (out == NULL) {
        return NGX_ERROR;
    }

    /* get small_lighted image as binary. */
    ctx->content        = out;
    ctx->content_length = size;

    ngx_pfree(r->pool, ctx->content_orig);

    ictx->complete = 1;

    return NGX_OK;
}
static ngx_int_t
ngx_http_qrcode_handler(ngx_http_request_t* r)
{
	ngx_http_qrcode_loc_conf_t *qlcf;
	ngx_int_t 	code_size;
	ngx_int_t 	img_margin, img_width;
	ngx_int_t 	fg_color, bg_color;
	ngx_int_t 	x, y, posx, posy;
	int 		img_stream_len;
	u_char		*encoded_txt;
	ngx_int_t	rc;

	qlcf = ngx_http_get_module_loc_conf(r, ngx_http_qrcode_module);

	/* compile args */
	rc = ngx_http_qrcode_compile_args(r, qlcf);
	if (rc != NGX_OK)  {
		ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to compile args.");
		return NGX_HTTP_INTERNAL_SERVER_ERROR;
	}

	encoded_txt = ngx_pcalloc(r->pool, qlcf->txt.len + 1);
	ngx_sprintf(encoded_txt, "%V", &qlcf->txt);

	QRcode *code;
	code = QRcode_encodeString((char*)encoded_txt,
			qlcf->version, qlcf->level, qlcf->hint, qlcf->casesensitive);

	if(code == NULL) {
		ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
				"Failed to encode content.exception raised by libqrencode: %s", strerror(errno));
		return NGX_HTTP_INTERNAL_SERVER_ERROR;
	}

	code_size	= ((qlcf->size > 2048) ? 1024 : qlcf->size) / code->width;
	code_size   = (code_size == 0) ? 1 : code_size;
	img_margin	= qlcf->margin;
	img_width	= code->width * code_size + 2 * img_margin;

	gdImagePtr img;
	img	= gdImageCreate(img_width, img_width);

	fg_color = gdImageColorAllocate(img,
			qlcf->fg_color[0], qlcf->fg_color[1], qlcf->fg_color[2]);

	bg_color = gdImageColorAllocate(img,
		   	qlcf->bg_color[0], qlcf->bg_color[1], qlcf->bg_color[2]);

	gdImageFill(img, 0, 0, bg_color);

	u_char *p = code->data;
	for (y = 0; y < code->width; y++)
	{
		for (x = 0; x < code->width; x++)
		{
			if (*p & 1) {
				posx = x * code_size + img_margin;
				posy = y * code_size + img_margin;

				gdImageFilledRectangle(img, posx, posy,
						posx + code_size, posy + code_size, fg_color);
			}
			p++;
		}
	}

	u_char *img_stream;
    img_stream = gdImagePngPtr(img, &img_stream_len);

	gdImageDestroy(img);
	QRcode_free(code);

	r->headers_out.status = NGX_HTTP_OK;
	r->headers_out.content_length_n = img_stream_len;

	ngx_str_set(&r->headers_out.content_type, "image/png");
	ngx_http_send_header(r);

	ngx_buf_t* buffer;
	buffer = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));

	if (buffer == NULL) {
		ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
				"Failed to allocate response buffer");
		return NGX_HTTP_INTERNAL_SERVER_ERROR;
	}

	//set up the buffer chain
	ngx_chain_t out;
	buffer->pos = img_stream;
	buffer->last = img_stream + img_stream_len;
	buffer->memory = 1;
	buffer->last_buf = 1;
	out.buf = buffer;
	out.next = NULL;

	return ngx_http_output_filter(r, &out);
}
Beispiel #27
0
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;

	if (w<1 || h <1) {
		return 0;
	}

	/* 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(php_gd_error("File size is %dx%d", 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(php_gd_error("Image palette completed: %d colours", 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;
		}
		if (chunkMax <= 0) {
			goto fail2;
		}

		chunkBuf = gdCalloc(chunkMax, 1);
		compBuf = gdCalloc(compMax, 1);
	}

	/* 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(php_gd_error("Data starts at %d", 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(php_gd_error("Processing Chunk (%d, %d), from %d to %d", cx, cy, ylo, yhi));

			if (!gd2_compressed(fmt)) {
				GD2_DBG(php_gd_error("Using raw format data"));
				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)) {
					php_gd_error_ex(E_WARNING, "Error from seek: %d", errno);
					goto fail2;
				}
				GD2_DBG(php_gd_error("Reading (%d, %d) from position %d", cx, cy, dpos - dstart));
			} else {
				chunkNum = cx + cy * ncx;

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

			GD2_DBG(php_gd_error("   into (%d, %d) - (%d, %d)", 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;
							}
						} else {
							ch = gdGetC(in);
							if ((int)ch == EOF) {
								ch = 0;
							}
						}
					} 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)) {
						if (im->trueColor) {
							im->tpixels[y - srcy][x - srcx] = ch;
						} else {
							im->pixels[y - srcy][x - srcx] = ch;
						}
					}
				}
			}
		}
	}

	if (chunkBuf) {
		gdFree(chunkBuf);
	}
	if (compBuf) {
		gdFree(compBuf);
	}
	if (chunkIdx) {
		gdFree(chunkIdx);
	}

	return im;

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

	return 0;
}
Beispiel #28
0
static int screenshot(char *model, char *wps, char *png)
{
    char lib[255];
    void *handle;
    FILE *out, *in;
    int res;
    
    in = fopen(wps, "rb");
    if(in == NULL)
    {
        fprintf(stderr, "[ERR]  Cannot open WPS: %s\n", wps);
        return -1;
    }
    fclose(in);
    
    out = fopen(png, "wb");
    if(out == NULL)
    {
        fprintf(stderr, "[ERR]  Cannot open PNG: %s\n", png);
        return -2;
    }
    
    snprintf(lib, 255, "%s/libwps_%s.so", (char*)get_current_dir_name(), (char*)model);
    handle = dlopen(lib, RTLD_LAZY);
    if (!handle)
    {
        fprintf(stderr, "[ERR]  Cannot open library: %s\n", dlerror());
        fclose(out);
        return -3;
    }
    
    wps_init = dlsym(handle, "wps_init");
    wps_display = dlsym(handle, "wps_display");
    wps_refresh = dlsym(handle, "wps_refresh");
    
    if (!wps_init || !wps_display || !wps_refresh)
    {
        fprintf(stderr, "[ERR]  Failed to resolve funcs!");
        dlclose(handle);
        fclose(out);
        return -4;
    }

    memset(&api, 0, sizeof(struct proxy_api));
    
    if(verbose)
        api.verbose = 3;
    else
        api.verbose = 0;

    api.putsxy =                     &_putsxy;
    api.transparent_bitmap_part =    &_transparent_bitmap_part;
    api.bitmap_part =                &_bitmap_part;
    api.drawpixel =                  &_drawpixel;
    api.fillrect =                   &_fillrect;
    api.hline =                      &_hline;
    api.vline =                      &_vline;
    api.clear_viewport =             &_clear_viewport;
    api.load_wps_backdrop =          &_load_wps_backdrop;
    api.read_bmp_file =              &_read_bmp_file;
    api.debugf =                     &_debug;
    
    res = wps_init(wps, &api, true);
    if(res != 1)
    {
        fprintf(stderr, "[ERR]  WPS wasn't correctly inited\n");
        dlclose(handle);
        fclose(out);
        return -5;
    }
    
    framebuffer = gdImageCreateTrueColor(api.getwidth(), api.getheight());

    _drawBackdrop();
    
    fprintf(stdout, "[INFO] Model: %s\n", api.get_model_name());
    
    wpsdata.fontheight = getFont()->h;
    wpsdata.fontwidth = getFont()->w;
    api.set_wpsstate(wpsdata);
    api.set_trackstate(mp3data);
    api.set_next_trackstate(mp3data);
    
    _drawBackdrop();
    wps_refresh();
    gdImagePng(framebuffer, out);
    
    fprintf(stdout, "[INFO] Image written\n");

    dlclose(handle);
    fclose(out);
    gdImageDestroy(framebuffer);
    if(backdrop != NULL)
        gdImageDestroy(backdrop);
    
    wps_init = NULL;
    wps_display = NULL;
    wps_refresh = NULL;
    
    return 0;
}
Beispiel #29
0
 ~ImageImpl()
 {
     gdImageDestroy(im_);
 }
Beispiel #30
0
/*
 * Save complex matrix to JPEG via gd
 * if magnitude is set, brightness of output pixels is abs(complex), otherwise it's atan(re/im)  
 * 
 * return -1 on error, 0 otherwise
 */
uint32_t y_complex_save( fftwf_complex *data, uint32_t magnitude, uint32_t w, uint32_t h, char *name )
{
	FILE *f;
	gdImage *image;
	uint32_t i, j, g, color;
	fftwf_complex *dat;
	float d, max, re, im;
	
	if(!name)
		return(-1);
	
	f = fopen(name, "wb");
	
	if(!f)
	{
		ERROR("Error opening file for output: %s", name);
		ERROR("fopen: %s", strerror(errno));
		return(-1);
	}
	
	image = gdImageCreateTrueColor(w,h);


	if(!image)
	{
		ERROR("Cannot create image");
		fclose(f);
		return(-1);
	}

	max=0;
	dat=data;
	for(j=0;j<h;j++)
		for(i=0;i<w;i++)
		{
			if(magnitude)
			{
				re = creal(*dat);
				im = cimag(*dat);
				d = sqrtf(powf(re,2)+powf(im,2));
			} else {
				re = creal(*dat);
				im = cimag(*dat);
				d = atan2(im, re);
			}
			dat++;
			if(d>max) max=d;
		}		
	


	dat = data;
	for(j=0; j<h; j++){
		for(i=0; i<w; i++)
		{
			if(magnitude)
			{
				re = creal(*dat);
				im = cimag(*dat);
				d = sqrtf(re*re+im*im);
			} else {
				re = creal(*dat);
				im = cimag(*dat);
				d = atan2(im, re);
			}
			dat++;
			g = round(255.0 * d/max);
			color = g + (g<<8) + (g<<16);
			color &= 0xffffff; 
			gdImageSetPixel(image,i,j,color);
		}
	}
	
	gdImageJpeg(image, f, 255);

	gdImageDestroy(image);

	return(0);
}