引言
基于生成图片实现了一个手机号转图片的需求。 内容也很简单,直接用手机号生成一个png图片。就是为了背景透明以便其他地方调用。 有无锯齿主要依靠一句代码:g.TextRenderingHint= TextRenderingHint.AntiAlias;
生成图片
1、有锯齿
2、无锯齿
生成方法
string color = "#ff6633"; System.Drawing.Bitmap image = new System.Drawing.Bitmap(170, 35); Graphics g = Graphics.FromImage(image); try { g.TextRenderingHint= TextRenderingHint.AntiAlias; //消除锯齿 //生成随机生成器 Random random = new Random(); //清空图片背景色 //g.Clear(Color.Transparent); //画图片的背景噪音线 /*for (int i = 0; i < 2; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2); } */ System.Drawing.ColorConverter colConvert = new System.Drawing.ColorConverter(); Color fontColor =(System.Drawing.Color)colConvert.ConvertFromString(color); Font font = new System.Drawing.Font("Arial", 18, System.Drawing.FontStyle.Bold); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), fontColor, fontColor,LinearGradientMode.Horizontal); g.DrawString(phone, font, brush, 2, 2); //画图片的前景噪音点 //for (int i = 0; i < 50; i++) //{ // int x = random.Next(image.Width); // int y = random.Next(image.Height); // image.SetPixel(x, y, Color.FromArgb(random.Next())); //} //画图片的边框线 //g.DrawRectangle(new Pen(Color.White), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); Color backColor = image.GetPixel(1, 1); image.MakeTransparent(backColor); image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); context.Response.ClearContent(); context.Response.ContentType = "image/x-png"; context.Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); }