Web Server程序編寫學習筆記(三)getpng.c

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!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章