Exemple #1
1
int main()
{
	gdImagePtr src, dst;
	int w, b;
	void *p;
	int size = 0;
	int status = 0;
	CuTestImageResult result = {0, 0};

	src = gdImageCreate(100, 100);
	if (src == NULL) {
		printf("could not create src\n");
		return 1;
	}
	w = gdImageColorAllocate(src, 0xFF, 0xFF, 0xFF);
	b = gdImageColorAllocate(src, 0, 0, 0);
	gdImageRectangle(src, 20, 20, 79, 79, b);
	gdImageEllipse(src, 70, 25, 30, 20, b);

#define OUTPUT_WBMP(name) do {							\
		FILE *fp;										\
														\
		fp = fopen("wbmp_im2im_" #name ".wbmp", "wb");	\
		if (fp) {										\
			gdImageWBMP(name, 1, fp);					\
			fclose(fp);									\
		}												\
	} while (0)

	OUTPUT_WBMP(src);
	p = gdImageWBMPPtr(src, &size, 1);
	if (p == NULL) {
		status = 1;
		printf("p is null\n");
		goto door0;
	}
	if (size <= 0) {
		status = 1;
		printf("size is non-positive\n");
		goto door1;
	}

	dst = gdImageCreateFromWBMPPtr(size, p);
	if (dst == NULL) {
		status = 1;
		printf("could not create dst\n");
		goto door1;
	}
	OUTPUT_WBMP(dst);
	gdTestImageDiff(src, dst, NULL, &result);
	if (result.pixels_changed > 0) {
		status = 1;
		printf("pixels changed: %d\n", result.pixels_changed);
	}
	gdImageDestroy(dst);
 door1:
	gdFree(p);
 door0:
	gdImageDestroy(src);
	return status;
}
Exemple #2
0
int main(int argc, char *argv[])
{
  Table formt;
  Vector stats;
  gdImagePtr im;
  int black,white,blue;
  char *user, *formdata;
  int size,pos,x;
  float searchscore,searchincrement;
  double thisscore,score,lineheight;
  char label[5];
  int labellen;
  float variance;
  int height,width,labelheight,horizpad;
  int scoremark;
  char *votelabel;
  int lightblue;

  /**********************************
    HTTP header
    ********************************/
  /* use image/png if possible */
  printf("content-type: image/gif\n\n");
  
  /**********************************
    get info about request
    ********************************/
  formt=cgiparse();
  
  formdata=Table_gets(formt,"WIDTH");
  if (formdata!=NULL)
    width=atoi(formdata);
  else
    width=DEFAULTWIDTH;
  
  formdata=Table_gets(formt,"HEIGHT");
  if (formdata!=NULL)
    height=atoi(formdata);
  else
    height=DEFAULTHEIGHT;
 
  formdata=Table_gets(formt,"LABELHEIGHT");
  if (formdata!=NULL)
    labelheight=atoi(formdata);
  else
    labelheight=DEFAULTLABELHEIGHT;

  formdata=Table_gets(formt,"HORIZPADDING");
  if (formdata!=NULL)
    horizpad=atoi(formdata);
  else
    horizpad=DEFAULTHORIZPADDING;
 
  formdata=Table_gets(formt,"VARIANCE");
  if (formdata!=NULL)
    variance=atof(formdata);
  else
    variance=DEFAULTVARIANCE;
 
  stats=Vector_create(0);
  user=Table_gets(formt,"USER");

  if (user!=NULL)
    {
      readdatafile(stats,user);
    }

  size=Vector_getSize(stats);
  
  /**********************************
    create the image object and set it up
    ********************************/
  
  im=gdImageCreate(width+2*horizpad,height+labelheight);

  black=gdImageColorAllocate(im,0,0,0);
  white=gdImageColorAllocate(im,255,255,255);
  blue=gdImageColorAllocate(im,0,0,200);
  lightblue=gdImageColorAllocate(im,80,80,255);

  /**********************************
    perform the search. awfully inefficient.
    ********************************/
  searchincrement=(HIGHESTSCORE-LOWESTSCORE)/width;
  
  searchscore=LOWESTSCORE;
  x=0;

  while (searchscore<=HIGHESTSCORE)
    {
      score=0;

      for (pos=0;pos<size;pos++)
	{
	  thisscore= *((double*) Vector_elementAt(stats,pos));

	  score+=exp(-fabs(pow(thisscore-searchscore,2)/variance));
	}

      if (size>0)
	lineheight=score*height/size;
      else
	lineheight=0;

      gdImageLine(im,x+horizpad,height,x+horizpad,height-lineheight,white);

      searchscore+=searchincrement;
      x++;
    }

  /**********************************
    Label the x axis
    ********************************/

  for (scoremark=LOWESTSCORE;scoremark<=HIGHESTSCORE;scoremark++)
    {
      x=(scoremark-LOWESTSCORE)*(width/(HIGHESTSCORE-LOWESTSCORE));

      snprintf(label,5,"%i",scoremark);
      labellen=strlen(label);

      gdImageLine(im,x+horizpad,0,x+horizpad,height,blue);
      gdImageString(im,gdFontLarge, x+horizpad-(gdFontLarge->w/2)*labellen,height+2,label,white);
    }

  /**********************************
    Outline the actual data
    ********************************/
  gdImageRectangle(im,horizpad,1,width+horizpad,height,white);
  
  votelabel=sprintfalloc("%i samples",Vector_getSize(stats));
  gdImageString(im,gdFontLarge,width+horizpad-(gdFontLarge->w)*strlen(votelabel)-2,2,votelabel,lightblue);
  free(votelabel);

  /**********************************
    Output the data 
    ********************************/

  /* use gdImagePng if possible */
  gdImageGif(im,stdout);

  gdImageDestroy(im);

  return 0;
}
Exemple #3
0
/*
  Function: gdImageCreateFromGd2PartCtx

  Parameters:

    in          - The data source.
    srcx, srcy  - The source X and Y coordinates
    w, h        - The resulting image's width and height

  Reads in part of a GD2 data image file via a <gdIOCtx> struct.  See
  <gdImageCreateFromGd2Part>.
*/
BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
{
	int scx, scy, ecx, ecy, fsx, fsy;
	int nc, ncx, ncy, cs, cx, cy;
	int x, y, ylo, yhi, xlo, xhi;
	int dstart, dpos;
	int i;
	/* 2.0.12: unsigned is correct; fixes problems with color munging.
	   Thanks to Steven Brown. */
	unsigned int ch;
	int vers, fmt;
	t_chunk_info *chunkIdx = NULL;
	unsigned char *chunkBuf = NULL;
	int chunkNum;
	int chunkMax = 0;
	uLongf chunkLen;
	int chunkPos = 0;
	int compMax;
	char *compBuf = NULL;

	gdImagePtr im;

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

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

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

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

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

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

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

	};

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return im;

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

}
Exemple #4
0
/*int initGD(int DimX, int DimY);*/
int initGD(int DimX, int DimY) {
        return (int)gdImageCreate(DimX, DimY);
}
Exemple #5
0
void paintMap ()
{
  /* Declare the image */
  gdImagePtr im;

  /* Color indexes */
  int black;
  int white;
  int gridgray;
  int mapcolors[16];

  /* Allocate the image */
  im = gdImageCreate(600, 600);

  /* Allocate colors */
  black = gdImageColorAllocate (im, 0, 0, 0);
  white = gdImageColorAllocate (im, 255, 255, 255);
  gridgray = gdImageColorAllocate (im, 64, 64, 64);

  /* Allocate map colors */
  mapcolors[0] = gdImageColorAllocate (im, 196, 196, 196); // gray
  mapcolors[1] = gdImageColorAllocate (im, 0, 0, 128); // darkblue
  mapcolors[2] = gdImageColorAllocate (im, 0, 128, 0); // darkgreen
  mapcolors[3] = gdImageColorAllocate (im, 0, 128, 128); // darkcyan
  mapcolors[4] = gdImageColorAllocate (im, 128, 0, 0); // darkred
  mapcolors[5] = gdImageColorAllocate (im, 128, 0, 128); // darkmagenta
  mapcolors[6] = gdImageColorAllocate (im, 128, 128, 0); // darkyellow
  mapcolors[7] = gdImageColorAllocate (im, 128, 128, 128); // darkgray
  mapcolors[8] = gdImageColorAllocate (im, 255, 255, 255); // white
  mapcolors[9] = gdImageColorAllocate (im, 0, 0, 255); // blue
  mapcolors[10] = gdImageColorAllocate (im, 0, 255, 0); // green
  mapcolors[11] = gdImageColorAllocate (im, 0, 255, 255); // cyan
  mapcolors[12] = gdImageColorAllocate (im, 255, 0, 0); // red
  mapcolors[13] = gdImageColorAllocate (im, 255, 0, 255); // magenta? (purple)
  mapcolors[14] = gdImageColorAllocate (im, 255, 255, 0); // yellow
  mapcolors[15] = gdImageColorAllocate (im, 196, 196, 196); // gray
  
  /* Draw the grid */
  for (int gx = (zoomMinX / 1000) - 1; gx <= (zoomMaxX / 1000) + 1; gx++)
    {
      int sx, sy;
      gdImageLine (im, sx=calcXOffset (gx * 1000), sy=0, calcXOffset (gx *
				      1000), 600, gridgray);
      char label[32];
      sprintf (label, "%d", gx*1000);
      gdImageString (im, gdFontSmall, sx+1, sy, (unsigned char *)label, gridgray);
      gdImageString (im, gdFontSmall, sx+1, sy-10, (unsigned char *)label, gridgray);
    }
  for (int gy = (zoomMinY / 1000) - 1; gy <= (zoomMaxY / 1000) + 1; gy++)
    {
      int sx, sy;
      gdImageLine (im, sx=0, sy=calcYOffset (gy * 1000), 600, calcYOffset (gy
					* 1000), gridgray);  
      char label[32];
      sprintf (label, "%d", gy*1000);
      gdImageString (im, gdFontSmall, sx, sy, (unsigned char *)label, gridgray);
    }

  /* Draw lines */
  for (int l = 0; l < numLines; l++)
    {
      for (int n =0; n<(linePoints[l]-1); n++)
        {
          gdImageLine (im, 
		      calcXOffset (lineX[l][n]), calcYOffset (lineY[l][n]),
		      calcXOffset (lineX[l][n+1]), calcYOffset (lineY[l][n+1]),
			      mapcolors[lineColor[l]]);
        }
    }

  /* Paint the locations */
  int tmpcolor;
   for (int n = 0; n < numLocations; n++)
   {
     if (!locationColor[n]) 
      {
	tmpcolor = white;
      }
     else 
      {
	tmpcolor = mapcolors[locationColor[n]];
      }
   
     gdImageString (im, gdFontSmall, 
		    calcXOffset (locationX[n]) - 2, 
		    calcYOffset (locationY[n]) - 2,
		    (unsigned char*)(const char *)locationName[n], tmpcolor);
   }

  /* Print the http header */
#ifdef HAVE_GD_IMAGEPNG
  printf ("Content-type: image/png\n\n");
#else
  printf ("Content-type: image/gif\n\n");
#endif

  /* Output image */
#ifdef HAVE_GD_IMAGEPNG
  gdImagePng(im, stdout);
#else
  gdImageGif(im, stdout);
#endif

  /* Destroy image */
  gdImageDestroy(im);

}
Exemple #6
0
int
list_fragments(int fd, u64 flags, char *dir)
{
	int ret;
	struct btrfs_ioctl_search_args args;
	struct btrfs_ioctl_search_key *sk = &args.key;
	int i;
	struct btrfs_ioctl_search_header *sh;
	unsigned long off = 0;
	int bgnum = 0;
	u64 bgstart = 0;
	u64 bglen = 0;
	u64 bgend = 0;
	u64 bgflags = 0;
	u64 bgused = 0;
	u64 saved_extent = 0;
	u64 saved_len = 0;
	int saved_color = 0;
	u64 last_end = 0;
	u64 areas = 0;
	long px;
	char name[1000];
	FILE *html;
	int colors[COLOR_MAX];

	gdImagePtr im = NULL;
	int black = 0;
	int width = 800;

	snprintf(name, sizeof(name), "%s/index.html", dir);
	html = fopen(name, "w");
	if (!html) {
		printf("unable to create %s\n", name);
		exit(1);
	}

	fprintf(html, "<html><header>\n");
	fprintf(html, "<title>Btrfs Block Group Allocation Map</title>\n");
	fprintf(html, "<style type=\"text/css\">\n");
	fprintf(html, "img {margin-left: 1em; margin-bottom: 2em;}\n");
	fprintf(html, "</style>\n");
	fprintf(html, "</header><body>\n");
	
	memset(&args, 0, sizeof(args));

	sk->tree_id = 2;
	sk->max_type = -1;
	sk->min_type = 0;
	sk->max_objectid = (u64)-1;
	sk->max_offset = (u64)-1;
	sk->max_transid = (u64)-1;

	/* just a big number, doesn't matter much */
	sk->nr_items = 4096;

	while(1) {
		ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
		if (ret < 0) {
			fprintf(stderr, "ERROR: can't perform the search\n");
			goto out_close;
		}
		/* the ioctl returns the number of item it found in nr_items */
		if (sk->nr_items == 0)
			break;

		off = 0;
		for (i = 0; i < sk->nr_items; i++) {
			int j;

			sh = (struct btrfs_ioctl_search_header *)(args.buf +
								  off);
			off += sizeof(*sh);
			if (sh->type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
				struct btrfs_block_group_item *bg;

				if (im) {
					push_im(im, name, dir);
					im = NULL;

					print_bg(html, name, bgstart, bglen,
						bgused, bgflags, areas);
				}

				++bgnum;

				bg = (struct btrfs_block_group_item *)
						(args.buf + off);
				bgflags = btrfs_block_group_flags(bg);
				bgused = btrfs_block_group_used(bg);
				
				printf("found block group %lld len %lld "
					"flags %lld\n", sh->objectid,
					sh->offset, bgflags);
				if (!(bgflags & flags)) {
					/* skip this block group */
					sk->min_objectid = sh->objectid +
							   sh->offset;
					sk->min_type = 0;
					sk->min_offset = 0;
					break;
				}
				im = gdImageCreate(width,
					(sh->offset / 4096 + 799) / width);

				black = gdImageColorAllocate(im, 0, 0, 0);  

				for (j = 0; j < ARRAY_SIZE(colors); ++j)
					colors[j] = black;

				init_colors(im, colors);
				bgstart = sh->objectid;
				bglen = sh->offset;
				bgend = bgstart + bglen;

				snprintf(name, sizeof(name), "bg%d.png", bgnum);

				last_end = bgstart;
				if (saved_len) {
					px = (saved_extent - bgstart) / 4096;
					for (j = 0; j < saved_len / 4096; ++j) {
						int x = (px + j) % width;
						int y = (px + j) / width;
						gdImageSetPixel(im, x, y,
								saved_color);
					}
					last_end += saved_len;
				}
				areas = 0;
				saved_len = 0;
			}
			if (im && sh->type == BTRFS_EXTENT_ITEM_KEY) {
				int c;
				struct btrfs_extent_item *item;

				item = (struct btrfs_extent_item *)
						(args.buf + off);

				if (use_color)
					c = colors[get_color(item, sh->len)];
				else
					c = black;
				if (sh->objectid > bgend) {
					printf("WARN: extent %lld is without "
						"block group\n", sh->objectid);
					goto skip;
				}
				if (sh->objectid == bgend) {
					saved_extent = sh->objectid;
					saved_len = sh->offset;
					saved_color = c;
					goto skip;
				}
				px = (sh->objectid - bgstart) / 4096;
				for (j = 0; j < sh->offset / 4096; ++j) {
					int x = (px + j) % width;
					int y = (px + j) / width;
					gdImageSetPixel(im, x, y, c);
				}
				if (sh->objectid != last_end)
					++areas;
				last_end = sh->objectid + sh->offset;
skip:;
			}
			off += sh->len;

			/*
			 * record the mins in sk so we can make sure the
			 * next search doesn't repeat this root
			 */
			sk->min_objectid = sh->objectid;
			sk->min_type = sh->type;
			sk->min_offset = sh->offset;
		}
		sk->nr_items = 4096;

		/* increment by one */
		if (++sk->min_offset == 0)
			if (++sk->min_type == 0)
				if (++sk->min_objectid == 0)
					break;
	}

	if (im) {
		push_im(im, name, dir);
		print_bg(html, name, bgstart, bglen, bgused, bgflags, areas);
	}

	if (use_color) {
		fprintf(html, "<p>");
		fprintf(html, "data - dark red, ");
		fprintf(html, "fs tree - black, ");
		fprintf(html, "extent tree - green, ");
		fprintf(html, "csum tree - blue, ");
		fprintf(html, "reloc tree - grey, ");
		fprintf(html, "other trees - red, ");
		fprintf(html, "unknown tree - dark grey");
		fprintf(html, "</p>");
	}
	fprintf(html, "</body></html>\n");

out_close:
	fclose(html);

	return ret;
}
Exemple #7
0
int main(int argc, char *argv[])
{
  FILE *stream;
  int ns,n,k;
  gdImagePtr img;
  shapeObj p;
  int i,j;
  int ncols,nrows;
  char buffer[256];
  int gray, green, red, black, white;
  classObj class;
  symbolSetObj symbolSet;

   /* ---- check the number of arguments, return syntax if not correct ---- */
  if( argc < 2 ) {
      fprintf(stdout, "Syntax: sym2img [symbolset] [outfile]\n" );
      exit(0);
  }

  /* Initialize the polygon/polyline */
  p.line = (lineObj *)malloc(sizeof(lineObj));
  p.numlines = 1;
  p.line[0].point = (pointObj *)malloc(sizeof(pointObj)*4);
  p.line[0].numpoints = 4;

  /* Initialize the symbol and font sets */
  symbolSet.filename = msStrdup(argv[1]);

  /* 
  ** load the symbol file
  */
  if(msLoadSymbolSet(&symbolSet) == -1) { 
    msWriteError(stderr);
    exit(1);
  }
  
  ns = symbolSet.numsymbols;

  if(ns < NCOLS) {
    ncols = ns;
    nrows = 1;
  } else {
    ncols = NCOLS;
    nrows = (int)ceil((double)ns/NCOLS);
  }

  img = gdImageCreate(ncols*CELLSIZE, nrows*CELLSIZE);

  gray = gdImageColorAllocate(img, 222, 222, 222);
  white = gdImageColorAllocate(img, 255, 255, 255);
  green = gdImageColorAllocate(img, 40, 170, 40);
  black = gdImageColorAllocate(img, 0, 0, 0);
  red = gdImageColorAllocate(img, 255, 0, 0);

  class.color = red;
  class.backgroundcolor = white;
  class.outlinecolor = black;

  n=0;

  for(i=0; n<ns;i+=CELLSIZE) {
	k=0;
    for(j=0; n<ns;j+=CELLSIZE) {
	  if (k == ncols) break;
	  k++;
      gdImageFilledRectangle(img,j,i,j+CELLSIZE, i+CELLSIZE, gray);

      class.symbol = n;

      switch(symbolSet.type) {
      case(MS_MARKERSET):
	class.sizescaled = RATIO*CELLSIZE;
	p.line[0].point[0].x = MS_NINT(j + CELLSIZE/2);
	p.line[0].point[0].y = MS_NINT(i + CELLSIZE/2);
	p.line[0].numpoints = 1;
	msDrawMarkerSymbol(&(symbolSet), img, &(p.line[0].point[0]), &(class));
	break;

      case(MS_LINESET):
	class.sizescaled = 1;
	p.line[0].point[0].x = j;
        p.line[0].point[0].y = i + (CELLSIZE-LBUF) - 1;
	p.line[0].point[1].x = j + MS_NINT((CELLSIZE-LBUF)/3.0) - 1;
        p.line[0].point[1].y = i;
        p.line[0].point[2].x = j + MS_NINT(2*(CELLSIZE-LBUF)/3.0) - 1;
        p.line[0].point[2].y = i + (CELLSIZE-LBUF) - 1;
	p.line[0].point[3].x = j + (CELLSIZE-LBUF) - 1;
        p.line[0].point[3].y = i;
	p.line[0].numpoints = 4;
        msDrawLineSymbol(&(symbolSet), img, &p, &(class));
	break;

      case(MS_SHADESET):
	class.sizescaled = 5;
	p.line[0].point[0].x = j;
	p.line[0].point[0].y = i;
	p.line[0].point[1].x = j + CELLSIZE-1;
	p.line[0].point[1].y = i;
	p.line[0].point[2].x = j + CELLSIZE-1;
	p.line[0].point[2].y = i + CELLSIZE-1 ;
	p.line[0].point[3].x = j;
	p.line[0].point[3].y = i + CELLSIZE-1;
	p.line[0].numpoints = 4;
	msDrawShadeSymbol(&(symbolSet), img, &p, &(class));
	break;

      default:
	break;
      }

      if(symbolSet.symbol[n]->name)
        snprintf(buffer, sizeof(buffer), "%d - %s", n, symbolSet.symbol[n]->name);
      else
        snprintf(buffer, sizeof(buffer), "%d", n);
      gdImageString(img, gdFontTiny, j+1, i+1, buffer, black);

      n++;
    }
  }

 if((stream = fopen(argv[2],"wb")) == NULL) { /* open the file */
    fprintf(stderr, "Unable to open output file: %s\n", argv[2]);
    exit(1);
  }
#ifndef USE_GD_1_6
  gdImageGif(img, stream);
#else
  gdImagePng(img, stream);
#endif
  gdImageDestroy(img);
  free(symbolSet.filename);
  fclose(stream);

  return(MS_TRUE);
}
Exemple #8
0
int
main (int argc, char **argv)
{
#ifdef HAVE_LIBPNG
  gdImagePtr im, ref, im2, im3;
  FILE *in, *out;
  void *iptr;
  int sz;
  char of[256];
  int colRed, colBlu;
  gdSource imgsrc;
  gdSink imgsnk;
  int foreground;
  int i;
  if (argc != 2)
    {
      fprintf (stderr, "Usage: gdtest filename.png\n");
      exit (1);
    }
  in = fopen (argv[1], "rb");
  if (!in)
    {
      fprintf (stderr, "Input file does not exist!\n");
      exit (1);
    }
  im = gdImageCreateFromPng (in);

  rewind (in);
  ref = gdImageCreateFromPng (in);

  fclose (in);

  printf ("Reference File has %d Palette entries\n", ref->colorsTotal);

  CompareImages ("Initial Versions", ref, im);


  /* */
  /* Send to PNG File then Ptr */
  /* */
  sprintf (of, "%s.png", argv[1]);
  out = fopen (of, "wb");
  gdImagePng (im, out);
  fclose (out);

  in = fopen (of, "rb");
  if (!in)
    {
      fprintf (stderr, "PNG Output file does not exist!\n");
      exit (1);
    }
  im2 = gdImageCreateFromPng (in);
  fclose (in);

  CompareImages ("GD->PNG File->GD", ref, im2);

  unlink (of);
  gdImageDestroy (im2);

  /* 2.0.21: use the new From*Ptr functions */
  iptr = gdImagePngPtr (im, &sz);
  im2 = gdImageCreateFromPngPtr (sz, iptr);
  gdFree (iptr);
  CompareImages ("GD->PNG ptr->GD", ref, im2);

  gdImageDestroy (im2);

  /* */
  /* Send to GD2 File then Ptr */
  /* */
  sprintf (of, "%s.gd2", argv[1]);
  out = fopen (of, "wb");
  gdImageGd2 (im, out, 128, 2);
  fclose (out);

  in = fopen (of, "rb");
  if (!in)
    {
      fprintf (stderr, "GD2 Output file does not exist!\n");
      exit (1);
    }
  im2 = gdImageCreateFromGd2 (in);
  fclose (in);

  CompareImages ("GD->GD2 File->GD", ref, im2);

  unlink (of);
  gdImageDestroy (im2);

  iptr = gdImageGd2Ptr (im, 128, 2, &sz);
  /*printf("Got ptr %d (size %d)\n",iptr, sz); */
  im2 = gdImageCreateFromGd2Ptr (sz, iptr);
  gdFree (iptr);
  /*printf("Got img2 %d\n",im2); */

  CompareImages ("GD->GD2 ptr->GD", ref, im2);

  gdImageDestroy (im2);

  /* */
  /* Send to GD File then Ptr */
  /* */
  sprintf (of, "%s.gd", argv[1]);
  out = fopen (of, "wb");
  gdImageGd (im, out);
  fclose (out);

  in = fopen (of, "rb");
  if (!in)
    {
      fprintf (stderr, "GD Output file does not exist!\n");
      exit (1);
    }
  im2 = gdImageCreateFromGd (in);
  fclose (in);

  CompareImages ("GD->GD File->GD", ref, im2);

  unlink (of);
  gdImageDestroy (im2);

  iptr = gdImageGdPtr (im, &sz);
  /*printf("Got ptr %d (size %d)\n",iptr, sz); */
  im2 = gdImageCreateFromGdPtr (sz, iptr);
  gdFree (iptr);
  /*printf("Got img2 %d\n",im2); */

  CompareImages ("GD->GD ptr->GD", ref, im2);

  gdImageDestroy (im2);

  /*
     ** Test gdImageCreateFromPngSource'
     * */

  in = fopen (argv[1], "rb");

  imgsrc.source = freadWrapper;
  imgsrc.context = in;
  im2 = gdImageCreateFromPngSource (&imgsrc);
  fclose (in);

  if (im2 == NULL)
    {
      printf
	("GD Source: ERROR Null returned by gdImageCreateFromPngSource\n");
    }
  else
    {
      CompareImages ("GD Source", ref, im2);
      gdImageDestroy (im2);
    };


  /*
     ** Test gdImagePngToSink'
     * */

  sprintf (of, "%s.snk", argv[1]);
  out = fopen (of, "wb");
  imgsnk.sink = fwriteWrapper;
  imgsnk.context = out;
  gdImagePngToSink (im, &imgsnk);
  fclose (out);
  in = fopen (of, "rb");
  if (!in)
    {
      fprintf (stderr,
	       "GD Sink: ERROR - GD Sink Output file does not exist!\n");
    }
  else
    {
      im2 = gdImageCreateFromPng (in);
      fclose (in);

      CompareImages ("GD Sink", ref, im2);
      gdImageDestroy (im2);
    };

  unlink (of);

  /* */
  /*  Test Extraction */
  /* */
  in = fopen ("test/gdtest_200_300_150_100.png", "rb");
  if (!in)
    {
      fprintf (stderr, "gdtest_200_300_150_100.png does not exist!\n");
      exit (1);
    }
  im2 = gdImageCreateFromPng (in);
  fclose (in);


  in = fopen ("test/gdtest.gd2", "rb");
  if (!in)
    {
      fprintf (stderr, "gdtest.gd2 does not exist!\n");
      exit (1);
    }
  im3 = gdImageCreateFromGd2Part (in, 200, 300, 150, 100);
  fclose (in);

  CompareImages ("GD2Part (gdtest_200_300_150_100.png, gdtest.gd2(part))",
		 im2, im3);

  gdImageDestroy (im2);
  gdImageDestroy (im3);

  /* */
  /*  Copy Blend */
  /* */
  in = fopen ("test/gdtest.png", "rb");
  if (!in)
    {
      fprintf (stderr, "gdtest.png does not exist!\n");
      exit (1);
    }
  im2 = gdImageCreateFromPng (in);
  fclose (in);

  im3 = gdImageCreate (100, 60);
  colRed = gdImageColorAllocate (im3, 255, 0, 0);
  colBlu = gdImageColorAllocate (im3, 0, 0, 255);
  gdImageFilledRectangle (im3, 0, 0, 49, 30, colRed);
  gdImageFilledRectangle (im3, 50, 30, 99, 59, colBlu);

  gdImageCopyMerge (im2, im3, 150, 200, 10, 10, 90, 50, 50);
  gdImageCopyMerge (im2, im3, 180, 70, 10, 10, 90, 50, 50);

  gdImageCopyMergeGray (im2, im3, 250, 160, 10, 10, 90, 50, 50);
  gdImageCopyMergeGray (im2, im3, 80, 70, 10, 10, 90, 50, 50);

  gdImageDestroy (im3);

  in = fopen ("test/gdtest_merge.png", "rb");
  if (!in)
    {
      fprintf (stderr, "gdtest_merge.png does not exist!\n");
      exit (1);
    }
  im3 = gdImageCreateFromPng (in);
  fclose (in);

  printf ("[Merged Image has %d colours]\n", im2->colorsTotal);
  CompareImages ("Merged (gdtest.png, gdtest_merge.png)", im2, im3);

  gdImageDestroy (im2);
  gdImageDestroy (im3);

#ifdef HAVE_LIBJPEG
  out = fopen ("test/gdtest.jpg", "wb");
  if (!out)
    {
      fprintf (stderr, "Can't create file test/gdtest.jpg.\n");
      exit (1);
    }
  gdImageJpeg (im, out, -1);
  fclose (out);
  in = fopen ("test/gdtest.jpg", "rb");
  if (!in)
    {
      fprintf (stderr, "Can't open file test/gdtest.jpg.\n");
      exit (1);
    }
  im2 = gdImageCreateFromJpeg (in);
  fclose (in);
  if (!im2)
    {
      fprintf (stderr, "gdImageCreateFromJpeg failed.\n");
      exit (1);
    }
  gdImageDestroy (im2);
  printf ("Created test/gdtest.jpg successfully. Compare this image\n"
	  "to the input image manually. Some difference must be\n"
	  "expected as JPEG is a lossy file format.\n");
#endif /* HAVE_LIBJPEG */
  /* Assume the color closest to black is the foreground
     color for the B&W wbmp image. */
  fprintf (stderr,
	   "NOTE: the WBMP output image will NOT match the original unless the original\n"
	   "is also black and white. This is OK!\n");
  foreground = gdImageColorClosest (im, 0, 0, 0);
  fprintf (stderr, "Foreground index is %d\n", foreground);
  if (foreground == -1)
    {
      fprintf (stderr, "Source image has no colors, skipping wbmp test.\n");
    }
  else
    {
      out = fopen ("test/gdtest.wbmp", "wb");
      if (!out)
	{
	  fprintf (stderr, "Can't create file test/gdtest.wbmp.\n");
	  exit (1);
	}
      gdImageWBMP (im, foreground, out);
      fclose (out);
      in = fopen ("test/gdtest.wbmp", "rb");
      if (!in)
	{
	  fprintf (stderr, "Can't open file test/gdtest.wbmp.\n");
	  exit (1);
	}
      im2 = gdImageCreateFromWBMP (in);
      fprintf (stderr, "WBMP has %d colors\n", gdImageColorsTotal (im2));
      fprintf (stderr, "WBMP colors are:\n");
      for (i = 0; (i < gdImageColorsTotal (im2)); i++)
	{
	  fprintf (stderr, "%02X%02X%02X\n",
		   gdImageRed (im2, i),
		   gdImageGreen (im2, i), gdImageBlue (im2, i));
	}
      fclose (in);
      if (!im2)
	{
	  fprintf (stderr, "gdImageCreateFromWBMP failed.\n");
	  exit (1);
	}
      CompareImages ("WBMP test (gdtest.png, gdtest.wbmp)", ref, im2);
      out = fopen ("test/gdtest_wbmp_to_png.png", "wb");
      if (!out)
	{
	  fprintf (stderr,
		   "Can't create file test/gdtest_wbmp_to_png.png.\n");
	  exit (1);
	}
      gdImagePng (im2, out);
      fclose (out);
      gdImageDestroy (im2);
    }
  gdImageDestroy (im);
  gdImageDestroy (ref);
#else
  fprintf (stderr, "No PNG library support.\n");
#endif /* HAVE_LIBPNG */

  return 0;
}
Exemple #9
0
int drawAsStructure( gdImagePtr* image, JBMaze* maze, JBMazePt* path, int len, PARMOPTS* opts ) {
  int wallClr;
  int bgColor;
  int boundClr;
  int i;
  int j;
  int ofs;
  int inc;
  int dir;
  int wallWid;
  int xSize;
  int ySize;
  int gridSize;

  JBMazeMask* mask;

  ofs = opts->ofs;
  inc = opts->pathWid;
  wallWid = opts->wallWid;

  gridSize = inc + wallWid + 1;
  mask = maze->getMask();

  xSize = ofs*2 + gridSize * maze->getX() + wallWid+2;
  ySize = ofs*2 + gridSize * maze->getY() + wallWid+2;

  *image = gdImageCreate( xSize, ySize );

  bgColor = gdImageColorAllocate( *image, RED(opts->bgColor), GREEN(opts->bgColor), BLUE(opts->bgColor) );
  wallClr = gdImageColorAllocate( *image, RED(opts->wallClr), GREEN(opts->wallClr), BLUE(opts->wallClr) );
  boundClr = gdImageColorAllocate( *image, RED(opts->boundClr), GREEN(opts->boundClr), BLUE(opts->boundClr) );

  gdImageFilledRectangle( *image, 0, 0, xSize - 1, ySize - 1, bgColor );

  ofs++;
  for( j = 0; j < maze->getY(); j++ ) {
    for( i = 0; i < maze->getX(); i++ ) {
      dir = maze->getExitsAt( i, j, 0 );
      if( dir == 0 ) {
        gdImageFilledRectangle( *image,
              ofs + i * gridSize, ofs + j * gridSize,
              ofs + (i+1) * gridSize, ofs + (j+1) * gridSize,
              wallClr );
      } else {
        if( ( dir & JBMaze::c_NORTH ) == 0  ) {
          gdImageFilledRectangle( *image,
              ofs + i * gridSize, ofs + j * gridSize,
              ofs + (i+1) * gridSize + wallWid, ofs + j * gridSize + wallWid,
              wallClr );
        }
        if( ( dir & JBMaze::c_WEST ) == 0 ) {
          gdImageFilledRectangle( *image,
              ofs + i * gridSize, ofs + j * gridSize,
              ofs + i * gridSize + wallWid, ofs + (j+1) * gridSize + wallWid,
              wallClr );
        }
      }
    }
  }

  /* right wall */
  gdImageFilledRectangle( *image,
                          ofs + maze->getX() * gridSize,
                          ofs,
                          ofs + maze->getX() * gridSize + wallWid,
                          ofs + maze->getY() * gridSize + wallWid,
                          wallClr );

  /* bottom wall */
  gdImageFilledRectangle( *image,
                          ofs,
                          ofs + maze->getY() * gridSize,
                          ofs + maze->getX() * gridSize + wallWid,
                          ofs + maze->getY() * gridSize + wallWid,
                          wallClr );


  /* trace the mask */

  for( j = 0; j < maze->getY(); j++ ) {
    for( i = 0; i < maze->getX(); i++ ) {
      if( verticalBoundary( mask, i, j ) ) {
        gdImageLine( *image, 
                     ofs + i * gridSize, 
                     ofs + j * gridSize,
                     ofs + (i+1) * gridSize,
                     ofs + j * gridSize,
                     boundClr );                  
      }
      if( horizontalBoundary( mask, i, j ) ) {
        gdImageLine( *image, 
                     ofs + i * gridSize, 
                     ofs + j * gridSize,
                     ofs + i * gridSize,
                     ofs + (j+1) * gridSize,
                     boundClr );                  
      }
    }
  }

  gdImageLine( *image, ofs, 
                       ofs + maze->getY() * gridSize + 1,
                       ofs + maze->getX() * gridSize + 1, 
                       ofs + maze->getY() * gridSize + 1,
                       boundClr );

  gdImageLine( *image, ofs + maze->getX() * gridSize + 1,
                       ofs,
                       ofs + maze->getX() * gridSize + 1, 
                       ofs + maze->getY() * gridSize + 1,
                       boundClr );

  /* display the beginning and ending markers */

  if( opts->showMarkers ) {
    int startClr;
    int endClr;

    startClr = gdImageColorAllocate( *image, RED(opts->startClr), GREEN(opts->startClr), BLUE(opts->startClr) );
    endClr   = gdImageColorAllocate( *image, RED(opts->endClr), GREEN(opts->endClr), BLUE(opts->endClr) );

    gdImageFilledRectangle( *image,
                            ofs + maze->getStart().x * gridSize + wallWid + 1,
                            ofs + maze->getStart().y * gridSize + wallWid + 1,
                            ofs + (maze->getStart().x+1) * gridSize - wallWid,
                            ofs + (maze->getStart().y+1) * gridSize - wallWid,
                            startClr );
    gdImageFilledRectangle( *image,
                            ofs + maze->getEnd().x * gridSize + wallWid + 1,
                            ofs + maze->getEnd().y * gridSize + wallWid + 1,
                            ofs + (maze->getEnd().x+1) * gridSize - wallWid,
                            ofs + (maze->getEnd().y+1) * gridSize - wallWid,
                            endClr );
  }

  /* display the solution */

  if( opts->showSolution ) {
    int pathClr;

    pathClr = gdImageColorAllocate( *image, RED(opts->pathClr), GREEN(opts->pathClr), BLUE(opts->pathClr) );

    for( j = 0; j < len-1; j++ ) {
      if( path[j].z == 0 ) {
        int x1 = ofs + path[j].x * gridSize + wallWid + inc/2+1;
        int y1 = ofs + path[j].y * gridSize + wallWid + inc/2+1;
        int x2 = ofs + path[j+1].x * gridSize + wallWid + inc/2+1;
        int y2 = ofs + path[j+1].y * gridSize + wallWid + inc/2+1;

        gdImageLine( *image,
                     x1, y1, x2, y2,
                     pathClr );
      }
    }
  }

  return 0;
}
Exemple #10
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;
}
Exemple #11
0
int main() {
  gdImagePtr im;
  FILE *pngout, *pArchivo;
  short int dato;
  int nx,ny,posicion;
  int resx,resy;
  int black, white, red, green, blue;
  float lonPL, latPL;
  float gris, color;
  int colorrgb;

  resx=10800;
  resy=6000;
  im = gdImageCreate(resx, resy);
  black = gdImageColorAllocate(im,  0,  0,  0);
  white = gdImageColorAllocate(im,255,255,255);
  red   = gdImageColorAllocate(im,255,  0,  0);
  green = gdImageColorAllocate(im,  0,255,  0);
  blue  = gdImageColorAllocate(im,  0,  0,255);
  // gdImageLine(im,0,0,resx,resy,white);
  // gdImageLine(im,resx,0,0,resy,red);
  // gdImageSetPixel(im, resx/3,resy/2, red);

  pArchivo=fopen("/home/marcos/WRF_PRD/globe_data/all10/f10g","r");
  if (pArchivo == NULL) {
    printf("*** ERROR: No se ha podido abrir el fichero solicitado.\n");
    return;
  }
  for (nx = 0; nx < resx ; nx++) {
    for (ny = 0; ny < resy ; ny++) {
      posicion= 21600 * ny + 2 * nx ;
      fseek(pArchivo, posicion, SEEK_SET);
      fread(&dato, sizeof(short int), 1, pArchivo);
//      printf("%i, %i, %i\n", i,j,dato );

      if (dato < -499) {
        gdImageSetPixel(im, nx, ny, blue);
      }
      else if (dato > -499 & dato < 0) {
        gdImageSetPixel(im, nx,ny, red);
      }
      else {
        gris=(float)dato/6085.0; // 6085 metros es la altitud máxima de esta losa.
        color=255.0*gris;
        colorrgb=gdImageColorAllocate(im,(int)color,(int)color,(int)color);
        // printf("gris=%f, color=%i, colorrgb=%i\n",gris,(int)color,colorrgb );
        gdImageSetPixel(im, nx, ny, colorrgb);
        gdImageColorDeallocate(im, colorrgb);
      }
    }
  }

// Píxel en rojo en Puerto Lumbreras.
  latPL=37.5663;
  lonPL=-1.8083;
  latPL=6000.0-(latPL*120.0);
  lonPL=10800.0+(lonPL*120.0);
  printf("%f\n",lonPL );
  printf("latPL=%i px, lonPL=%i px\n",(int)latPL,(int)lonPL );

  gdImageSetPixel(im, (int)lonPL,(int)latPL, red);


  pngout=fopen("test.png","wb");
  gdImagePng(im, pngout);
  fclose(pngout);
  gdImageDestroy(im);
  fclose(pArchivo);
}
Exemple #12
0
int main()
{
	gdImagePtr src, dst;
	int r, g, b;
	void *p;
	int size = 0;
	int status = 0;
	CuTestImageResult result = {0, 0};

	src = gdImageCreate(100, 100);
	if (src == NULL) {
		printf("could not create src\n");
		return 1;
	}
	r = gdImageColorAllocate(src, 0xFF, 0, 0);
	g = gdImageColorAllocate(src, 0, 0xFF, 0);
	b = gdImageColorAllocate(src, 0, 0, 0xFF);
	gdImageFilledRectangle(src, 0, 0, 99, 99, r);
	gdImageRectangle(src, 20, 20, 79, 79, g);
	gdImageEllipse(src, 70, 25, 30, 20, b);

#define OUTPUT_GD2(x) do {												\
		FILE *fp;														\
																		\
		fp = fopen("gd2_im2im_" #x ".gd2", "wb");						\
		if (fp) {														\
			gdImageGd2(x, fp, (GD2_CHUNKSIZE_MIN+GD2_CHUNKSIZE_MAX)/2, GD2_FMT_COMPRESSED); \
			fclose(fp);													\
		}																\
	} while (0)

	OUTPUT_GD2(src);
	p = gdImageGd2Ptr(src, (GD2_CHUNKSIZE_MIN+GD2_CHUNKSIZE_MAX)/2, GD2_FMT_COMPRESSED, &size);
	if (p == NULL) {
		status = 1;
		printf("p is null\n");
		goto door0;
	}
	if (size <= 0) {
		status = 1;
		printf("size is non-positive\n");
		goto door1;
	}

	dst = gdImageCreateFromGd2Ptr(size, p);
	if (dst == NULL) {
		status = 1;
		printf("could not create dst\n");
		goto door1;
	}
	OUTPUT_GD2(dst);
	gdTestImageDiff(src, dst, NULL, &result);
	if (result.pixels_changed > 0) {
		status = 1;
		printf("pixels changed: %d\n", result.pixels_changed);
	}
	gdImageDestroy(dst);
 door1:
	gdFree(p);
 door0:
	gdImageDestroy(src);
	return status;
}
Exemple #13
0
/* {{{ gdImagePtr gdImageCreateFromXbm */
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;
}
Exemple #14
0
void binary(unsigned char *inputFileBuffer, int32_t inputFileSize, char *output, char *retinaout, int32_t columns, char *font, int32_t bits, bool icecolors, bool createRetinaRep)
{
    // some type declarations
    struct fontStruct fontData;

    // font selection
    alSelectFont(&fontData, font);

    // libgd image pointers
    gdImagePtr im_Binary;

    // allocate buffer image memory
    im_Binary = gdImageCreate(columns * bits, 
                              ((inputFileSize / 2) / columns * fontData.font_size_y));

    if (!im_Binary) {
        fputs ("\nError, can't allocate buffer image memory.\n\n", stderr); exit (6);
    }

    // allocate black color
    gdImageColorAllocate(im_Binary, 0, 0, 0);

    // allocate color palette
    int32_t colors[16];

    colors[0] = gdImageColorAllocate(im_Binary, 0, 0, 0);
    colors[1] = gdImageColorAllocate(im_Binary, 0, 0, 170);
    colors[2] = gdImageColorAllocate(im_Binary, 0, 170, 0);
    colors[3] = gdImageColorAllocate(im_Binary, 0, 170, 170);
    colors[4] = gdImageColorAllocate(im_Binary, 170, 0, 0);
    colors[5] = gdImageColorAllocate(im_Binary, 170, 0, 170);
    colors[6] = gdImageColorAllocate(im_Binary, 170, 85, 0);
    colors[7] = gdImageColorAllocate(im_Binary, 170, 170, 170);
    colors[8] = gdImageColorAllocate(im_Binary, 85, 85, 85);
    colors[9] = gdImageColorAllocate(im_Binary, 85, 85, 255);
    colors[10] = gdImageColorAllocate(im_Binary, 85, 255, 85);
    colors[11] = gdImageColorAllocate(im_Binary, 85, 255, 255);
    colors[12] = gdImageColorAllocate(im_Binary, 255, 85, 85);
    colors[13] = gdImageColorAllocate(im_Binary, 255, 85, 255);
    colors[14] = gdImageColorAllocate(im_Binary, 255, 255, 85);
    colors[15] = gdImageColorAllocate(im_Binary, 255, 255, 255);

    // process binary
    int32_t character, attribute, color_background, color_foreground;
    int32_t loop = 0, position_x = 0, position_y = 0;

    while (loop < inputFileSize)
    {
        if (position_x == columns) 
        {
            position_x = 0;
            position_y++;
        }

        character = inputFileBuffer[loop];
        attribute = inputFileBuffer[loop+1];

        color_background = (attribute & 240) >> 4;
        color_foreground = (attribute & 15);

        if (color_background > 8 && !icecolors)
        {
            color_background -= 8;
        }

        alDrawChar(im_Binary, fontData.font_data, bits, fontData.font_size_y, 
                   position_x, position_y, colors[color_background], colors[color_foreground], character);

        position_x++;
        loop+=2;
    }

    // create output image
    FILE *file_Out = fopen(output, "wb");
    gdImagePng(im_Binary, file_Out);
    fclose(file_Out);

    // in case Retina image output is wanted
    if (createRetinaRep)
    {
        gdImagePtr im_RetinaANSi;

        // make the Retina image @2x as large as im_Binary
        im_RetinaANSi = gdImageCreate(im_Binary->sx * 2, im_Binary->sy * 2);

        gdImageCopyResized(im_RetinaANSi, im_Binary, 0, 0, 0, 0,
                           im_RetinaANSi->sx, im_RetinaANSi->sy,
                           im_Binary->sx, im_Binary->sy);

        // create retina output image
        FILE *file_RetinaOut = fopen(retinaout, "wb");
        gdImagePng(im_RetinaANSi, file_RetinaOut);
        fclose(file_RetinaOut);

        gdImageDestroy(im_RetinaANSi);
    }

    // free memory
    gdImageDestroy(im_Binary);
}
Exemple #15
0
int create_png_range(const freq_range_t rx_range_list[],
                     const freq_range_t tx_range_list[],
                     int num)
{
    FILE *out;

    /* Input and output images */
    gdImagePtr im_rng;
    char rng_fname[128];

    /* Color indexes */
#if 0
    int white;
#endif
    int black;
    int rx_rgb, tx_rgb;

    /* Create output image, x by y pixels. */
    im_rng  = gdImageCreate(RANGE_WIDTH + IM_LGD, UHF_H + RANGE_HEIGHT);

    /* First color allocated is background. */
//    white = gdImageColorAllocate(im_rng, 255, 255, 255);
    gdImageColorAllocate(im_rng, 255, 255, 255);
    black = gdImageColorAllocate(im_rng, 0, 0, 0);

#if 0
    /* Set transparent color. */
    gdImageColorTransparent(im_rng, white);
#endif

    /* Try to load demoin.png and paste part of it into the
        output image. */

    tx_rgb = gdImageColorAllocate(im_rng, TX_R, TX_G, TX_B);
    rx_rgb = gdImageColorAllocate(im_rng, RX_R, RX_G, RX_B);

    draw_range(rx_range_list, im_rng, 0, RANGE_MIDHEIGHT - 1, rx_rgb);
    draw_range(tx_range_list, im_rng, RANGE_MIDHEIGHT, RANGE_HEIGHT - 1, tx_rgb);

    gdImageRectangle(im_rng,
                     IM_LGD,
                     HF_H,
                     IM_LGD + RANGE_WIDTH - 1,
                     HF_H + RANGE_HEIGHT - 1,
                     black);

    gdImageRectangle(im_rng,
                     IM_LGD,
                     VHF_H,
                     IM_LGD + RANGE_WIDTH - 1,
                     VHF_H + RANGE_HEIGHT - 1,
                     black);

    gdImageRectangle(im_rng,
                     IM_LGD,
                     UHF_H,
                     IM_LGD + RANGE_WIDTH - 1,
                     UHF_H + RANGE_HEIGHT - 1,
                     black);

    /* gdImageStringUp */
    gdImageString(im_rng,
                  gdFontSmall,
                  1,
                  HF_H + 1,
                  (unsigned char *) "HF",
                  black);

    gdImageString(im_rng,
                  gdFontSmall,
                  1,
                  VHF_H + 1,
                  (unsigned char *) "VHF",
                  black);

    gdImageString(im_rng,
                  gdFontSmall,
                  1,
                  UHF_H + 1,
                  (unsigned char *) "UHF",
                  black);

    /* Make output image interlaced (allows "fade in" in some viewers,
        and in the latest web browsers) */
    gdImageInterlace(im_rng, 1);

    sprintf(rng_fname, "range%d.png", num);
    out = fopen(rng_fname, "wb");

    /* Write PNG */
    gdImagePng(im_rng, out);
    fclose(out);
    gdImageDestroy(im_rng);

    return 0;
}
Exemple #16
0
static int createImage (MULTICHART_ID id)
{
    int         i;

    if (id->height < (10 * gdFontMediumBold->h))
    {
        return -1;
    }

    if (id->im)
    {
        gdImageDestroy (id->im);
    }

    id->im = gdImageCreate (id->width, id->height);
    if (id->im == NULL)
    {
        return -1;
    }

    //  ... allocate our colors
    id->bgcolor = gdImageColorAllocateAlpha (id->im,
                  GLC_RED(id->bgcolor),
                  GLC_GREEN(id->bgcolor),
                  GLC_BLUE(id->bgcolor),
                  GLC_ALPHA(id->bgcolor));

    if (id->isTransparent)
    {
        gdImageColorTransparent (id->im, id->bgcolor);
        id->chartcolor = id->bgcolor;
        id->titleBGcolor = id->bgcolor;
    }
    else
    {
        id->chartcolor = gdImageColorAllocateAlpha (id->im,
                         GLC_RED(id->chartcolor),
                         GLC_GREEN(id->chartcolor),
                         GLC_BLUE(id->chartcolor),
                         GLC_ALPHA(id->chartcolor));
        id->titleBGcolor = gdImageColorAllocateAlpha (id->im,
                           GLC_RED(id->titleBGcolor),
                           GLC_GREEN(id->titleBGcolor),
                           GLC_BLUE(id->titleBGcolor),
                           GLC_ALPHA(id->titleBGcolor));
    }

    id->gridcolor = gdImageColorAllocateAlpha (id->im,
                    GLC_RED(id->gridcolor),
                    GLC_GREEN(id->gridcolor),
                    GLC_BLUE(id->gridcolor),
                    GLC_ALPHA(id->gridcolor));
    id->titleFGcolor = gdImageColorAllocateAlpha (id->im,
                       GLC_RED(id->titleFGcolor),
                       GLC_GREEN(id->titleFGcolor),
                       GLC_BLUE(id->titleFGcolor),
                       GLC_ALPHA(id->titleFGcolor));
    id->textcolor = gdImageColorAllocateAlpha (id->im,
                    GLC_RED(id->textcolor),
                    GLC_GREEN(id->textcolor),
                    GLC_BLUE(id->textcolor),
                    GLC_ALPHA(id->textcolor));

    for (i = 0; i < id->numdatasets; i ++)
    {
        id->dataset[i].lineColor =
            gdImageColorAllocateAlpha (id->im,
                                       GLC_RED(id->dataset[i].lineColor),
                                       GLC_GREEN(id->dataset[i].lineColor),
                                       GLC_BLUE(id->dataset[i].lineColor),
                                       GLC_ALPHA(id->dataset[i].lineColor));
    }

    return 0;
}
Exemple #17
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];
#ifdef PNG_SETJMP_SUPPORTED
  jmpbuf_wrapper jbw;
#endif
  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;
  volatile png_bytep image_data = NULL;
  volatile 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_sig_cmp(sig, 0, 8) != 0) { /* bad signature */
    return NULL;
  }

#ifdef PNG_SETJMP_SUPPORTED
  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, &jbw, 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
   */
#ifdef PNG_SETJMP_SUPPORTED
  if (setjmp(jbw.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)
    || color_type == PNG_COLOR_TYPE_GRAY_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);

    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
   */
#ifdef PNG_SETJMP_SUPPORTED
  if (setjmp(jbw.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);
      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:
      /* 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.)
         */
      }
Exemple #18
0
int    tipojuego_get_logo( Tipojuego* tj, void** png, int* width, int* height ){
#if GRAPH_ENABLED
    Graphdef*  g = NULL;
    gdImagePtr gd = NULL;
    int i;
    if( tj->graphdefs ){
        for( i = 0; i < tj->graphdefs->entradas; i ++ ){
            Graphdef* g2 = tj->graphdefs->data[i];
            if( g2->tipo == TIPOGRAPH_LOGO ){
                g = g2;
                break;
            }
        }
    }
    if( !g ){
        LOGPRINT( 5, "Tipojuego %s no tiene definido logo ... va posicion inicial", tj->nombre );
        g = malloc( sizeof( Graphdef ) );
        memset( g, 0, sizeof( Graphdef ) );
        if( !tj->graphdefs ) tj->graphdefs = list_nueva( NULL );
        g->tipo = TIPOGRAPH_LOGO;
        list_agrega( tj->graphdefs, g );
    }
    if( g->gd ){
        gd = g->gd;
    } else {
        if( !g->cus ){
            gd = graph_dibujar_posicion( tj, 0, tj->inicial, NULL );
            g->gd = gdImageCreate( LOGO_WIDTH, LOGO_HEIGHT );
            gdImageCopyResized( g->gd, gd, 0, 0, 0, 0,
                LOGO_WIDTH, LOGO_HEIGHT,
                gdImageSX(gd), gdImageSY(gd) );
            gdImageDestroy( gd );
            gd = g->gd;
        } else if ( g->std == STANDARD_FROM_PGN )  {
            Partida* pp = partida_new( tj, "from_logo" );
            partida_mover_serie( pp, g->cus );
            gd = graph_dibujar_posicion( tj, 0, pp->pos, partida_ultimo_movimiento( pp ) );
            g->gd = gdImageCreate( LOGO_WIDTH, LOGO_HEIGHT );
            gdImageCopyResized( g->gd, gd, 0, 0, 0, 0,
                LOGO_WIDTH, LOGO_HEIGHT,
                gdImageSX(gd), gdImageSY(gd) );
            gdImageDestroy( gd );
            gd = g->gd;
        } else {
            FILE* fpng = fopen( g->cus, "r" );
            if( !fpng ){
                LOGPRINT( 2, "No puede abrir %s", g->cus );
                return 0;
            }
            gd = gdImageCreateFromPng( fpng );
            g->gd = gd;
            fclose( fpng );
        }
    }

    if( !gd ){
        LOGPRINT( 2, "No puede generarse logo para %s", tj->nombre );
        return 0;
    }
    int size = 0;
    if( png ) *png = gdImagePngPtr( gd, &size );
    if( width  ) *width  = gdImageSX( gd );
    if( height ) *height = gdImageSY( gd );
    return size;

#else
    LOGPRINT( 2, "No compilado con el modulo GD tjuego = %s", tj->nombre );
    return 0;
#endif
}
Exemple #19
0
/* ======================================================= *\ 
 * PIE
 * 
 * Notes:
 *  always drawn from 12:00 position clockwise
 *  'missing' slices don't get labels
 *  sum(val[0], ... val[num_points-1]) is assumed to be 100%
\* ======================================================= */
void
GDC_out_pie( short			IMGWIDTH,
			 short			IMGHEIGHT,
			 FILE			*img_fptr,			/* open file pointer */
			 GDCPIE_TYPE	type,
			 int			num_points,
			 char			*lbl[],				/* data labels */
			 float			val[] )				/* data */
{
	int			i;

	gdImagePtr	im;
	int			BGColor,
				LineColor,
				PlotColor,
				EdgeColor,
				EdgeColorShd;
	CREATE_ARRAY1( SliceColor, int, num_points );		/* int SliceColor[num_points] */
	CREATE_ARRAY1( SliceColorShd, int, num_points );	/* int SliceColorShd[num_points] */

	float		rad = 0.0;					/* radius */
	float		ellipsex = 1.0;
	float		ellipsey = 1.0 - (float)GDCPIE_perspective/100.0;
	float		tot_val = 0.0;
	float		pscl;
	int			cx,							/* affects PX() */
				cy;							/* affects PY() */
								/* ~ 1% for a size of 100 pixs */
								/* label sizes will more dictate this */
	float		min_grphable = ( GDCPIE_other_threshold < 0?
								  100.0/(float)MIN(IMGWIDTH,IMGHEIGHT):
								  (float)GDCPIE_other_threshold )/100.0;
	short		num_slices1 = 0,
				num_slices2 = 0;
	char		any_too_small = FALSE;
	CREATE_ARRAY1( others, char, num_points );			/* char others[num_points] */
	CREATE_ARRAY2( slice_angle, float, 3, num_points );	/* float slice_angle[3][num_points] */
														/* must be used with others[] */
	char		threeD = ( type == GDC_3DPIE );

	int			xdepth_3D      = 0,			/* affects PX() */
				ydepth_3D      = 0;			/* affects PY() */
	int			do3Dx = 0,					/* reserved for macro use */
				do3Dy = 0;

	CREATE_ARRAY2( pct_lbl, char, num_points, 16 );			/* sizeof or strlen (GDCPIE_percent_fmt)? */
	CREATE_ARRAY1( pct_ftsz, struct fnt_sz_t, num_points );	/* struct fnt_sz_t lbl_ftsz[num_points] */
	CREATE_ARRAY1( lbl_ftsz, struct fnt_sz_t, num_points );	/* struct fnt_sz_t lbl_ftsz[num_points] */


#ifdef HAVE_LIBFREETYPE
	char			*gdcpie_title_font  = GDCPIE_title_font;
	char			*gdcpie_label_font  = GDCPIE_label_font;
	double			gdcpie_title_ptsize = GDCPIE_title_ptsize;
	double			gdcpie_label_ptsize = GDCPIE_label_ptsize;
#else
	char			*gdcpie_title_font  = NULL;
	char			*gdcpie_label_font  = NULL;
	double			gdcpie_title_ptsize = 0.0;
	double			gdcpie_label_ptsize = 0.0;
#endif

/*	GDCPIE_3d_angle = MOD_360(90-GDCPIE_3d_angle+360); */
	pie_3D_rad = TO_RAD( GDCPIE_3d_angle );

	xdepth_3D      = threeD? (int)( cos((double)MOD_2PI(M_PI_2-pie_3D_rad+2.0*M_PI)) * GDCPIE_3d_depth ): 0;
	ydepth_3D      = threeD? (int)( sin((double)MOD_2PI(M_PI_2-pie_3D_rad+2.0*M_PI)) * GDCPIE_3d_depth ): 0;
/*	xdepth_3D      = threeD? (int)( cos(pie_3D_rad) * GDCPIE_3d_depth ): 0; */
/*	ydepth_3D      = threeD? (int)( sin(pie_3D_rad) * GDCPIE_3d_depth ): 0; */

	load_font_conversions();

	/* ----- get total value ----- */
	for( i=0; i<num_points; ++i )
		tot_val += val[i];

	/* ----- pie sizing ----- */
	/* ----- make width room for labels, depth, etc.: ----- */
	/* ----- determine pie's radius ----- */
	{
	int		title_hgt  = GDCPIE_title? 1			/*  title? horizontal text line */
									   + GDCfnt_sz( GDCPIE_title,
													GDCPIE_title_size,
													gdcpie_title_font, gdcpie_title_ptsize, 0.0, NULL ).h

									   + 2:
									   0;
	float	last = 0.0;
	float	label_explode_limit = 0.0;
	int		cheight,
			cwidth;

	/* maximum: no labels, explosions */
	/* gotta start somewhere */
	rad = (float)MIN( (IMGWIDTH/2)/ellipsex-(1+ABS(xdepth_3D)), (IMGHEIGHT/2)/ellipsey-(1+ABS(ydepth_3D))-title_hgt );

	/* ok fix center, i.e., no floating re labels, explosion, etc. */
	cx = IMGWIDTH/2 /* - xdepth_3D */ ;
	cy = (IMGHEIGHT-title_hgt)/2 + title_hgt /* + ydepth_3D */ ;

	cheight = (IMGHEIGHT- title_hgt)/2 /* - ydepth_3D */ ;
	cwidth  = cx;

	/* walk around pie. determine spacing to edge */
	for( i=0; i<num_points; ++i )
		{
		float	this_pct = val[i]/tot_val;						/* should never be > 100% */
		float	this = this_pct*(2.0*M_PI);						/* pie-portion */
		if( (this_pct > min_grphable) ||						/* too small */
			(!GDCPIE_missing || !GDCPIE_missing[i]) )			/* still want angles */
			{
			int this_explode = GDCPIE_explode? GDCPIE_explode[i]: 0;
			double	this_sin;
			double	this_cos;
			slice_angle[0][i] = this/2.0+last;				/* mid-point on full pie */
			slice_angle[1][i] = last;						/* 1st on full pie */
			slice_angle[2][i] = this+last;					/* 2nd on full pie */
			this_sin        = ellipsex*sin( (double)slice_angle[0][i] );
			this_cos        = ellipsey*cos( (double)slice_angle[0][i] );

			if( !GDCPIE_missing || !(GDCPIE_missing[i]) )
				{
				short	lbl_wdth = 0,
						lbl_hgt  = 0;
				float	this_y_explode_limit,
						this_x_explode_limit;

				/* start slice label height, width     */
				/*  accounting for PCT placement, font */
				pct_ftsz[i].h = 0;
				pct_ftsz[i].w = 0;
				if( GDCPIE_percent_fmt &&
					GDCPIE_percent_labels != GDCPIE_PCT_NONE )
					{
					sprintf( pct_lbl[i], GDCPIE_percent_fmt, this_pct * 100.0 );
					pct_ftsz[i] = GDCfnt_sz( pct_lbl[i],
											 GDCPIE_label_size,
											 gdcpie_label_font, gdcpie_label_ptsize, 0.0, NULL );
					lbl_wdth = pct_ftsz[i].w;
					lbl_hgt  = pct_ftsz[i].h;
					}

				if( lbl && lbl[i] )
					{
					lbl_ftsz[i] = GDCfnt_sz( lbl[i],
											 GDCPIE_label_size,
											 gdcpie_label_font, gdcpie_label_ptsize, 0.0, NULL );

					if( GDCPIE_percent_labels == GDCPIE_PCT_ABOVE ||
						GDCPIE_percent_labels == GDCPIE_PCT_BELOW )
						{
						lbl_wdth = MAX( pct_ftsz[i].w, lbl_ftsz[i].w );
						lbl_hgt  = pct_ftsz[i].h + lbl_ftsz[i].h + 1;
						}
					else
					if( GDCPIE_percent_labels == GDCPIE_PCT_RIGHT ||
						GDCPIE_percent_labels == GDCPIE_PCT_LEFT )
						{
						lbl_wdth = pct_ftsz[i].w + lbl_ftsz[i].w + 1;
						lbl_hgt  = MAX( pct_ftsz[i].h, lbl_ftsz[i].h );
						}
					else /* GDCPIE_PCT_NONE */
						{
						lbl_wdth = lbl_ftsz[i].w;
						lbl_hgt  = lbl_ftsz[i].h;
						}
					}
				else
					lbl_wdth = lbl_hgt = 0;
				/* end label height, width */
				
				/* diamiter limited by this point's: explosion, label                 */
				/* (radius to box @ slice_angle) - (explode) - (projected label size) */
				/* radius constraint due to labels */
				this_y_explode_limit = (float)this_cos==0.0? FLT_MAX:
										(	(float)( (double)cheight/ABS(this_cos) ) - 
											(float)( this_explode + (lbl&&lbl[i]? GDCPIE_label_dist: 0) ) -
											(float)( lbl_hgt/2 ) / (float)ABS(this_cos)	);
				this_x_explode_limit = (float)this_sin==0.0? FLT_MAX:
										(	(float)( (double)cwidth/ABS(this_sin) ) - 
											(float)( this_explode + (lbl&&lbl[i]? GDCPIE_label_dist: 0) ) -
											(float)( lbl_wdth ) / (float)ABS(this_sin)	);

				rad = MIN( rad, this_y_explode_limit );
				rad = MIN( rad, this_x_explode_limit );

				/* ok at this radius (which is most likely larger than final) */
				/* adjust for inter-label spacing */
/*				if( lbl[i] && *lbl[i] ) */
/*					{ */
/*					char which_edge = slice_angle[0][i] > M_PI? +1: -1;		// which semi */
/*					last_label_yedge = cheight - (int)( (rad +				// top or bottom of label */
/*														(float)(this_explode + */
/*														(float)GDCPIE_label_dist)) * (float)this_cos ) + */
/*											     ( (GDC_fontc[GDCPIE_label_size].h+1)/2 + */
/*													GDC_label_spacing )*which_edge; */
/*					} */

				/* radius constriant due to exploded depth */
				/* at each edge of the slice, and the middle */
				/* this is really stupid */
				/*  this section uses a different algorithm then above, but does the same thing */
				/*  could be combined, but each is ugly enough! */
/* PROTECT /0 */
				if( threeD )
					{
					short	j;
					int		this_y_explode_pos;
					int		this_x_explode_pos;

					/* first N E S W (actually no need for N) */
					if( (slice_angle[1][i] < M_PI_2 && M_PI_2 < slice_angle[2][i]) &&				/* E */
						(this_x_explode_pos=OX(i,M_PI_2,1)) > cx+cwidth )
						rad -= (float)ABS( (double)(1+this_x_explode_pos-(cx+cwidth))/sin(M_PI_2) );
					if( (slice_angle[1][i] < 3.0*M_PI_2 && 3.0*M_PI_2 < slice_angle[2][i]) &&		/* W */
						(this_x_explode_pos=OX(i,3.0*M_PI_2,1)) < cx-cwidth )
						rad -= (float)ABS( (double)(this_x_explode_pos-(cx+cwidth))/sin(3.0*M_PI_2) );
					if( (slice_angle[1][i] < M_PI && M_PI < slice_angle[2][i]) &&					/* S */
						(this_y_explode_pos=OY(i,M_PI,1)) > cy+cheight )
						rad -= (float)ABS( (double)(1+this_y_explode_pos-(cy+cheight))/cos(M_PI) );

					for( j=0; j<3; ++j )
						{
						this_y_explode_pos = IY(i,j,1);
						if( this_y_explode_pos < cy-cheight )
							rad -= (float)ABS( (double)((cy-cheight)-this_y_explode_pos)/cos((double)slice_angle[j][i]) );
						if( this_y_explode_pos > cy+cheight )
							rad -= (float)ABS( (double)(1+this_y_explode_pos-(cy+cheight))/cos((double)slice_angle[j][i]) );

						this_x_explode_pos = IX(i,j,1);
						if( this_x_explode_pos < cx-cwidth )
							rad -= (float)ABS( (double)((cx-cwidth)-this_x_explode_pos)/sin((double)slice_angle[j][i]) );
						if( this_x_explode_pos > cx+cwidth )
							rad -= (float)ABS( (double)(1+this_x_explode_pos-(cx+cwidth))/sin((double)slice_angle[j][i]) );
						}
					}
				}
			others[i] = FALSE;
			}
		else
			{
			others[i] = TRUE;
			slice_angle[0][i] = -FLT_MAX;
			}
		last += this;
		}
	}

	/* ----- go ahead and start the image ----- */
	im = gdImageCreate( IMGWIDTH, IMGHEIGHT );

	/* --- allocate the requested colors --- */
	BGColor   = clrallocate( im, GDCPIE_BGColor );
	LineColor = clrallocate( im, GDCPIE_LineColor );
	PlotColor = clrallocate( im, GDCPIE_PlotColor );
	if( GDCPIE_EdgeColor != GDC_NOCOLOR )
	 {
	 EdgeColor = clrallocate( im, GDCPIE_EdgeColor );
	 if( threeD )
	  EdgeColorShd = clrshdallocate( im, GDCPIE_EdgeColor );
	 }

	/* --- set color for each slice --- */
	for( i=0; i<num_points; ++i )
		if( GDCPIE_Color )
			{
			unsigned long	slc_clr = GDCPIE_Color[i];

			SliceColor[i]     = clrallocate( im, slc_clr );
			if( threeD )
			 SliceColorShd[i] = clrshdallocate( im, slc_clr );
			}
		else
			{
			SliceColor[i]     = PlotColor;
			if( threeD )
			 SliceColorShd[i] = clrshdallocate( im, GDCPIE_PlotColor );
			}

	pscl = (2.0*M_PI)/tot_val;
	
	/* ----- calc: smallest a slice can be ----- */
	/* 1/2 circum / num slices per side. */
	/*              determined by number of labels that'll fit (height) */
	/* scale to user values */
	/* ( M_PI / (IMGHEIGHT / (SFONTHGT+1)) ) */
/*	min_grphable = tot_val / */
/*				   ( 2.0 * (float)IMGHEIGHT / (float)(SFONTHGT+1+TFONTHGT+2) ); */


	if( threeD )
		{
		/* draw background shaded pie */
		{
		float	rad1 = rad * 3.0/4.0;
		for( i=0; i<num_points; ++i )
			if( !(others[i]) &&
				(!GDCPIE_missing || !GDCPIE_missing[i]) )
				{
				int		edge_color = GDCPIE_EdgeColor == GDC_NOCOLOR? SliceColorShd[i]:
				                                                      EdgeColorShd;

				gdImageLine( im, CX(i,1), CY(i,1), IX(i,1,1), IY(i,1,1), edge_color );
				gdImageLine( im, CX(i,1), CY(i,1), IX(i,2,1), IY(i,2,1), edge_color );
				gdImageArc( im, CX(i,1), CY(i,1),
								(int)(rad*ellipsex*2.0), (int)(rad*ellipsey*2.0),
								TO_INT_DEG_FLOOR(slice_angle[1][i])+270,
								TO_INT_DEG_CEIL(slice_angle[2][i])+270,
								edge_color );
					
/*				gdImageFilledArc( im, CX(i,1), CY(i,1), */
/*									  rad*ellipsex*2, rad*ellipsey*2, */
/*									  TO_INT_DEG_FLOOR(slice_angle[1][i])+270, */
/*									  TO_INT_DEG_CEIL(slice_angle[2][i])+270, */
/*									  SliceColorShd[i], */
/*									  gdPie ); */
				/* attempt to fill, if slice is wide enough */
				if( (ABS(IX(i,1,1)-IX(i,2,1)) + ABS(IY(i,1,1)-IY(i,2,1))) > 2 )
					{
					float	rad = rad1;										/* local override */
					gdImageFillToBorder( im, IX(i,0,1), IY(i,0,1), edge_color, SliceColorShd[i] );
					}
				}
		}
		/* fill in connection to foreground pie */
		/* this is where we earn our keep */
		{
		int					t,
							num_slice_angles = 0;
		CREATE_ARRAY1( tmp_slice, struct tmp_slice_t, 4*num_points+4 );		/* should only need 2*num_points+2 */

		for( i=0; i<num_points; ++i )
			if( !GDCPIE_missing || !GDCPIE_missing[i] )
				{
				if( RAD_DIST1(slice_angle[1][i]) < RAD_DIST2(slice_angle[0][i]) )
					tmp_slice[num_slice_angles].hidden = FALSE;
				else
					tmp_slice[num_slice_angles].hidden = TRUE;
				tmp_slice[num_slice_angles].i       = i;
				tmp_slice[num_slice_angles].slice   = slice_angle[0][i];
				tmp_slice[num_slice_angles++].angle = slice_angle[1][i];
				if( RAD_DIST1(slice_angle[2][i]) < RAD_DIST2(slice_angle[0][i]) )
					tmp_slice[num_slice_angles].hidden = FALSE;
				else
					tmp_slice[num_slice_angles].hidden = TRUE;
				tmp_slice[num_slice_angles].i       = i;
				tmp_slice[num_slice_angles].slice   = slice_angle[0][i];
				tmp_slice[num_slice_angles++].angle = slice_angle[2][i];
				/* identify which 2 slices (i) have a tangent parallel to depth angle  */
				if( slice_angle[1][i]<MOD_2PI(pie_3D_rad+M_PI_2) && slice_angle[2][i]>MOD_2PI(pie_3D_rad+M_PI_2) )
					{
					tmp_slice[num_slice_angles].i       = i;
					tmp_slice[num_slice_angles].hidden  = FALSE;
					tmp_slice[num_slice_angles].slice   = slice_angle[0][i];
					tmp_slice[num_slice_angles++].angle = MOD_2PI( pie_3D_rad+M_PI_2 );
					}
				if( slice_angle[1][i]<MOD_2PI(pie_3D_rad+3.0*M_PI_2) && slice_angle[2][i]>MOD_2PI(pie_3D_rad+3.0*M_PI_2) )
					{
					tmp_slice[num_slice_angles].i       = i;
					tmp_slice[num_slice_angles].hidden  = FALSE;
					tmp_slice[num_slice_angles].slice   = slice_angle[0][i];
					tmp_slice[num_slice_angles++].angle = MOD_2PI( pie_3D_rad+3.0*M_PI_2 );
					}
				}

		qsort( tmp_slice, num_slice_angles, sizeof(struct tmp_slice_t), ocmpr );
		for( t=0; t<num_slice_angles; ++t )
			{
			gdPoint	gdp[4];

			i = tmp_slice[t].i;

			gdp[0].x  = CX(i,0);					gdp[0].y = CY(i,0);
			gdp[1].x  = CX(i,1);					gdp[1].y = CY(i,1);
			gdp[2].x  = OX(i,tmp_slice[t].angle,1);	gdp[2].y = OY(i,tmp_slice[t].angle,1);
			gdp[3].x  = OX(i,tmp_slice[t].angle,0);	gdp[3].y = OY(i,tmp_slice[t].angle,0);

			if( !(tmp_slice[t].hidden) )
				gdImageFilledPolygon( im, gdp, 4, SliceColorShd[i] );
			else
				{
				rad -= 2.0;										/* no peeking */
				gdp[0].x  = OX(i,slice_angle[0][i],0);	gdp[0].y = OY(i,slice_angle[0][i],0);
				gdp[1].x  = OX(i,slice_angle[0][i],1);	gdp[1].y = OY(i,slice_angle[0][i],1);
				rad += 2.0;
				gdp[2].x  = OX(i,slice_angle[1][i],1);	gdp[2].y = OY(i,slice_angle[1][i],1);
				gdp[3].x  = OX(i,slice_angle[1][i],0);	gdp[3].y = OY(i,slice_angle[1][i],0);
				gdImageFilledPolygon( im, gdp, 4, SliceColorShd[i] );
				gdp[2].x  = OX(i,slice_angle[2][i],1);	gdp[2].y = OY(i,slice_angle[2][i],1);
				gdp[3].x  = OX(i,slice_angle[2][i],0);	gdp[3].y = OY(i,slice_angle[2][i],0);
				gdImageFilledPolygon( im, gdp, 4, SliceColorShd[i] );
				}
				

			if( GDCPIE_EdgeColor != GDC_NOCOLOR )
				{
				gdImageLine( im, CX(i,0), CY(i,0), CX(i,1), CY(i,1), EdgeColorShd );
				gdImageLine( im, OX(i,tmp_slice[t].angle,0), OY(i,tmp_slice[t].angle,0),
								 OX(i,tmp_slice[t].angle,1), OY(i,tmp_slice[t].angle,1),
								 EdgeColorShd );
				}
			}
		FREE_ARRAY1( tmp_slice );
		}
		}


	/* ----- pie face ----- */
	{
	/* float	last = 0.0; */
	float	rad1 = rad * 3.0/4.0;
	for( i=0; i<num_points; ++i )
		if( !others[i] &&
			(!GDCPIE_missing || !GDCPIE_missing[i]) )
			{
			int		edge_color = GDCPIE_EdgeColor == GDC_NOCOLOR? SliceColor[i]:
																  EdgeColorShd;
			/* last += val[i]; */
			/* EXPLODE_CX_CY( slice_angle[0][i], i ); */
			gdImageLine( im, CX(i,0), CY(i,0), IX(i,1,0), IY(i,1,0), edge_color );
			gdImageLine( im, CX(i,0), CY(i,0), IX(i,2,0), IY(i,2,0), edge_color );
			gdImageArc( im, CX(i,0), CY(i,0), 
							(int)(rad*ellipsex*2.0), (int)(rad*ellipsey*2.0),
							(TO_INT_DEG_FLOOR(slice_angle[1][i])+270)%360,
							(TO_INT_DEG_CEIL(slice_angle[2][i])+270)%360,
							edge_color );
			/* antialiasing here */
			/* likely only on the face? */
/* bugs in gd2.0.0 */
/*	arc doesn't honor deg>360 */
/*	arcs from gdImageFilledArc() don't match with gdImageArc() */
/*	angles are off */
/*	doesn't always fill completely */
/*			gdImageFilledArc( im, CX(i,0), CY(i,0),  */
/*								  (int)(rad*ellipsex*2.0), (int)(rad*ellipsey*2.0), */
/*								  (TO_INT_DEG_FLOOR(slice_angle[1][i])+270)%360, */
/*								  (TO_INT_DEG_CEIL(slice_angle[2][i])+270)%360, */
/*								  SliceColor[i], */
/*								  gdPie ); */
			/* attempt to fill, if slice is wide enough */
			{
			float	rad = rad1;										/* local override */
			if( (ABS(IX(i,1,1)-IX(i,2,1)) + ABS(IY(i,1,1)-IY(i,2,1))) > 2 )
				{
				gdImageFillToBorder( im, IX(i,0,0), IY(i,0,0), edge_color, SliceColor[i] );
				}
			/* catch missed pixels on narrow slices */
			gdImageLine( im, CX(i,0), CY(i,0), IX(i,0,0), IY(i,0,0), SliceColor[i] );
			}
			}
	}

	if( GDCPIE_title )
		{
		struct fnt_sz_t	tftsz      = GDCfnt_sz( GDCPIE_title,
												GDCPIE_title_size,
												gdcpie_title_font, gdcpie_title_ptsize, 0.0, NULL );
		GDCImageStringNL( im,
						  &GDC_fontc[GDCPIE_title_size],
						  gdcpie_title_font, gdcpie_title_ptsize,
						  0.0,
						  IMGWIDTH/2 - tftsz.w/2,
						  1,
						  GDCPIE_title,
						  LineColor,
						  GDC_JUSTIFY_CENTER,
						  NULL );
		}

	/* labels */
	if( lbl )
		{
		float	liner = rad;

		rad += GDCPIE_label_dist;
		for( i=0; i<num_points; ++i )
			{
			if( !others[i] &&
				(!GDCPIE_missing || !GDCPIE_missing[i]) )
				{
				int		lblx,  pctx,
						lbly,  pcty,
						linex, liney;

				lbly = (liney = IY(i,0,0))-lbl_ftsz[i].h / 2;
				lblx = pctx = linex = IX(i,0,0);

				if( slice_angle[0][i] > M_PI )								/* which semicircle */
					{
					lblx -= lbl_ftsz[i].w;
					pctx = lblx;
					++linex;
					}
				else
					--linex;

				switch( GDCPIE_percent_labels )
					{
					case GDCPIE_PCT_LEFT:	if( slice_angle[0][i] > M_PI )
												pctx -= lbl_ftsz[i].w-1;
											else
												lblx += pct_ftsz[i].w+1;
											pcty = IY(i,0,0) - ( 1+pct_ftsz[i].h ) / 2;
											break;
					case GDCPIE_PCT_RIGHT:	if( slice_angle[0][i] > M_PI )
												lblx -= pct_ftsz[i].w-1;
											else
												pctx += lbl_ftsz[i].w+1;
											pcty = IY(i,0,0) - ( 1+pct_ftsz[i].h ) / 2;
											break;
					case GDCPIE_PCT_ABOVE:	lbly += (1+pct_ftsz[i].h) / 2;
											pcty = lbly - pct_ftsz[i].h;
											break;
					case GDCPIE_PCT_BELOW:	lbly -= (1+pct_ftsz[i].h) / 2;
											pcty = lbly + lbl_ftsz[i].h;
											break;
					case GDCPIE_PCT_NONE:
					default:;
					}

				if( GDCPIE_percent_labels != GDCPIE_PCT_NONE )
					GDCImageStringNL( im,
									  &GDC_fontc[GDCPIE_label_size],
									  gdcpie_label_font, gdcpie_label_ptsize,
									  0.0,
									  slice_angle[0][i] <= M_PI? pctx:
																 pctx+lbl_ftsz[i].w-pct_ftsz[i].w,
									  pcty,
									  pct_lbl[i],
									  LineColor,
									  GDC_JUSTIFY_CENTER,
									  NULL );
				if( lbl[i] )
					GDCImageStringNL( im,
									  &GDC_fontc[GDCPIE_label_size],
									  gdcpie_label_font, gdcpie_label_ptsize,
									  0.0,
									  lblx,
									  lbly,
									  lbl[i],
									  LineColor,
									  slice_angle[0][i] <= M_PI? GDC_JUSTIFY_LEFT:
																 GDC_JUSTIFY_RIGHT,
									  NULL );
				if( GDCPIE_label_line )
					{
					float	rad = liner;
					gdImageLine( im, linex, liney, IX(i,0,0), IY(i,0,0), LineColor );
					}
				}
			}
		rad -= GDCPIE_label_dist;
		}

		fflush( img_fptr );
		switch( GDC_image_type )
			{
#ifdef HAVE_JPEG
			case GDC_JPEG:	gdImageJpeg( im, img_fptr, GDC_jpeg_quality );	break;
#endif
			case GDC_WBMP:	gdImageWBMP( im, PlotColor, img_fptr );			break;
			case GDC_GIF:	gdImageGif( im, img_fptr);						break;
			case GDC_PNG:
			default:		gdImagePng( im, img_fptr );
			}

	FREE_ARRAY1( lbl_ftsz );
	FREE_ARRAY1( pct_ftsz );
	FREE_ARRAY2( pct_lbl );

	FREE_ARRAY2( slice_angle );
	FREE_ARRAY1( others );

	FREE_ARRAY1( SliceColorShd );
	FREE_ARRAY1( SliceColor );
	gdImageDestroy(im);
	return;
}
int main()
{
	gdImagePtr im;
	int error = 0;
	int c, c1, c2, c3, c4, color, i;

	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;
}
Exemple #21
0
int main(void)
{
	/* Input and output files */
	FILE *in;
	FILE *out;

	/* Input and output images */
	gdImagePtr im_in, im_out;

	/* Brush image */
	gdImagePtr brush;

	/* Color indexes */
	int white;
	int blue;
	int red;
	int green;

	/* Points for polygon */
	gdPoint points[3];

	/* Create output image, 128 by 128 pixels. */
	im_out = gdImageCreate(128, 128);

	/* First color allocated is background. */
	white = gdImageColorAllocate(im_out, 255, 255, 255);

	/* Set transparent color. */
	gdImageColorTransparent(im_out, white);

	/* Try to load demoin.png and paste part of it into the
		output image. */

	in = fopen("demoin.png", "rb");
	if (!in) {
		fprintf(stderr, "Can't load source image; this demo\n");
		fprintf(stderr, "is much more impressive if demoin.png\n");
		fprintf(stderr, "is available.\n");
		im_in = 0;
	} else {
		im_in = gdImageCreateFromPng(in);
		fclose(in);
		/* Now copy, and magnify as we do so */
		gdImageCopyResized(im_out, im_in, 
			16, 16, 0, 0, 96, 96, 127, 127);		
	}
	red = gdImageColorAllocate(im_out, 255, 0, 0);
	green = gdImageColorAllocate(im_out, 0, 255, 0);
	blue = gdImageColorAllocate(im_out, 0, 0, 255);
	/* Rectangle */
	gdImageLine(im_out, 8, 8, 120, 8, green);	
	gdImageLine(im_out, 120, 8, 120, 120, green);	
	gdImageLine(im_out, 120, 120, 8, 120, green);	
	gdImageLine(im_out, 8, 120, 8, 8, green);	
	/* Circle */
	gdImageArc(im_out, 64, 64, 30, 10, 0, 360, blue);
	/* Arc */
	gdImageArc(im_out, 64, 64, 20, 20, 45, 135, blue);
	/* Flood fill */
	gdImageFill(im_out, 4, 4, blue);
	/* Polygon */
	points[0].x = 32;
	points[0].y = 0;
	points[1].x = 0;
	points[1].y = 64;	
	points[2].x = 64;
	points[2].y = 64;	
	gdImageFilledPolygon(im_out, points, 3, green);
	/* Brush. A fairly wild example also involving a line style! */
	if (im_in) {
		int style[8];
		brush = gdImageCreate(8, 8);
		gdImageCopyResized(brush, im_in,
			0, 0, 0, 0, 
			gdImageSX(brush), gdImageSY(brush),
			gdImageSX(im_in), gdImageSY(im_in));
		gdImageSetBrush(im_out, brush);	
		/* With a style, so they won't overprint each other.
			Normally, they would, yielding a fat-brush effect. */
		style[0] = 0;
		style[1] = 0;
		style[2] = 0;
		style[3] = 0;
		style[4] = 0;
		style[5] = 0;
		style[6] = 0;
		style[7] = 1;
		gdImageSetStyle(im_out, style, 8);
		/* Draw the styled, brushed line */
		gdImageLine(im_out, 0, 127, 127, 0, gdStyledBrushed);
	}
	/* Text */
	gdImageString(im_out, gdFontGiant, 16, 16, 
		(unsigned char *) "hi", red);
	gdImageStringUp(im_out, gdFontSmall, 32, 32, 
		(unsigned char *) "hi", red);
	/* Make output image interlaced (allows "fade in" in some viewers,
		and in the latest web browsers) */
	gdImageInterlace(im_out, 1);
	out = fopen("demoout.png", "wb");
	/* Write PNG */
	gdImagePng(im_out, out);
	fclose(out);
	gdImageDestroy(im_out);
	if (im_in) {
		gdImageDestroy(im_in);
	}
	return 0;
}
Exemple #22
0
void gifstr_ (
#endif
	      int *x, int *nx, int *ny,
	      int *sx, int *sy,
	      int *nc, int *r, int *g, int *b,
	      int *or, char *fn, int n) {
  gdImagePtr im;
  gdFontPtr  ft;
  int        i,j,c;
  int        xs, ys;
  int        *ct;
  char       *f;

  if (*nx < 300) {
    ft = gdFontTiny;
  } else if (*nx < 600) {
    ft = gdFontSmall;
  } else if (*nx < 900) {
    ft = gdFontMediumBold;
  } else if (*nx < 1200) {
    ft = gdFontLarge;
  } else {
    ft = gdFontGiant;
  }

  /* chop off last character from file name */

  f = (char *)chopst(fn,n);
  
  /* create a new image with appropriate dimensions */

  im = gdImageCreate(*nx, *ny);

  /* allocate color table */

  ct = (int *)malloc(*nc*sizeof(int));
  for (i = 0; i < *nc; i++) {
    ct[i] = gdImageColorAllocate(im, r[i], g[i], b[i]);
  }

  /* set pixel colors in image */

  for (i = 0; i < *nx; i++) {
    for (j = 0; j < *ny; j++) {
      c = x[i + j * *nx];
      gdImageSetPixel(im, i, j, ct[c]);
    }
  }

  ys = *sy - ft->h / 2;
  if (*or < 0) {
    xs = *sx - ((strlen(f) + 1) * ft->w);
  } else if (*or > 0) {
    xs = *sx + ft->w;
  } else {
    xs = *sx - (strlen(f) * ft->w / 2);
  }

  gdImageString(im, ft,	xs, ys,	f, ct[0]);

  for (i = 0; i < *nx; i++) {
    for (j = 0; j < *ny; j++) {
      x[i + j * *nx] = gdImageGetPixel(im, i, j);
    }
  }

  /* destroy image */

  gdImageDestroy(im);
}
Exemple #23
0
void doCreate(FILE *stream) {
  int x, y;
  x = getNumber(stream);
  y = getNumber(stream);
  image = gdImageCreate(x, y);
}
Exemple #24
0
BGD_DECLARE(gdImagePtr) gdImageCreateFromXpm (char *filename)
{
  XpmInfo info;
  XpmImage image;
  int i, j, k, number;
  char buf[5];
  gdImagePtr im = 0;
  int *pointer;
  int red = 0, green = 0, blue = 0;
  int *colors;
  int ret;

  ret = XpmReadFileToXpmImage (filename, &image, &info);
  if (ret != XpmSuccess)
    return 0;

  if (!(im = gdImageCreate (image.width, image.height)))
    return 0;

  number = image.ncolors;
  colors = (int *) gdMalloc (sizeof (int) * number);
  if (colors == NULL)
    return (0);
  for (i = 0; i < number; i++)
    {
      switch (strlen (image.colorTable[i].c_color))
	{
	case 4:
	  buf[1] = '\0';
	  buf[0] = image.colorTable[i].c_color[1];
	  red = strtol (buf, NULL, 16);

	  buf[0] = image.colorTable[i].c_color[3];
	  green = strtol (buf, NULL, 16);

	  buf[0] = image.colorTable[i].c_color[5];
	  blue = strtol (buf, NULL, 16);
	  break;
	case 7:
	  buf[2] = '\0';
	  buf[0] = image.colorTable[i].c_color[1];
	  buf[1] = image.colorTable[i].c_color[2];
	  red = strtol (buf, NULL, 16);

	  buf[0] = image.colorTable[i].c_color[3];
	  buf[1] = image.colorTable[i].c_color[4];
	  green = strtol (buf, NULL, 16);

	  buf[0] = image.colorTable[i].c_color[5];
	  buf[1] = image.colorTable[i].c_color[6];
	  blue = strtol (buf, NULL, 16);
	  break;
	case 10:
	  buf[3] = '\0';
	  buf[0] = image.colorTable[i].c_color[1];
	  buf[1] = image.colorTable[i].c_color[2];
	  buf[2] = image.colorTable[i].c_color[3];
	  red = strtol (buf, NULL, 16);
	  red /= 64;

	  buf[0] = image.colorTable[i].c_color[4];
	  buf[1] = image.colorTable[i].c_color[5];
	  buf[2] = image.colorTable[i].c_color[6];
	  green = strtol (buf, NULL, 16);
	  green /= 64;

	  buf[0] = image.colorTable[i].c_color[7];
	  buf[1] = image.colorTable[i].c_color[8];
	  buf[2] = image.colorTable[i].c_color[9];
	  blue = strtol (buf, NULL, 16);
	  blue /= 64;
	  break;
	case 13:
	  buf[4] = '\0';
	  buf[0] = image.colorTable[i].c_color[1];
	  buf[1] = image.colorTable[i].c_color[2];
	  buf[2] = image.colorTable[i].c_color[3];
	  buf[3] = image.colorTable[i].c_color[4];
	  red = strtol (buf, NULL, 16);
	  red /= 256;

	  buf[0] = image.colorTable[i].c_color[5];
	  buf[1] = image.colorTable[i].c_color[6];
	  buf[2] = image.colorTable[i].c_color[7];
	  buf[3] = image.colorTable[i].c_color[8];
	  green = strtol (buf, NULL, 16);
	  green /= 256;

	  buf[0] = image.colorTable[i].c_color[9];
	  buf[1] = image.colorTable[i].c_color[10];
	  buf[2] = image.colorTable[i].c_color[11];
	  buf[3] = image.colorTable[i].c_color[12];
	  blue = strtol (buf, NULL, 16);
	  blue /= 256;
	  break;
	}


      colors[i] = gdImageColorResolve (im, red, green, blue);
      if (colors[i] == -1)
	fprintf (stderr, "ARRRGH\n");
    }

  pointer = (int *) image.data;
  for (i = 0; i < image.height; i++)
    {
      for (j = 0; j < image.width; j++)
	{
	  k = *pointer++;
	  gdImageSetPixel (im, j, i, colors[k]);
	}
    }
  gdFree (colors);
  return (im);
}
Exemple #25
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;
}
Exemple #26
0
void write_gif(universe *u, int gen, const char *filename) {

        FILE *out = fopen(filename, "wb");
        gdImagePtr im;

        int l, r, t, b;

        generation *g = universe_find_generation(u, gen, 0);
        generation_find_bounds(g, &l, &r, &t, &b);

        int scale = 4;

        im = gdImageCreate((r - l) * scale, (b - t) * scale);

        int background = gdImageColorAllocate(im, 230, 230, 255);
        gdImageRectangle(im, 0, 0, (r-l) * scale, (b-t) * scale, background);

        int tile_bg = gdImageColorAllocate(im, 255, 255, 255);
        int tile_frame = gdImageColorAllocate(im, 230, 230, 230);

        int on = gdImageColorAllocate(im, 0, 0, 0);
        int unknown = gdImageColorAllocate(im, 255, 255, 0);
        int unknown_stable = gdImageColorAllocate(im, 192, 255, 0);

        tile *tp;
        for(tp = g->all_first; tp; tp = tp->all_next) {
                if(!(tp->flags & (IS_LIVE | HAS_UNKNOWN_CELLS))) {
                        continue;
                }

                gdImageFilledRectangle(im, GX(tp->xpos), GY(tp->ypos),
                                       GX(tp->xpos + TILE_WIDTH)-1, 
                                       GY(tp->ypos + TILE_HEIGHT)-1,
                                       tile_bg);

                gdImageRectangle(im, GX(tp->xpos), GY(tp->ypos),
                                 GX(tp->xpos + TILE_WIDTH)-1, 
                                 GY(tp->ypos + TILE_HEIGHT)-1,
                                 tile_frame);
                int xx, yy;
                for(xx = 0; xx < TILE_WIDTH; xx++) {
                        for(yy = 0; yy < TILE_HEIGHT; yy++) {
                                cellvalue cv = tile_get_cell(tp, xx, yy);
                                if(cv == ON) {
                                        gdImageFilledRectangle(im, 
                                                               GX(tp->xpos + xx),
                                                               GY(tp->ypos + yy),
                                                               GX(tp->xpos + xx + 1) - 1,
                                                               GY(tp->ypos + yy + 1) - 1,
                                                               on);
                                } else if(cv == UNKNOWN) {
                                        gdImageFilledRectangle(im, 
                                                               GX(tp->xpos + xx),
                                                               GY(tp->ypos + yy),
                                                               GX(tp->xpos + xx + 1) - 1,
                                                               GY(tp->ypos + yy + 1) - 1,
                                                               unknown);
                                } else if(cv == UNKNOWN_STABLE) {
                                        gdImageFilledRectangle(im, 
                                                               GX(tp->xpos + xx),
                                                               GY(tp->ypos + yy),
                                                               GX(tp->xpos + xx + 1) - 1,
                                                               GY(tp->ypos + yy + 1) - 1,
                                                               unknown_stable);
                                } 
                        }
                }
        }

        gdImageGif(im, out);
        fclose(out);
        gdImageDestroy(im);
}
Exemple #27
0
bool wfg_generateImage(char* audioFileName, char* pictureFileName, WFGO* options)
{	
	int width = options->width;
	int height = options->height;
	int seconds;
	long framesPerLine;

	// Initial audio part
	
	SF_INFO sfinfo;
	memset(&sfinfo, 0, sizeof(sfinfo));
	
	SNDFILE *sfile;
	if(audioFileName != NULL) {
		sfile =  sf_open(audioFileName, SFM_READ, &sfinfo);
	} else {
		sfile = sf_open_fd(STDIN_FILENO, SFM_READ, &sfinfo, 0);
	}
	
	if(sfile == NULL)
	{
		lastErrorMessage = "Could not open input file!";
		return false;
	}
	
	if(audioFileName == NULL) {
		seconds = options->trackLength;
		framesPerLine = ((long) seconds * sfinfo.samplerate) / width;
	} else {
		seconds = sfinfo.frames / sfinfo.samplerate;
		framesPerLine = (long) sfinfo.frames / width;
	}
	long samplesPerLine = framesPerLine * sfinfo.channels;
	
	// although one could think, that these values are flexible, the loops
	// below only work in these configurations (1/all or all/1)
	
	int channelsPerDrawing = 1;
	int drawnChannels = sfinfo.channels;
	
	if(options->mixChannels)
	{
		channelsPerDrawing = sfinfo.channels;
		drawnChannels = 1;
	}
		
	float * buffer = malloc(sizeof(float) * samplesPerLine);
	
	// malloc fail
	if(buffer == NULL)
	{
		lastErrorMessage = "Could not allocate memory!";
		sf_close(sfile);
		return false;
	}
	
	// Allocate Image
	gdImagePtr im = gdImageCreate(width,height);
	
	if(im == NULL)
	{
		lastErrorMessage = "Could not allocate image!";
		free(buffer);
		sf_close(sfile);
		return false;
	}
	
	// calculate how large one drawing should be
	
	int drawHeight = height;
	
	// leave space for the timeline
	if(options->drawTimeline)
		drawHeight -= 13;
	
	// subtract spacing
	drawHeight = drawHeight - ((drawnChannels - 1) * options->channelSpacing);
	
	// divide by drawnChannels
	drawHeight = drawHeight / drawnChannels;
	
	// background color
	int bgColor = gdImageColorAllocate(im,WFG_UNPACK_RGB(options->bgColor));
	
	if(options->transparentBg) {
		gdImageColorTransparent(im,bgColor);
	}
	
	int rmsColor =  gdImageColorAllocate(im, WFG_UNPACK_RGB(options->rmsColor));
	int peakColor = gdImageColorAllocate(im, WFG_UNPACK_RGB(options->peakColor));
	
	// too many nested loops ...
	for(int i = 0; i < width; i++)
	{
		if(sf_read_float(sfile, buffer, samplesPerLine) != samplesPerLine)
		{
			if(audioFileName == NULL) {
				memset(buffer, 0, samplesPerLine);
			} else {
				lastErrorMessage = "Could not read samples from audio file!";
				sf_close(sfile);
				free(buffer);
				gdImageDestroy(im);
				return false;
			}
		}
		
		int drawOffset = 0;

		for(int d = 0; d < drawnChannels; d++)
		{
			double val = 0.0;
			
			float peakP = 0.0;
			float peakM = 0.0;
			
			for(long e = 0; e < framesPerLine; e++)
			{
				for(int f = 0; f < channelsPerDrawing; f++)
				{
					float smpl = buffer[e * drawnChannels + d];
					val = val + (smpl*smpl);
					
					if(peakM > smpl)
						peakM = smpl;
					
					if(peakP < smpl)
						peakP = smpl;
				}
			}
			
			val = val / (float) (framesPerLine * channelsPerDrawing);
			val = sqrt(val);
			
			double ddrawHeight = drawHeight;
			
			int peakPP = drawHeight/2 -  round(peakP * (ddrawHeight/2.0));
			int peakMP = drawHeight/2 +  round(peakM * -1.0 * (ddrawHeight/2.0));
					
			// avoid rounding errors when peak is very small
			// if(peakP > 0.001 || peakM < -0.001) 
			gdImageLine(im, i,peakPP + drawOffset,i,peakMP + drawOffset, peakColor);
			
			int rmsSize;
			rmsSize = val * (double) (drawHeight/2);
			gdImageLine(im, i,drawHeight/2 - rmsSize + drawOffset,i,drawHeight/2 + rmsSize + drawOffset, rmsColor);
			
			drawOffset += drawHeight + options->channelSpacing;
		}
	}

	
	sf_close(sfile);
	free(buffer);
	
	if(options->drawTimeline)
		drawTimeline(im, options, seconds);
	
	// write out file
	FILE* file;
	if(pictureFileName) {
		file = fopen(pictureFileName,"wb");
	} else {
		file = stdout;
	}
	if(file == NULL)
	{
		lastErrorMessage = "Could not open output file!";
		gdImageDestroy(im);
	}
	
	gdImagePng(im,file);
	
	fclose(file);
	gdImageDestroy(im);
	
	return true;
}
Exemple #28
0
void write_animated_gif(universe *u, const char *filename) {

        FILE *out = fopen(filename, "wb");
        gdImagePtr im;

        int l, r, t, b;
        int ll, rr, tt, bb;

        generation *g = u->first;
        generation_find_bounds(g, &l, &r, &t, &b);

        for(g = g->next; g; g = g->next) {
                generation_find_bounds(g, &ll, &rr, &tt, &bb);
                if(ll < l) l = ll;
                if(rr > r) r = rr;
                if(tt < t) t = tt;
                if(bb > b) b = bb;
        }

        int scale = 4;
	int delay = 10;

        im = gdImageCreate((r - l) * scale, (b - t) * scale);

        int background = gdImageColorAllocate(im, 230, 230, 255);
        gdImageRectangle(im, 0, 0, (r-l) * scale, (b-t) * scale, background);

        int tile_bg = gdImageColorAllocate(im, 255, 255, 255);
        int tile_frame = gdImageColorAllocate(im, 230, 230, 230);

        int on = gdImageColorAllocate(im, 0, 0, 0);
        int unknown = gdImageColorAllocate(im, 255, 255, 0);
        int unknown_stable = gdImageColorAllocate(im, 192, 255, 0);

	gdImageGifAnimBegin(im, out, 1, 0);

        for(g = u->first; g; g = g->next) {
                tile *tp;
                for(tp = g->all_first; tp; tp = tp->all_next) {
                        if(!(tp->flags & IS_LIVE)) {
                                continue;
                        }

                        gdImageFilledRectangle(im, GX(tp->xpos), GY(tp->ypos),
                                               GX(tp->xpos + TILE_WIDTH)-1, 
                                               GY(tp->ypos + TILE_HEIGHT)-1,
                                               tile_bg);

                        gdImageRectangle(im, GX(tp->xpos), GY(tp->ypos),
                                         GX(tp->xpos + TILE_WIDTH)-1, 
                                         GY(tp->ypos + TILE_HEIGHT)-1,
                                         tile_frame);
                        int xx, yy;
                        for(xx = 0; xx < TILE_WIDTH; xx++) {
                                for(yy = 0; yy < TILE_HEIGHT; yy++) {
                                        cellvalue cv = tile_get_cell(tp, xx, yy);
                                        int colour = -1;
                                        if(cv == ON) {
                                                colour = on;
                                        } else if(cv == UNKNOWN) {
                                                colour = unknown;
                                        } else if(cv == UNKNOWN_STABLE) {
                                                colour = unknown_stable;
                                        } 
                                        if(colour >= 0)
                                                gdImageFilledRectangle(im, 
                                                                       GX(tp->xpos + xx),
                                                                       GY(tp->ypos + yy),
                                                                       GX(tp->xpos + xx + 1) - 1,
                                                                       GY(tp->ypos + yy + 1) - 1,
                                                                       colour);
                                }
                        }
                }
		gdImageGifAnimAdd(im, out, 0, 0, 0,
				  delay, gdDisposalNone, NULL);
        }

	gdImageGifAnimEnd(out);

        fclose(out);
        gdImageDestroy(im);
}
int main(int argc, char const *argv[]) {
  gdImagePtr im;
  FILE *pFichero, *pngOut;
  int salida;
  char ruta[] = "/home/marcos/WRF_PRD/gshhg_data/wdb_rivers_l.b";
  struct GSHHG_HEADER h;
  struct GSHHG_POINT p;
  double w, e, s, n;
  double x, y;
  int i, k, resx, resy, black, white;

  resx = 400;
  resy = 400;
  im = gdImageCreate( resx, resy );
  white = gdImageColorAllocate( im, 255, 255, 255 );
  black = gdImageColorAllocate( im, 0, 0, 0 );

  pFichero = fopen( ruta, "rb" );
  if ( pFichero == NULL )
  {
    perror( "*** ERROR ***" );
    return -1;
  }
  else
  {
    printf( "Fichero abierto correctamente.\n" );
  }

  for ( k = 0; k < 10000; k++) {
  if ( fread( &h, sizeof( h ), 1, pFichero ) != 1 )
  {
    printf( "No se ha podido leer correctamente el encabezado del polígono\n" );
  }
  h.id = swabi4( h.id );
  h.n = swabi4( h.n );
  h.west = swabi4( h.west );
  h.east = swabi4( h.east );
  h.south = swabi4( h.south );
  h.north = swabi4( h.north );
  w = (double) h.west * GSHHG_SCL;
  e = (double) h.east * GSHHG_SCL;
  s = (double) h.north * GSHHG_SCL;
  n = (double) h.south * GSHHG_SCL;
  printf( "id=%i n=%i\n", h.id, h.n );
  printf( "w=%f e=%f s=%f n=%f\n", w, e, s, n );

  h.flag = swabi4( h.flag );
  int level = h.flag & 255;
  int version = ( h.flag >> 8 ) & 255;
  int greenwich = ( h.flag >> 16) & 3;
  int source = ( h.flag >> 24) & 1;
  int river = ( h.flag >> 25) & 1;
  int elevado_a = h.flag >> 26;

  printf("level=%i\n", level);
  printf("version=%i\n", version);
  printf("greenwich=%i\n", greenwich);
  printf("source=%i\n", source);
  printf("river=%i\n", river);
  printf("elevado_a=%i\n", elevado_a);

for( i = 1; i <= h.n; i++){
  fread( &p, sizeof( p ), 1, pFichero );
  p.x = swabi4( p.x );
  p.y = swabi4( p.y );
  x = (double) p.x * GSHHG_SCL;
  y = (double) p.y * GSHHG_SCL;

  // printf("i=%i x=%f y=%f\n", i, x, y );
  if ( x > 300 )
  {
    x = x - 310;
    gdImageSetPixel( im, (int)x, resy - (int)y - 100, black);
  }
  else
  {
    gdImageSetPixel( im, (int)x+50, resy - (int)y - 100, black);
  }
}
}
  fclose( pFichero );

  pngOut = fopen( "gshhg.png", "wb" );
  gdImagePng( im, pngOut );
  fclose( pngOut );
  gdImageDestroy( im );
  return 0;
}
Exemple #30
0
int main()
{
	gdImagePtr im;
	int black;
	int white;
	int brect[8];
	int x, y;
	char *err;

	char s[5];	/* String to draw. */
	double sz = 40.;
	char fontpath[256];
	unsigned int r;
	char buf[50];
	char userid[IDLEN + 1];
	struct MD5Context mdc;
	unsigned int pass[4];
	if (initbbsinfo(&bbsinfo) < 0)
		return -1;
	bzero(pass, sizeof(pass));
	strsncpy(buf, getsenv("QUERY_STRING"), sizeof (buf));
	__unhcode(buf);
	if (strncmp(buf, "userid=", 7)) {
		userid[0] = 0;
	} else {
		strsncpy(userid, buf+7, IDLEN+1);
	//	errlog("%s",userid);
	}
	if (userid[0] == 0) {
		s[0] = 0;
	} else {
		MD5Init(&mdc);
		MD5Update(&mdc, (void *)(&bbsinfo.ucachehashshm->regkey), sizeof(int) * 4);
		MD5Update(&mdc, userid, strlen(userid));
		MD5Final((char *)pass, &mdc);
		sprintf(s, "%d%d%d%d", pass[0]%10, pass[1] % 10, pass[2] % 10, pass[3] % 10);
	}
	getrandomint(&r);
	sprintf(fontpath, MY_BBS_HOME "/etc/fonts/%d.ttf", r % MAXFONTS);	/* User supplied font */

	fprintf(stdout, "Content-type: image/png\r\n\r\n");
/* obtain brect so that we can size the image */
	err = gdImageStringTTF(NULL, &brect[0], 0, fontpath, sz, 0., 0, 0, s);
	if (err) {
		return 1;
	}
/* create an image big enough for the string plus a little whitespace */
	x = brect[2] - brect[6] + 6;
	y = brect[3] - brect[7] + 6;
	im = gdImageCreate(x, y);

/* Background color (first allocated) */
	white = gdImageColorResolve(im, 255, 255, 255);
	black = gdImageColorResolve(im, 0, 0, 0);

/* render the string, offset origin to center string*/
/* note that we use top-left coordinate for adjustment
 * since gd origin is in top-left with y increasing downwards. */
	x = 3 - brect[6];
	y = 3 - brect[7];
	err = gdImageStringFT(im, &brect[0], black, fontpath, sz, 0.0, x, y, s);
	if (err) {
		return 1;
	}
/* Write img to stdout */
	gdImagePng(im, stdout);

/* Destroy it */
	gdImageDestroy(im);
	return 0;
}