【www.gdgbn.com--php与数据库】

图片的随机生成的原理,就是从数据库中随机读取记录,然后据其构造相应的图片,然后用二进制把其写入Response.OutputStream里。
数据库中随机读取的原理如下:
set rowcount 1 select * from [yourtable] order by newid()
如果你的表中的数据的ID是连续的,也可以用C#Random类的next()方法来生成一个随机的ID,从而获得相应的记录,如下:
"select * from [yourtable] where [pkid]="+(new Random()).Next(1,1000);
就可以了。
已经从数据库中读取出来相应记录了,现在就应该利用读出来的记录作为参数来生成相应的图片,因为这里只是一个示范,传读取的参数只是一个字符串,当然也可以做更为实用,比如设置图片的样式等。下面的这个方法返回一个bitmap对象:
public Bitmap GetImage(string s)
{
Bitmap b=new Bitmap(1,1);
int width,height;
Font aFont=new Font("Times New Roman",16,System.Drawing.GraphicsUnit.Point);
Graphics graphics=Graphics.FromImage(b);
width=(int)graphics.MeasureString(s,aFont).Width;
height=(int)graphics.MeasureString(s,aFont).Height;
b=new Bitmap(b,new Size(width,height));
graphics=Graphics.FromImage(b);
graphics.Clear(Color.Black);
graphics.TextRenderingHint=TextRenderingHint.AntiAlias;
graphics.DrawString(s,aFont,new SolidBrush(Color.Yellow),0,0);
graphics.Flush();
return(b);
}
现在获得一个bitmap对象,现在就是输出了,我们只要在相应的事件中加入输出代码就可以了,下面的例子是放在page_load方法里的,代码如下:
Response.ContentType="image/GIF"
b.Save(Response.OutputStream,System.Drawing .Imaging .ImageFormat .Gif);
// MemoryStream ms=new MemoryStream();
// b.Save(ms,System.Drawing .Imaging .ImageFormat .Gif);
// ms.Position=0;
// byte [] t=new byte[ms.Length];
// ms.Read(t,0,(int)ms.Length);;
// Response.BinaryWrite(t);
上面的代码给了两种输出方法,一个是直接把bitmap保存到Response的输出流中去,另一方法是先把bitmap保存到一个流中,然后把流中数据库再写到一个字节数组中,然后用Response的二进制输出方法直接写到输出流中,其实也可以把ms的内容直接写到输出流去,实现图片的输出。

本文来源:http://www.gdgbn.com/jiaocheng/7545/