你試過(guò)用.net來(lái)進(jìn)行圖像處理嗎?公司最近進(jìn)行的一個(gè)項(xiàng)目,數(shù)據(jù)庫(kù)中存入了很多的產(chǎn)品圖片,可是都沒(méi)有版權(quán)信息,當(dāng)時(shí)客戶(hù)要求將所有的圖片打上公司名稱(chēng)?這時(shí)候,你該怎么辦?
雖說(shuō)我還是江湖嫩手,可是對(duì)這一問(wèn)題的解決方案還是很多,歸結(jié)如下:
1.使用圖形處理軟件,如photoshop等,利用其批處理功能,可以實(shí)現(xiàn)這個(gè)功能,可是每次數(shù)據(jù)錄入員加進(jìn)圖片的話(huà),還得加工一下圖片,很麻煩的,看錄入員大姐平常對(duì)我很不錯(cuò),每日笑臉相迎,能忍心折磨她么?這個(gè)方案否決了。
2.使用.net行云流水般的圖像處理,當(dāng)錄入員大姐上傳圖片的時(shí)候,就自動(dòng)加上公司標(biāo)記,這樣豈不更好,嗯,這想法不錯(cuò),可以進(jìn)入2005最佳解決方案第萬(wàn)強(qiáng)了,好說(shuō)干就干。
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;
}
//還需要判斷文件類(lèi)型是否為圖像類(lèi)型,這里就不贅述了
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; //文本的長(zhǎng)度
//下面定義一個(gè)矩形區(qū)域,以后在這個(gè)矩形里畫(huà)上白底黑字
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); //白筆刷,畫(huà)文字用
Brush blackBrush = new SolidBrush(Color.Black); //黑筆刷,畫(huà)背景用
g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight);
g.DrawString(text,font,whiteBrush,textArea);
MemoryStream ms = new MemoryStream( );
//保存為Jpg類(lèi)型
bitmap.Save(ms,ImageFormat.Jpeg);
//輸出處理后的圖像,這里為了演示方便,我將圖片顯示在頁(yè)面中了
Response.Clear();
Response.ContentType = "image/jpeg";
Response.BinaryWrite( ms.ToArray() );
g.Dispose();
bitmap.Dispose();
image.Dispose();
}
調(diào)用時(shí)很簡(jiǎn)單,
AddTextToImg("me.jpg","小智");
一切OK了,感覺(jué).net確實(shí)好強(qiáng)大,這些功能在asp中可是奢侈品了,而在.Net環(huán)境中卻能輕而易舉的完成!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注