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

C# Image 学习总结相关推荐

  1. java入门 慕路径,Java入门基础知识总结学习教程大全【必看经典】

    类型的表达式,是循环条件,表达式3是党执行了一遍循环之后,修改控制循环的变量值. ??? for语句的执行过程是这样的:首先计算表达式1,完成必要的初始化工作:然后判断表达式2的值,如果表达式的值为t ...

  2. Java EE学习心得

    –Java EE学习心得   1.    称为编程专家的秘诀是: 思考-----编程--------思考------编程--.. 编程不能一步到位,不能一上来就编,必须先思考如何写,怎样写?然后再编程 ...

  3. FastAI 2019课程学习笔记 lesson 2:自行获取数据并创建分类器

    文章目录 数据获取 google_images_download 的安装和使用 挂载google 个人硬盘到Google colab中 删除不能打开文件 创建ImageDataBunch 训练模型 解 ...

  4. FastAI 课程学习笔记 lesson 1:宠物图片分类

    文章目录 代码解析 神奇的"%" 导入fastAI 库 下载解压数据集 untar_data 获取帮助文档 help() ? ?? doc 设置路径 get_image_files ...

  5. 深度学习学习指南-工具篇

    colab Colab是由Google提供的云计算服务,通过它可以让开发者很方便的使用google的免费资源(CPU.GPU.TPU)来训练自己的模型. 学习经验总结 如何使用命令行? 通过!+cmd ...

  6. Redis学习之路(一)--下载安装redis

    redis学习之路--下载安装redis windows安装redis 1.下载redis 2.安装 3.查看是否安装成功 windows安装redis 1.下载redis 网址:https://gi ...

  7. python内置库之学习configparser库(一)

    python内置库之学习configparser库(一) 1.引言 ini文件简介 [节] 键=值 注:节不能重复出现 2.自己封装了一个增删改查的类,可以参考一下 import configpars ...

  8. 前端Vue学习之路(二)-Vue-router路由

    Vue学习之路 (二) Vue-router(基础版) 一.增加静态路由 二.动态路由+路由嵌套+404页面 三. 编程式导航 四.命名路由 五.命名视图 六.重定向和起别名 1.重定向 2.起别名 ...

  9. 前端Vue学习之路(一)-初识Vue

    Vue学习之路 (一) 1.引言 2.更换npm国内镜像源 3.用npm下载Vue 4.Vue全家桶 5.使用命令创建项目 5.推荐插件 6.推荐网站 7.学习扩展 1.引言 先安装node.js环境 ...

  10. 如何学习数据挖掘和数据科学的7个步骤

    前言 概括 1 学习语言 2 工具:数据挖掘,数据科学和可视化软件 3 教科书 4 教育:网络研讨会,课程,证书和学位 5 数据 6 比赛 7 互动:会议,团体和社交网络 more 前言 最近一直一再 ...

最新文章

  1. Springboot之YAML语法
  2. 第十六届智能汽车竞赛AI视觉组分赛区数据集发布
  3. graphlab中SFrame用法
  4. android技术积累,Android开发中积累的一些报错的解决方法
  5. 粤西茂名实现光网全覆盖 智慧城市改变民众生活
  6. 基于40万表格数据集TableBank,用MaskRCNN做表格检测
  7. Web文件管理原码.rar
  8. 康博(COMPUWARE)软件公司简介
  9. java基于springboot+vue的网上购物商城系统
  10. layabox flash转html5,FlashBuilder中第一个H5程序“Hello Layabox”
  11. 神经网络数据分析案例题,神经网络模型数据处理
  12. i510200h和i78750h哪个好?有什么区别
  13. 云运维拓扑图_云平台网络拓扑图
  14. 迪斯尼计算机动画,迪斯尼经典动画的十大运动规律
  15. 还在想假期去哪玩?直接做一个旅游攻略小程序
  16. 华为云服务器双十一报价表出炉最新内容
  17. 中国修边压力机行业市场供需与战略研究报告
  18. App.xaml MainWindow.xaml
  19. 二叉树(Binary Tree)详解
  20. 利用最小二乘法进行线性拟合

热门文章

  1. 怎么写显示商品图片_shopee商品描述怎么写,shopee商品排名靠前的是
  2. 线性系统理论知识点总结_线性系统理论(七)推广与总结
  3. python中怎么打开文件_python如何打开文件
  4. 实验18:使用@Autowired注解实现根据类型实现自动装配★
  5. mybatis执行查询的所有分析和创建代理对象的分析
  6. Request —— 获取请求行数据 获取请求头数据 获取请求体数据
  7. Java和C语言的语句对比
  8. CTFshow 命令执行 web29
  9. mean,std,var
  10. spg app android,GitHub - spgwzp/AndEsptouch: esptouch for android ,ESP8266网关配对