本文來源于網(wǎng)頁設(shè)計(jì)愛好者web開發(fā)社區(qū)http://www.html.org.cn收集整理,歡迎訪問。給圖片添加版權(quán)信息(c#)
現(xiàn)在越來越多的網(wǎng)站都喜歡將用戶上傳的圖片加上網(wǎng)站的版權(quán)信息,不要以為那是用photoshop之類的圖片處理軟件加上去的,其實(shí)我們只要寫一小段代碼,就可以實(shí)現(xiàn)這個功能。
添加版權(quán)信息的原理其實(shí)挺簡單:通過圖片獲取graphics類的對象,該類有一個drawstring()方法可以將信息寫到圖片上,甚至還可以做出各種各樣的效果,如水印,背景透明等。最后保存圖片即大功告成了。
我們創(chuàng)建一個windows應(yīng)用程序項(xiàng)目,界面設(shè)計(jì)如圖:
添加版權(quán)信息的代碼如下:
//創(chuàng)建一張位圖
bitmap bitmap=new bitmap(this.picturebox2.width,this.picturebox2.height,system.drawing.imaging.pixelformat.format24bpprgb);
//根據(jù)位圖獲取畫布
graphics g=graphics.fromimage(bitmap);
//清空畫布并用透明色填充
g.clear(color.transparent);
//將另一幅圖片畫到畫布上
g.drawimage(this.picturebox1.image,0,0);
//寫版權(quán)信息到圖片上。
g.drawstring(this.textbox2.text,new font("黑體",15),new solidbrush(color.red),new rectangle(20,20,100,100));
//顯示
this.picturebox2.image=bitmap;
//保存圖片
bitmap.save("c://abc.bmp",system.drawing.imaging.imageformat.bmp);
順便帖一下“選擇”按鈕的單擊事件程序:
private void button1_click(object sender, system.eventargs e)
{
if(this.openfiledialog1.showdialog()==dialogresult.ok)
{
if(this.openfiledialog1.filename.length==0)
{
messagebox.show("請選擇圖片","錯誤",messageboxbuttons.ok,messageboxicon.error);
return;
}
this.textbox1.text=this.openfiledialog1.filename;
filestream fs=new filestream(this.openfiledialog1.filename,filemode.open,fileaccess.read);
try
{
this.picturebox1.image=image.fromstream(fs);
}
catch(exception)
{
messagebox.show("您選擇的文件不是可識別的圖片格式","錯誤",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
fs.close();
}
}
}