Web Server程序编写学习笔记(三)getpng.c

来源:互联网 发布:淘宝达人管理中心 编辑:程序博客网 时间:2024/05/16 05:53

12月31日,12:44:58
终于完成了用C生成PNG格式图片的程序,总结下:
1.使用gd-1.8.4图像处理库中的函数,主要步骤为:
创建一变量存放空白图像-〉匹配图形的颜色-〉为图像填充以上颜色-〉创建PNG图像-〉破坏图像流以释放内存。
2.gd-1.8.4与1.8.3以前的函数有一些不同首先每个函数名前都加了gd两个字;其次gdImageString(),gdImageChar()等这个函数中参数变了,以前表示字体的参数是“int font“,其值为1-5,现在表示字体的参数变成了“gdFontPtr font“,gdFontPtr是一个指向gdFont结构的指针:
typedef struct {
 /* # of characters in font */
 int nchars;
 /* First character is numbered... (usually 32 = space) */
 int offset;
 /* Character width and height */
 int w;
 int h;
 /* Font data; array of characters, one row after another.
  Easily included in code, also easily loaded from
  data files. */
 char *data;
} gdFont;
/* Text functions take these. */
typedef gdFont *gdFontPtr;
这样一来使用gdImageString(),gdImageChar()等函数时这个表示字体的参数就不能使简单的写1-5了。
到底怎么办呢?我在这个问题上花了很久的时间。后来在一个老外的主页上看到他说一种字体nchars=256;offset=0;w=8;h=15;data[]={0,0,0,0,........0,0,0,};我就将这些值赋给一个gdFontPtr结构的变量,结果还是不行。不过受他的启发,我在gd.h同一目录下发现有几个文件,gdfontg.h,gdfontl.h等等,其实这些文件就是每个帮我们定义了一种字体,gdFontGiant,gdFontLarge,gdFontSmall等等。这样的话,在用gdImageString(),gdImageChar()等函数时这个表示字体的参数就可以写gdFontGiant,gdFontLarge,gdFontSmall。大概就相当于原来的数字吧。
************************************************************************************
^_^,呵呵,终于搞定了。下面的函数将任意字符串生成为绿底红字的png图片,并加入了一定的干扰线。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <gd.h>
#include <gdfontg.h>

int
getpng(char *string,int strlen)
{
int back,word,front,len,sx,sy,i;
char *str;
gdImagePtr newimg;
FILE *pngfp;

str=string;
len=strlen;
sx=10+len*9;
sy=20;
newimg=gdImageCreate(sx,sy); /* 创建一变量存放空白图像,像素sx*sy */
pngfp=fopen("mypng.png","wb");
back=gdImageColorAllocate(newimg,0,255,128); /* 匹配图形的颜色 */
word=gdImageColorAllocate(newimg,255,0,128); /* 匹配图形的颜色 */
front=gdImageColorAllocate(newimg,255,64,128);/* 匹配图形的颜色 */
gdImageFill(newimg,0,0,back);   /* 为图像填充以上颜色 */
gdImageString(newimg,gdFontGiant,5,1,str,word);/* 输出字符串图像 */
 for(i=0;i<len;(i=i+2))
  gdImageLine(newimg,(5+i*9),0,(23+i*9),20,front); /*产生一些干绕线 */
gdImagePng(newimg,pngfp);   /* 创建PNG图像 */
gdImageDestroy(newimg);    /* 破坏图像流以释放内存 */

close(pngfp);
return;
}
OK.GoodLuck all!!!

原创粉丝点击