using System.Drawing;using System.IO;using System.Drawing.Imaging;private void AddTextToImg(string fileName,string text){if(!File.Exists(MapPath(fileName))){throw new FileNotFoundException("The file don't exist!");}if( text == string.Empty ){return;}//還需要判斷文件類型是否為圖像類型,這里就不贅述了System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));Bitmap bitmap = new Bitmap(image,image.Width,image.Height);Graphics g = Graphics.FromImage(bitmap);float fontSize = 12.0f; //字體大小float textWidth = text.Length*fontSize; //文本的長度//下面定義一個矩形區(qū)域,以后在這個矩形里畫上白底黑字float rectX = 0; float rectY = 0;float rectWidth = text.Length*(fontSize+8);float rectHeight = fontSize+8;//聲明矩形域RectangleF textArea = new RectangleF(rectX,rectY,rectWidth,rectHeight);Font font = new Font("宋體",fontSize); //定義字體Brush whiteBrush = new SolidBrush(Color.White); //白筆刷,畫文字用Brush blackBrush = new SolidBrush(Color.Black); //黑筆刷,畫背景用g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight); g.DrawString(text,font,whiteBrush,textArea);MemoryStream ms = new MemoryStream( );//保存為Jpg類型bitmap.Save(ms,ImageFormat.Jpeg);//輸出處理后的圖像,這里為了演示方便,我將圖片顯示在頁面中了Response.Clear();Response.ContentType = "image/jpeg";Response.BinaryWrite( ms.ToArray() );g.Dispose();bitmap.Dispose();image.Dispose();}
調用時很簡單,
AddTextToImg("me.jpg","武林網http://www.companysz.com/");
一切OK了,感覺.net確實好強大,這些功能在Asp中可是奢侈品了,而在.Net環(huán)境中卻能輕而易舉的完成!
新聞熱點
疑難解答
圖片精選