生成缩略图和添加水印
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Collections;
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="Width">缩略图的宽度</param>
/// <param name="Height">缩略图的高度</param>
/// <param name="targetFilePath">缩略图保存的全文件名,(带路径),参数格式:D:\Images\filename.jpg</param>
/// <returns>成功返回true,否则返回false</returns>
public bool GetReducedImage(int Width, int Height, string ImageFileName, string targetFilePath)
{
System.Drawing.Image ReducedImage = System.Drawing.Image.FromFile(ImageFileName);
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(Width, Height);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(ReducedImage, new Rectangle(0, 0, Width, Height),
new Rectangle(0, 0, ReducedImage.Width, ReducedImage.Height),
GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
bitmap.Save(targetFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
}
catch (System.Exception e)
{
throw e;
}
finally
{
ReducedImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
/// <summary>
/// 给图片添加文字水印
/// </summary>
/// <param name="str_sourceImagePath"></param>
/// <param name="str_WaterImagePatgh"></param>
/// <param name="str_SaveImagePath"></param>
public void AddWaterImage(string str_sourceImagePath, string str_WaterImagePatgh, string str_SaveImagePath)
{
System.Drawing.Image Cover;
if (File.Exists(str_sourceImagePath))
{
//加载图片
Cover = System.Drawing.Image.FromFile(str_sourceImagePath);
//加载水印图片
System.Drawing.Image watermark = System.Drawing.Image.FromFile(str_WaterImagePatgh);
//实例化画布
Graphics g = Graphics.FromImage(Cover);
//在image上绘制水印
g.DrawImage(watermark, new Rectangle(Cover.Width - watermark.Width, Cover.Height - watermark.Height, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel);
//释放画布
g.Dispose();
//释放水印图片
watermark.Dispose();
//将修改的图片保存到输出流中
Cover.Save(str_SaveImagePath, ImageFormat.Jpeg);
Cover.Dispose();
}
}
/// <summary>
/// 检测扩展名的有效性
/// </summary>
/// <param name="sExt">文件名扩展名</param>
/// <returns>如果扩展名有效,返回true,否则返回false.</returns>
private bool CheckValidExt(string sExt)
{
bool flag = false;
string[] aExt = AllowExt.Split('|');
foreach (string filetype in aExt)
{
if (filetype.ToLower() == sExt.ToLower())
{
flag = true;
break;
}
}
return flag;
}