C# Image 学习总结

Image 类

https://msdn.microsoft.com/zh-cn/library/system.drawing.image.aspx


.NET Framework (current version) 其他版本 
 
一个抽象基类,提供了用于功能 Bitmap 和 Metafile 继承的类。
命名空间:   System.Drawing
程序集:  System.Drawing(位于 System.Drawing.dll)


继承层次结构
System.Object
  System.MarshalByRefObject
    System.Drawing.Image
      System.Drawing.Bitmap
      System.Drawing.Imaging.Metafile


语法
C#C++F#VB
[SerializableAttribute]
[TypeConverterAttribute(typeof(ImageConverter))]
[ComVisibleAttribute(true)]
public abstract class Image : MarshalByRefObject, ISerializable, 
ICloneable, IDisposable
属性
名称 说明
System_CAPS_pubproperty Flags
获取特性的像素数据的这标志 Image。
System_CAPS_pubproperty FrameDimensionsList
获取表示在此帧的维数的 Guid 的数组, Image。
System_CAPS_pubproperty Height
获取的高度,以像素为单位,这 Image。
System_CAPS_pubproperty HorizontalResolution
获取以每英寸的像素为单位的水平分辨率 Image。
System_CAPS_pubproperty Palette
获取或设置用于此目的的颜色调色板 Image。
System_CAPS_pubproperty PhysicalDimension
获取此图像的宽度和高度。
System_CAPS_pubproperty PixelFormat
获取此像素格式 Image。
System_CAPS_pubproperty PropertyIdList
获取存储于此的属性项的 Id Image。
System_CAPS_pubproperty PropertyItems
获取的所有属性项 (元数据片) 存储在此 Image。
System_CAPS_pubproperty RawFormat
获取此文件格式 Image。
System_CAPS_pubproperty Size
获取此图像的宽度和高度(以像素为单位)。
System_CAPS_pubproperty Tag
获取或设置提供有关图像的附加数据的对象。
System_CAPS_pubproperty VerticalResolution
获取以每英寸的像素为单位的垂直分辨率 Image。
System_CAPS_pubproperty Width
获取的宽度,以像素为单位,这 Image。
方法
名称 说明
System_CAPS_pubmethod Clone()
创建此 Image 的一个精确副本。
System_CAPS_pubmethod CreateObjRef(Type)
创建包含生成用来与远程对象通信的代理所需的所有相关信息的对象。(继承自 MarshalByRefObject。)
System_CAPS_pubmethod Dispose()
释放此 Image 使用的所有资源。
System_CAPS_protmethod Dispose(Boolean)
释放由 Image 占用的非托管资源,还可以另外再释放托管资源。
System_CAPS_pubmethod Equals(Object)
确定指定的对象是否等于当前对象。(继承自 Object。)
System_CAPS_protmethod Finalize()
在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(覆盖 Object.Finalize()。)
System_CAPS_pubmethodSystem_CAPS_static FromFile(String)
创建 Image 从指定的文件。
System_CAPS_pubmethodSystem_CAPS_static FromFile(String, Boolean)
创建 Image 从指定的文件使用嵌入的颜色管理信息在该文件中。
System_CAPS_pubmethodSystem_CAPS_static FromHbitmap(IntPtr)
创建 Bitmap 从 GDI 位图的句柄。
System_CAPS_pubmethodSystem_CAPS_static FromHbitmap(IntPtr, IntPtr)
创建 Bitmap 从 GDI 位图和 GDI 调色板的句柄的句柄。
System_CAPS_pubmethodSystem_CAPS_static FromStream(Stream)
创建 Image 从指定的数据流。
System_CAPS_pubmethodSystem_CAPS_static FromStream(Stream, Boolean)
创建 Image 从指定的数据流 (可选) 使用嵌入的颜色管理信息该流中。
System_CAPS_pubmethodSystem_CAPS_static FromStream(Stream, Boolean, Boolean)
创建 Image 从指定的数据流 (可选) 使用嵌入的颜色管理信息并验证图像数据。
System_CAPS_pubmethod GetBounds(GraphicsUnit)
以指定的单位获取图像的界限。
System_CAPS_pubmethod GetEncoderParameterList(Guid)
返回有关指定的图像编码器所支持的参数的信息。
System_CAPS_pubmethod GetFrameCount(FrameDimension)
返回指定维度的帧数。
System_CAPS_pubmethod GetHashCode()
作为默认哈希函数。(继承自 Object。)
System_CAPS_pubmethod GetLifetimeService()
检索当前生存期的服务对象,用于控制此实例的生存期策略。(继承自 MarshalByRefObject。)
System_CAPS_pubmethodSystem_CAPS_static GetPixelFormatSize(PixelFormat)
返回指定像素格式的颜色深度(每个像素的位数)。
System_CAPS_pubmethod GetPropertyItem(Int32)
获取指定的属性项从此 Image。
System_CAPS_pubmethod GetThumbnailImage(Int32, Int32, Image.GetThumbnailImageAbort, IntPtr)
返回此缩略图 Image。
System_CAPS_pubmethod GetType()
获取当前实例的 Type。(继承自 Object。)
System_CAPS_pubmethod InitializeLifetimeService()
获取使用生存期服务对象来控制此实例的生存期策略。(继承自 MarshalByRefObject。)
System_CAPS_pubmethodSystem_CAPS_static IsAlphaPixelFormat(PixelFormat)
返回一个值,该值指示的像素格式是否为此 Image 包含 alpha 信息。
System_CAPS_pubmethodSystem_CAPS_static IsCanonicalPixelFormat(PixelFormat)
返回一个值,该值指示该像素格式是否为每个像素 32 位。
System_CAPS_pubmethodSystem_CAPS_static IsExtendedPixelFormat(PixelFormat)
返回一个值,该值指示该像素格式是否为每个像素 64 位。
System_CAPS_protmethod MemberwiseClone()
创建当前 Object 的浅表副本。(继承自 Object。)
System_CAPS_protmethod MemberwiseClone(Boolean)
创建当前的浅表副本 MarshalByRefObject 对象。(继承自 MarshalByRefObject。)
System_CAPS_pubmethod RemovePropertyItem(Int32)
从这中移除指定的属性项 Image。
System_CAPS_pubmethod RotateFlip(RotateFlipType)
旋转、 翻转,或将旋转和翻转 Image。
System_CAPS_pubmethod Save(Stream, ImageCodecInfo, EncoderParameters)
使用指定的编码器和图像编码器参数,将该图像保存到指定的流。
System_CAPS_pubmethod Save(Stream, ImageFormat)
将此图像以指定的格式保存到指定的流中。
System_CAPS_pubmethod Save(String)
这会将保存 Image 写入指定的文件或流。
System_CAPS_pubmethod Save(String, ImageCodecInfo, EncoderParameters)
这会将保存 Image 写入指定的文件,使用指定的编码器和图像编码器参数。
System_CAPS_pubmethod Save(String, ImageFormat)
这会将保存 Image 写入指定的文件中指定的格式。
System_CAPS_pubmethod SaveAdd(EncoderParameters)
将帧添加到上次对 Save 方法调用时所指定的文件或流中。 使用此方法将多帧图像中的选定帧保存到另一个多帧图像。
System_CAPS_pubmethod SaveAdd(Image, EncoderParameters)
将帧添加到上次对 Save 方法调用时所指定的文件或流中。
System_CAPS_pubmethod SelectActiveFrame(FrameDimension, Int32)
选择由维度和索引指定的帧。
System_CAPS_pubmethod SetPropertyItem(PropertyItem)
在此 Image 中存储一个属性项(元数据片)。
System_CAPS_pubmethod ToString()
返回表示当前对象的字符串。(继承自 Object。)
显式接口实现
名称 说明
System_CAPS_pubinterfaceSystem_CAPS_privmethod ISerializable.GetObjectData(SerializationInfo, StreamingContext)
使用将目标对象序列化所需的数据填充 SerializationInfo。
备注
若要绘制 Image 在 Windows 窗体中,应使用之一 DrawImage 方法。
示例
下面的代码示例旨在为使用 Windows 窗体。 它是处理程序 Paint 事件。 一个 Graphics 对象传递给事件,并且使用窗体上绘制图像。 该代码执行下列操作:
从名为 sampimag.jpg 位于同一个文件中创建的映像。 此文件必须位于应用程序可执行文件所在的文件夹。
创建要在该处绘制图像的左上角的点。
窗体上绘制不成比例的图像。
C#C++VB
private void ImageExampleForm_Paint(object sender, PaintEventArgs e)
{         
    // Create image.
    Image newImage = Image.FromFile("SampImag.jpg");


    // Create Point for upper-left corner of image.
    Point ulCorner = new Point(100, 100);


    // Draw image to screen.
    e.Graphics.DrawImage(newImage, ulCorner);
}
版本信息
.NET Framework 
自 1.1 起可用
线程安全
此类型的所有公共静态(Visual Basic 中的 已共享 在 Visual Basic 中)成员都是线程安全的。不保证所有实例成员都是线程安全的。
另请参阅
System.Drawing 命名空间
图像、位图和图元文件
使用图像、位图、图标和图元文件
========

 C# Image 加载图片

http://blog.csdn.net/cai_huan_123/article/details/42524001
Image.FromFile  一旦使用后,对应的文件在一直调用其生成的Image对象被Disponse前都不会被解除锁定,这就造成了一个问题,就是在这个图形被解锁前无法对图像进行操作(比如删除,修改等操作).


在以前用的过程中曾用过下面三个方法解决问题.


第一种方法,在要进行文件操作前将Image对象销毁.


PictureBox picbox;


if(picbox.Image!=null)picbox.Image.Disponse();


第二种方法,就是在加载图像的时候用一种方法替代:


System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);


System.Drawing.Image bmp = new System.Drawing.Bitmap(img.Width, img.Height,    System.Drawing.Imaging.PixelFormat.Format32bppArgb);


System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);


g.DrawImage(img, 0, 0);


g.Flush();


g.Dispose();


img.Dispose();


//下面开始使用bmp作为显示的Image对象


System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);


System.Drawing.Image bmp = new System.Drawing.Bitmap(img);


img.Dispose();


方法四:


fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()


Image类的FromFile方法打开文件と后没有关闭,导致文件锁定,无法进行删除、移动等操作。


  该而使用FromStream方法,代码如下:


  //读取文件流
FileStream fileStream = new FileStream(iconPath, FileMode.Open, FileAccess.Read);


int byteLength = (int)fileStream.Length;
byte[] fileBytes = new byte[byteLength];
fileStream.Read(fileBytes, 0, byteLength);


//文件流关閉,文件解除锁定
fileStream.Close();


Pictrue.Image = Image.FromStream(new MemoryStream(fileBytes));


因为FromStream方法参数应用的流必须一直保持打开,故代码中有一个文件流向MemeoryStream流的转换,从而可以关闭文件流,保持MemoryStream流的打开状态。
========

C#如何释放已经加载的图片

http://www.cnblogs.com/netlyf/p/3781630.html
使用Image.FromFile取磁盘上的图片时,这个方法会锁定图片文件,而且会导致内存占用增大, 有几种方法解决:
一:将Image类转换成Bitmap类
System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);
System.Drawing.Image bmp = new System.Drawing.Bitmap(img);
img.Dispose();
然后使用 bmp作为PictureBox的图片源
二:从流中读取
FileStream fileStream = new FileStream("文件名", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(fileStream);
fileStream.Close();
fileStream.Dispose(); 


原因:一个图像对象从一个文件构造时该文件仍保留锁定对象的生存期。所以关键是要使用 Graphics.DrawImage()方法或Drawing.Bitmap()方法来将映像复制到新位图Bitmap对象,然后Bitmap和Graphics就可以释放了。或者用使用FileStream的方式将文件读成流。
========

c#在sql中存取图片image示例

http://www.jb51.net/article/48035.htm
这篇文章主要介绍了c#在sql中存取图片image示例,需要的朋友可以参考下
..(1)控制台应用程序下演示插入图片


复制代码 代码如下:
public void InsertIMG()
{
//将需要存储的图片读取为数据流
FileStream fs = new FileStream(@"E:\c.jpg", FileMode.Open,FileAccess.Read);
Byte[] btye2 = new byte[fs.Length];
fs.Read(btye2 , 0, Convert.ToInt32(fs.Length));
fs.Close();


using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into T_Img(imgfile) values(@imgfile)";
SqlParameter par = new SqlParameter("@imgfile", SqlDbType.Image);
par.Value = bt;
cmd.Parameters.Add(par);


int t=(int)(cmd.ExecuteNonQuery());
if (t > 0)
{
Console.WriteLine("插入成功");
}
conn.Close();
}
}


(2)控制台应用程序下读出并生成图片到物理位置


复制代码 代码如下:
public void Read()
{
byte[] MyData = new byte[0];
using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from T_img";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
MyData = (byte[])sdr["ImgFile"];//读取第一个图片的位流
int ArraySize= MyData.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限,用作读取流的上限


FileStream fs = new FileStream(@"c:\00.jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0, ArraySize);
fs.Close();   //-- 写入到c:\00.jpg。
conn.Close();
Console.WriteLine("读取成功");//查看硬盘上的文件
}
}


(3)Web下picshow.aspx页将图片读取出来并写入到浏览器上呈现


复制代码 代码如下:
public void Read()
{
byte[] MyData = new byte[0];
using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from T_img";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
MyData = (byte[])sdr["ImgFile"];
Response.ContentType = "image/gif";
Response.BinaryWrite(MyData);
conn.Close();
Response.Write("读取成功");
}
(4)在web中可以如上picshow.aspx页面读取并显示图片,而真正引用该图片时如下示例


复制代码 代码如下:
<img src="picshow.aspx" width="500" height="300" />


 (5)Winform下将图片写入到sql数据库image类型字段中的方法和以上方法基本一致,仅区别于可以利用多个对话框来帮助选取存储图片等,各个属性可以方便的利用上


(6)Winform下读取图片在picturebox控件中显示出来


方法一:利用MemoryStream 和System.Drawing.Image


复制代码 代码如下:
public void Read()
{
byte[] MyData = new byte[0];
using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from T_img";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
MyData = (byte[])sdr["ImgFile"];


MemoryStream mystream = new MemoryStream(MyData);
//用指定的数据流来创建一个image图片
System.Drawing.Image img = System.Drawing.Image.FromStream(mystream, true);


System.Windows.Forms.PictureBox picbox = new PictureBox();
picbox.Image = img;
picbox.Left = 30;
picbox.Top = 80;
picbox.Width = 800;
picbox.Height = 500;
this.Controls.Add(picbox);


mystream.Close();
conn.Close();
}
}


方法二:将流直接读取成图片并写入到物理位置,然后再行利用该图片呈现


复制代码 代码如下:
void Read()
{
using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from T_img";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();


byte[] Image_img = (byte[])sdr["ImgFile"];
if (Image_img.Length == 0)
{
return;
}
int filelength = Image_img.Length;
string imageName = "1.jpg";
string myUrl = Environment.CurrentDirectory + "\\" + imageName;
FileStream fs = new FileStream(myUrl, FileMode.OpenOrCreate,FileAccess.Write);
BinaryWriter BW = new BinaryWriter(fs);
BW.BaseStream.Write(Image_img, 0, filelength);
BW.Flush();
BW.Close();
System.Windows.Forms.PictureBox picbox = new PictureBox();


//为picbox添加图片方法一
//picbox.ImageLocation = myUrl;
//picbox.Width = 800;
//picbox.Height = 300;


//为picbox添加图片方法二
Bitmap bitmap = new Bitmap(myUrl);
picbox.Width = 100;//bitmap.Width;
picbox.Height = 80;//bitmap.Height;
picbox.Image = (Image)bitmap;
picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
picbox.Left = 20;
picbox.Top = 30;


this.Controls.Add(picbox);
conn.Close();
}
}
========

C#利用原图和水印图的重叠简单实现水印的方法

http://www.jb51.net/article/82764.htm
这篇文章主要介绍了C#利用原图和水印图的重叠简单实现水印的方法,实例演示了完整的水印操作类实现方法,需要的朋友可以参考下


图片操作类


/// <summary> /// 获取一个图片按等比例缩小后的大小。 /// </summary> /// <param name="maxWidth">需要缩小到的宽度</param> /// <param name="maxHeight">需要缩小到的高度</param> /// <param name="imageOriginalWidth">图片的原始宽度</param> /// <param name="imageOriginalHeight">图片的原始高度</param> /// <returns>返回图片按等比例缩小后的实际大小</returns> public static Size GetNewSize(int maxWidth, int maxHeight, int imageOriginalWidth, int imageOriginalHeight) {   double w = 0.0;   double h = 0.0;   double sw = Convert.ToDouble(imageOriginalWidth);   double sh = Convert.ToDouble(imageOriginalHeight);   double mw = Convert.ToDouble(maxWidth);   double mh = Convert.ToDouble(maxHeight);   if (sw < mw && sh < mh)   {     w = sw;     h = sh;   }   else if ((sw / sh) > (mw / mh))   {     w = maxWidth;     h = (w * sh) / sw;   }   else  {     h = maxHeight;     w = (h * sw) / sh;   }   return new Size(Convert.ToInt32(w), Convert.ToInt32(h)); } /// <summary> /// 对给定的一个图片(Image对象)生成一个指定大小的缩略图。 /// </summary> /// <param name="originalImage">原始图片</param> /// <param name="thumMaxWidth">缩略图的宽度</param> /// <param name="thumMaxHeight">缩略图的高度</param> /// <returns>返回缩略图的Image对象</returns> public static System.Drawing.Image GetThumbNailImage(System.Drawing.Image originalImage, int thumMaxWidth, int thumMaxHeight) {   Size thumRealSize = Size.Empty;   System.Drawing.Image newImage = originalImage;   Graphics graphics = null;   try  {     thumRealSize = GetNewSize(thumMaxWidth, thumMaxHeight, originalImage.Width, originalImage.Height);     newImage = new Bitmap(thumRealSize.Width, thumRealSize.Height);     graphics = Graphics.FromImage(newImage);     graphics.CompositingQuality = CompositingQuality.HighQuality;     graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;     graphics.SmoothingMode = SmoothingMode.HighQuality;     graphics.Clear(Color.Transparent);     graphics.DrawImage(originalImage, new Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel);   }   catch { }   finally  {     if (graphics != null)     {       graphics.Dispose();       graphics = null;     }   }   return newImage; } /// <summary> /// 对给定的一个图片文件生成一个指定大小的缩略图。 /// </summary> /// <param name="originalImage">图片的物理文件地址</param> /// <param name="thumMaxWidth">缩略图的宽度</param> /// <param name="thumMaxHeight">缩略图的高度</param> /// <returns>返回缩略图的Image对象</returns> public static System.Drawing.Image GetThumbNailImage(string imageFile, int thumMaxWidth, int thumMaxHeight) {   System.Drawing.Image originalImage = null;   System.Drawing.Image newImage = null;   try  {     originalImage = System.Drawing.Image.FromFile(imageFile);     newImage = GetThumbNailImage(originalImage, thumMaxWidth, thumMaxHeight);   }   catch { }   finally  {     if (originalImage != null)     {       originalImage.Dispose();       originalImage = null;     }   }   return newImage; } /// <summary> /// 对给定的一个图片文件生成一个指定大小的缩略图,并将缩略图保存到指定位置。 /// </summary> /// <param name="originalImageFile">图片的物理文件地址</param> /// <param name="thumbNailImageFile">缩略图的物理文件地址</param> /// <param name="thumMaxWidth">缩略图的宽度</param> /// <param name="thumMaxHeight">缩略图的高度</param> public static void MakeThumbNail(string originalImageFile, string thumbNailImageFile, int thumMaxWidth, int thumMaxHeight) {   System.Drawing.Image newImage = GetThumbNailImage(originalImageFile, thumMaxWidth, thumMaxHeight);   try  {     newImage.Save(thumbNailImageFile, ImageFormat.Jpeg);   }   catch  { }   finally  {     newImage.Dispose();     newImage = null;   } } /// <summary> /// 将一个图片的内存流调整为指定大小,并返回调整后的内存流。 /// </summary> /// <param name="originalImageStream">原始图片的内存流</param> /// <param name="newWidth">新图片的宽度</param> /// <param name="newHeight">新图片的高度</param> /// <returns>返回调整后的图片的内存流</returns> public static MemoryStream ResizeImage(Stream originalImageStream, int newWidth, int newHeight) {   MemoryStream newImageStream = null;   System.Drawing.Image newImage = Globals.GetThumbNailImage(System.Drawing.Image.FromStream(originalImageStream), newWidth, newHeight);   if (newImage != null)   {     newImageStream = new MemoryStream();     newImage.Save(newImageStream, ImageFormat.Jpeg);   }   return newImageStream; } /// <summary> /// 将一个内存流保存为磁盘文件。 /// </summary> /// <param name="stream">内存流</param> /// <param name="newFile">目标磁盘文件地址</param> public static void SaveStreamToFile(Stream stream, string newFile) {   if (stream == null || stream.Length == 0 || string.IsNullOrEmpty(newFile))   {     return;   }   byte[] buffer = new byte[stream.Length];   stream.Position = 0;   stream.Read(buffer, 0, buffer.Length);   FileStream fileStream = new FileStream(newFile, FileMode.OpenOrCreate, FileAccess.Write);   fileStream.Write(buffer, 0, buffer.Length);   fileStream.Flush();   fileStream.Close();   fileStream.Dispose(); } /// <summary> /// 对一个指定的图片加上图片水印效果。 /// </summary> /// <param name="imageFile">图片文件地址</param> /// <param name="waterImage">水印图片(Image对象)</param> public static void CreateImageWaterMark(string imageFile, System.Drawing.Image waterImage) {   if (string.IsNullOrEmpty(imageFile) || !File.Exists(imageFile) || waterImage == null)   {     return;   }   System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imageFile);   if (originalImage.Width - 10 < waterImage.Width || originalImage.Height - 10 < waterImage.Height)   {     return;   }   Graphics graphics = Graphics.FromImage(originalImage);   int x = originalImage.Width - waterImage.Width - 10;   int y = originalImage.Height - waterImage.Height - 10;   int width = waterImage.Width;   int height = waterImage.Height;   graphics.DrawImage(waterImage, new Rectangle(x, y, width, height), 0, 0, width, height, GraphicsUnit.Pixel);   graphics.Dispose();   MemoryStream stream = new MemoryStream();   originalImage.Save(stream, ImageFormat.Jpeg);   originalImage.Dispose();   System.Drawing.Image imageWithWater = System.Drawing.Image.FromStream(stream);   imageWithWater.Save(imageFile);   imageWithWater.Dispose(); } /// <summary> /// 对一个指定的图片加上文字水印效果。 /// </summary> /// <param name="imageFile">图片文件地址</param> /// <param name="waterText">水印文字内容</param> public static void CreateTextWaterMark(string imageFile, string waterText) {   if (string.IsNullOrEmpty(imageFile) || string.IsNullOrEmpty(waterText) || !File.Exists(imageFile))   {     return;   }   System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imageFile);   Graphics graphics = Graphics.FromImage(originalImage);   graphics.SmoothingMode = SmoothingMode.HighQuality;   graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;   graphics.CompositingQuality = CompositingQuality.HighQuality;   graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;   SolidBrush brush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));   Font waterTextFont = new Font("Arial", 16, FontStyle.Regular);   SizeF waterTextSize = graphics.MeasureString(waterText, waterTextFont);   float x = (float)originalImage.Width - waterTextSize.Width - 10F;   float y = (float)originalImage.Height - waterTextSize.Height - 10F;   graphics.DrawString(waterText, waterTextFont, brush, x, y);   graphics.Dispose();   brush.Dispose();   MemoryStream stream = new MemoryStream();   originalImage.Save(stream, ImageFormat.Jpeg);   originalImage.Dispose();   System.Drawing.Image imageWithWater = System.Drawing.Image.FromStream(stream);   imageWithWater.Save(imageFile);   imageWithWater.Dispose(); } /// <summary> /// 判断上传组件是否包含内容。 /// </summary> /// <param name="fileUpload">ASP.NET 2.0标准上传组件</param> /// <returns>如果数据有效,则返回True,否则返回False</returns> public static bool IsAttachmentValid(FileUpload fileUpload) {   if (fileUpload != null &&     fileUpload.PostedFile != null &&     !string.IsNullOrEmpty(fileUpload.PostedFile.FileName) &&     fileUpload.PostedFile.ContentLength > 0)   {     return true;   }   return false; } 
public class ImageHelper {   #region " 水印存放的相对路径 "   public static string GetLogoPath()   {     return "/images/logo.png";  ///水印图路径   }   #endregion   #region " 图片水印 "   // <summary>   // 在图片上生成图片水印,此方法不支持Gif类型的图片   // </summary>   // <param name="Path">原服务器图片路径</param>   // <param name="Path_syp">生成的带图片水印的图片路径</param>   // <param name="Path_sypf">水印图片路径</param>   public static void MarkImage(Stream InUploadImagePath, string inLogoImagePath, string InSavePath)   {     System.Drawing.Image Image = System.Drawing.Image.FromStream(InUploadImagePath);     System.Drawing.Image newimage = Image.FromFile(Current.Server.MapPath(inLogoImagePath));     Graphics g = Graphics.FromImage(Image);     g.DrawImage(newimage, new Rectangle(Image.Width - newimage.Width, Image.Height - newimage.Height, newimage.Width, newimage.Height), 0, 0, newimage.Width, newimage.Height, GraphicsUnit.Pixel);     try {       Image.Save(Current.Server.MapPath(InSavePath));     }     catch (Exception ex) {     }     finally {       g.Dispose();       Image.Dispose();       newimage.Dispose();     }   }   #endregion } 
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#图片操作技巧汇总》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#常见控件用法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
========

C#给图片加水印标记,可设置透明度

http://www.cnblogs.com/huangcong/archive/2010/03/26/1697319.html
/// <summary>  
/// Creating a Watermarked Photograph with GDI+ for .NET  
/// </summary>  
/// <param name="rSrcImgPath">原始图片的物理路径</param>  
/// <param name="rMarkImgPath">水印图片的物理路径</param>  
/// <param name="rMarkText">水印文字(不显示水印文字设为空串)</param>  
/// <param name="rDstImgPath">输出合成后的图片的物理路径</param>  
/// @整理: anyrock@mending.cn  
public void BuildWatermark(string rSrcImgPath,string rMarkImgPath,string rMarkText,string rDstImgPath)  
{  
     //以下(代码)从一个指定文件创建了一个Image 对象,然后为它的 Width 和 Height定义变量。  
     //这些长度待会被用来建立一个以24 bits 每像素的格式作为颜色数据的Bitmap对象。  
     Image imgPhoto = Image.FromFile(rSrcImgPath);  
     int phWidth = imgPhoto.Width;  
     int phHeight = imgPhoto.Height;  
     Bitmap bmPhoto=new Bitmap(phWidth,phHeight, PixelFormat.Format24bppRgb);  
     bmPhoto.SetResolution(72,72);  
     Graphics grPhoto = Graphics.FromImage(bmPhoto);  
     //这个代码载入水印图片,水印图片已经被保存为一个BMP文件,以绿色(A=0,R=0,G=255,B=0)作为背景颜色。  
     //再一次,会为它的Width 和Height定义一个变量。  
     Image imgWatermark = new Bitmap(rMarkImgPath);  
     int wmWidth = imgWatermark.Width;  
     int wmHeight = imgWatermark.Height;  
     //这个代码以100%它的原始大小绘制imgPhoto 到Graphics 对象的(x=0,y=0)位置。  
     //以后所有的绘图都将发生在原来照片的顶部。  
     grPhoto.SmoothingMode = SmoothingMode.AntiAlias;  
     grPhoto.DrawImage(  
          imgPhoto,                                        
          new Rectangle(0, 0, phWidth, phHeight),   
          0,                                                    
          0,                                                      
          phWidth,                                          
          phHeight,                                        
          GraphicsUnit.Pixel);  
     //为了最大化版权信息的大小,我们将测试7种不同的字体大小来决定我们能为我们的照片宽度使用的可能的最大大小。  
     //为了有效地完成这个,我们将定义一个整型数组,接着遍历这些整型值测量不同大小的版权字符串。  
     //一旦我们决定了可能的最大大小,我们就退出循环,绘制文本  
     int[] sizes = new int[]{16,14,12,10,8,6,4};  
     Font crFont = null;   
     SizeF crSize = new  SizeF();   
     for (int i=0 ;i<7; i++)  
     {   
          crFont = new Font("arial", sizes[i],  
                FontStyle.Bold);  
          crSize = grPhoto.MeasureString(rMarkText,  
                crFont);  
          if((ushort)crSize.Width < (ushort)phWidth)  
                break;  
     }  
     //因为所有的照片都有各种各样的高度,所以就决定了从图象底部开始的5%的位置开始。  
     //使用rMarkText字符串的高度来决定绘制字符串合适的Y坐标轴。  
     //通过计算图像的中心来决定X轴,然后定义一个StringFormat 对象,设置StringAlignment 为Center。  
     int yPixlesFromBottom = (int)(phHeight *.05);  
     float yPosFromBottom = ((phHeight -   
          yPixlesFromBottom)-(crSize.Height/2));  
     float xCenterOfImg = (phWidth/2);  
     StringFormat StrFormat = new StringFormat();  
     StrFormat.Alignment = StringAlignment.Center;  
     //现在我们已经有了所有所需的位置坐标来使用60%黑色的一个Color(alpha值153)创建一个SolidBrush 。  
     //在偏离右边1像素,底部1像素的合适位置绘制版权字符串。  
     //这段偏离将用来创建阴影效果。使用Brush重复这样一个过程,在前一个绘制的文本顶部绘制同样的文本。  
     SolidBrush semiTransBrush2 =   
          new SolidBrush(Color.FromArgb(153, 0, 0,0));   
     grPhoto.DrawString(rMarkText,                          
          crFont,                                                   
          semiTransBrush2,                                      
          new PointF(xCenterOfImg+1,yPosFromBottom+1),   
          StrFormat);  
     SolidBrush semiTransBrush = new SolidBrush(  
          Color.FromArgb(153, 255, 255, 255));  
     grPhoto.DrawString(rMarkText,                      
          crFont,                                               
          semiTransBrush,                                     
          new PointF(xCenterOfImg,yPosFromBottom),    
          StrFormat);  
     //根据前面修改后的照片创建一个Bitmap。把这个Bitmap载入到一个新的Graphic对象。  
     Bitmap bmWatermark = new Bitmap(bmPhoto);   
     bmWatermark.SetResolution(  
          imgPhoto.HorizontalResolution,   
          imgPhoto.VerticalResolution);  
     Graphics grWatermark =  
          Graphics.FromImage(bmWatermark);  
     //通过定义一个ImageAttributes 对象并设置它的两个属性,我们就是实现了两个颜色的处理,以达到半透明的水印效果。  
     //处理水印图象的第一步是把背景图案变为透明的(Alpha=0, R=0, G=0, B=0)。我们使用一个Colormap 和定义一个RemapTable来做这个。  
     //就像前面展示的,我的水印被定义为100%绿色背景,我们将搜到这个颜色,然后取代为透明。  
     ImageAttributes imageAttributes =  
          new ImageAttributes();  
     ColorMap colorMap = new ColorMap();  
     colorMap.OldColor=Color.FromArgb(255, 0, 255, 0);  
     colorMap.NewColor=Color.FromArgb(0, 0, 0, 0);  
     ColorMap[] remapTable = {colorMap};  
     //第二个颜色处理用来改变水印的不透明性。  
     //通过应用包含提供了坐标的RGBA空间的5x5矩阵来做这个。  
     //通过设定第三行、第三列为0.3f我们就达到了一个不透明的水平。结果是水印会轻微地显示在图象底下一些。  
     imageAttributes.SetRemapTable(remapTable,  
          ColorAdjustType.Bitmap);  
     float[][] colorMatrixElements = {   
                                                     new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},  
                                                     new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},  
                                                     new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},  
                                                     new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},  
                                                     new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}  
                                                };  
     ColorMatrix wmColorMatrix = new  
          ColorMatrix(colorMatrixElements);  
     imageAttributes.SetColorMatrix(wmColorMatrix,   
          ColorMatrixFlag.Default,   
          ColorAdjustType.Bitmap);  
     //随着两个颜色处理加入到imageAttributes 对象,我们现在就能在照片右手边上绘制水印了。  
     //我们会偏离10像素到底部,10像素到左边。  
     int markWidth;  
     int markHeight;  
     //mark比原来的图宽  
     if(phWidth<=wmWidth)  
     {  
          markWidth = phWidth-10;  
          markHeight = (markWidth*wmHeight)/wmWidth;  
     }  
     else if(phHeight<=wmHeight)  
     {  
          markHeight = phHeight-10;  
          markWidth = (markHeight*wmWidth)/wmHeight;  
     }  
     else  
     {  
          markWidth = wmWidth;  
          markHeight = wmHeight;  
     }  
     int xPosOfWm = ((phWidth - markWidth)-10);  
     int yPosOfWm = 10;  
     grWatermark.DrawImage(imgWatermark,   
          new Rectangle(xPosOfWm,yPosOfWm,markWidth,  
          markHeight),  
          0,                          
          0,                           
          wmWidth,                
          wmHeight,               
          GraphicsUnit.Pixel,   
          imageAttributes);  
     //最后的步骤将是使用新的Bitmap取代原来的Image。 销毁两个Graphic对象,然后把Image 保存到文件系统。  
     imgPhoto = bmWatermark;  
     grPhoto.Dispose();  
     grWatermark.Dispose();  
     imgPhoto.Save(rDstImgPath,ImageFormat.Jpeg);  
     imgPhoto.Dispose();  
     imgWatermark.Dispose();                  
}  
========
  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值