给图片添加版权信息(C#)

** 给图片添加版权信息 (C#) **

现在越来越多的网站都喜欢将用户上传的图片加上网站的版权信息,不要以为那是用 photoshop 之类的图片处理软件加上去的,其实我们只要写一小段代码,就可以实现这个功能。

添加版权信息的原理其实挺简单:通过图片获取 Graphics 类的对象,该类有一个 DrawString() 方法可以将信息写到图片上,甚至还可以做出各种各样的效果,如水印,背景透明等。最后保存图片即大功告成了。

我们创建一个 windows 应用程序项目,界面设计如图:

添加版权信息的代码如下:

//创建一张位图

Bitmap bitmap= new Bitmap( this .pictureBox2.Width, this .pictureBox2.Height,System.Drawing.Imaging.PixelFormat.Format24bppRgb);

//根据位图获取画布

Graphics g=Graphics.FromImage(bitmap);

//清空画布并用透明色填充

g.Clear(Color.Transparent);

//将另一幅图片画到画布上

g.DrawImage( this .pictureBox1.Image,0,0);

//写版权信息到图片上。

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();

}

}

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus