对图片进行操作,常用的就是上传及对图片进行裁剪,生成缩略图等
/// <summary>
/// jqueryUpImg 图片上传及裁剪
/// </summary>
public class jqueryUpImg : IHttpHandler
{
private string urlPath = "";
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string reStr = "{\"status\" : \"error\", \"msg\" : \"上传失败,请重试!\"}";
HttpFileCollection postedFile = context.Request.Files;
HttpPostedFile file = postedFile[0];
urlPath = HttpContext.Current.Server.MapPath("~/upFile/" + @context.Request["name"] + "/");
string uploadpath = urlPath;
if (file != null)
{
string filetype = Path.GetExtension(file.FileName).ToLower();
filetype = filetype.ToLower();
if (filetype == ".png" || filetype == ".jpg" || filetype == ".gif" || filetype == ".bmp" || filetype == ".jpeg" || filetype == ".icon")
{
Random rd = new Random();
string oldFileName = file.FileName;
string fileNameStr = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(100, 999).ToString(); //随机产品文件名
string fileName = fileNameStr + filetype;
string savepath = uploadpath + fileName;
string width = @context.Request["width"];
string height = @context.Request["height"];
if (File.Exists(savepath))
{
reStr = "{\"status\" : \"error\", \"msg\" : \"当前图片名称已经存在,请更改!\"}";
}
else
{
if (Directory.Exists(uploadpath) == false) //如果不存在就创建file文件夹,防止不存在文件夹是出错
{
Directory.CreateDirectory(uploadpath);
}
file.SaveAs(savepath);
try
{
string[] widthStr = width.Split(',');
string[] heightStr = height.Split(',');
int quality = 100;
if (Convert.ToInt32(widthStr[0]) > 600)
{
quality = 80;
}
/*规定大小图片,进行切图*/
string fileNameStr1 = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000, 9999).ToString();
string fileName1 = fileNameStr1 + filetype;
string newpath = uploadpath + fileName1;
ImageHelper.MakeThumbnail(savepath, newpath, Convert.ToInt32(widthStr[0]), Convert.ToInt32(heightStr[0]), (heightStr[0] == "0" ? "W" : "Cut"), quality);
string fileNameStr2 = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000, 9999).ToString();
string fileName2 = fileNameStr2 + filetype;
string newpath1 = uploadpath + fileName2;
ImageHelper.MakeThumbnail(newpath, newpath1, Convert.ToInt32(widthStr[1]), Convert.ToInt32(heightStr[1]), (heightStr[1] == "0" ? "W" : "Cut"), quality);
string fileNameStr3 = DateTime.Now.ToString("yyyyMMddhhmmssfff") + rd.Next(1000, 9999).ToString();
string fileName3 = fileNameStr3 + filetype;
string newpath2 = uploadpath + fileName3;
ImageHelper.MakeThumbnail(newpath1, newpath2, Convert.ToInt32(widthStr[2]), Convert.ToInt32(heightStr[2]), (heightStr[2] == "0" ? "W" : "Cut"), quality);
/*规定大小图片,进行切图*/
if (File.Exists(newpath))
{
if (savepath.Trim() != "")
{
string img = "../upFile/" + @context.Request["name"] + "/" + fileName;
string imgBig = "../upFile/" + @context.Request["name"] + "/" + fileName1;
string imgMiddle = "../upFile/" + @context.Request["name"] + "/" + fileName2;
string imgSmall = "../upFile/" + @context.Request["name"] + "/" + fileName3;
reStr = "{\"status\" : \"success\", \"img\" : \"" + img + "\", \"imgBig\" : \"" + imgBig + "\", \"imgMiddle\" : \"" + imgMiddle + "\", \"imgSmall\" : \"" + imgSmall + "\"}";
}
}
}
catch
{
}
}
}
else
{
reStr = "{\"status\" : \"error\", \"msg\" : \"文件名格式不正确!\"}";
}
}
context.Response.Write(reStr);
}
public bool IsReusable
{
get
{
return false;
}
}
}
/// <summary>
/// 图片操作类
/// </summary>
public class ImageHelper
{
#region 缩略图
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
/// <param name="quality">质量(范围1-100) //设置图片质量,越大越清晰文件就越大,100以上设置了也是和100一样的效果:有些没有这个参数,会出现上传超时情况</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, int quality)
{
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case "HW": //指定高宽缩放(可能变形)
break;
case "W": //指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H": //指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut": //指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
try
{
/*//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);*/ //使用这个,会出现上传超时情况
//关键质量控制:使用上面注释掉的程序的时候,图片不清晰
//获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
if (originalImagePath.IndexOf("png") != -1)
{
jgpEncoder = GetEncoder(ImageFormat.Png);
}
else if (originalImagePath.IndexOf("gif") != -1)
{
jgpEncoder = GetEncoder(ImageFormat.Gif);
}
else if (originalImagePath.IndexOf("bmp") != -1)
{
jgpEncoder = GetEncoder(ImageFormat.Bmp);
}
else if (originalImagePath.IndexOf("tiff") != -1)
{
jgpEncoder = GetEncoder(ImageFormat.Tiff);
}
else if (originalImagePath.IndexOf("icon") != -1)
{
jgpEncoder = GetEncoder(ImageFormat.Icon);
}
else if (originalImagePath.IndexOf("wmf") != -1)
{
jgpEncoder = GetEncoder(ImageFormat.Wmf);
}
else
{
jgpEncoder = GetEncoder(ImageFormat.Jpeg);
}
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
//保存缩略图
bitmap.Save(thumbnailPath, jgpEncoder, ep);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
/// <summary>
/// 图片格式
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
#endregion
#region 图片裁剪
/// <summary>
/// 裁剪图片并保存
/// </summary>
/// <param name="fileName">源图路径(绝对路径)</param>
/// <param name="newFileName">缩略图路径(绝对路径)</param>
/// <param name="maxWidth">缩略图宽度</param>
/// <param name="maxHeight">缩略图高度</param>
/// <param name="cropWidth">裁剪宽度</param>
/// <param name="cropHeight">裁剪高度</param>
/// <param name="X">X轴</param>
/// <param name="Y">Y轴</param>
public static bool MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y)
{
byte[] imageBytes = File.ReadAllBytes(fileName);
Image originalImage = Image.FromStream(new System.IO.MemoryStream(imageBytes));
Bitmap b = new Bitmap(cropWidth, cropHeight);
try
{
using (Graphics g = Graphics.FromImage(b))
{
//设置高质量插值法
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, cropWidth, cropHeight), X, Y, cropWidth, cropHeight, GraphicsUnit.Pixel);
Image displayImage = new Bitmap(b, maxWidth, maxHeight);
SaveImage(displayImage, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
return true;
}
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
b.Dispose();
}
}
#region 图片裁剪帮助方法
/// <summary>
/// 保存图片
/// </summary>
/// <param name="image">Image 对象</param>
/// <param name="savePath">保存路径</param>
/// <param name="ici">指定格式的编解码参数</param>
private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
{
//设置 原图片 对象的 EncoderParameters 对象
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100));
image.Save(savePath, ici, parameters);
parameters.Dispose();
}
/// <summary>
/// 获取图像编码解码器的所有相关信息
/// </summary>
/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
/// <returns>返回图像编码解码器的所有相关信息</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType)
return ici;
}
return null;
}
/// <summary>
/// 计算新尺寸
/// </summary>
/// <param name="width">原始宽度</param>
/// <param name="height">原始高度</param>
/// <param name="maxWidth">最大新宽度</param>
/// <param name="maxHeight">最大新高度</param>
/// <returns></returns>
private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
{
//此次2012-02-05修改过=================
if (maxWidth <= 0)
maxWidth = width;
if (maxHeight <= 0)
maxHeight = height;
//以上2012-02-05修改过=================
decimal MAX_WIDTH = (decimal)maxWidth;
decimal MAX_HEIGHT = (decimal)maxHeight;
decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;
int newWidth, newHeight;
decimal originalWidth = (decimal)width;
decimal originalHeight = (decimal)height;
if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
{
decimal factor;
// determine the largest factor
if (originalWidth / originalHeight > ASPECT_RATIO)
{
factor = originalWidth / MAX_WIDTH;
newWidth = Convert.ToInt32(originalWidth / factor);
newHeight = Convert.ToInt32(originalHeight / factor);
}
else
{
factor = originalHeight / MAX_HEIGHT;
newWidth = Convert.ToInt32(originalWidth / factor);
newHeight = Convert.ToInt32(originalHeight / factor);
}
}
else
{
newWidth = width;
newHeight = height;
}
return new Size(newWidth, newHeight);
}
/// <summary>
/// 得到图片格式
/// </summary>
/// <param name="name">文件名称</param>
/// <returns></returns>
public static ImageFormat GetFormat(string name)
{
string ext = name.Substring(name.LastIndexOf(".") + 1);
switch (ext.ToLower())
{
case "jpg":
case "jpeg":
return ImageFormat.Jpeg;
case "bmp":
return ImageFormat.Bmp;
case "png":
return ImageFormat.Png;
case "gif":
return ImageFormat.Gif;
default:
return ImageFormat.Jpeg;
}
}
#endregion
#endregion
#region 图片水印
/// <summary>
/// 图片水印处理方法
/// </summary>
/// <param name="path">需要加载水印的图片路径(绝对路径)</param>
/// <param name="waterpath">水印图片(绝对路径)</param>
/// <param name="location">水印位置(传送正确的代码)</param>
public static string ImageWatermark(string path, string waterpath, string location)
{
string kz_name = Path.GetExtension(path);
if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg")
{
DateTime time = DateTime.Now;
string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
Image img = Bitmap.FromFile(path);
Image waterimg = Image.FromFile(waterpath);
Graphics g = Graphics.FromImage(img);
ArrayList loca = GetLocation(location, img, waterimg);
g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), waterimg.Width, waterimg.Height));
waterimg.Dispose();
g.Dispose();
string newpath = Path.GetDirectoryName(path) + filename + kz_name;
img.Save(newpath);
img.Dispose();
File.Copy(newpath, path, true);
if (File.Exists(newpath))
{
File.Delete(newpath);
}
}
return path;
}
/// <summary>
/// 图片水印位置处理方法
/// </summary>
/// <param name="location">水印位置</param>
/// <param name="img">需要添加水印的图片</param>
/// <param name="waterimg">水印图片</param>
private static ArrayList GetLocation(string location, Image img, Image waterimg)
{
ArrayList loca = new ArrayList();
int x = 0;
int y = 0;
if (location == "LT")
{
x = 10;
y = 10;
}
else if (location == "T")
{
x = img.Width / 2 - waterimg.Width / 2;
y = img.Height - waterimg.Height;
}
else if (location == "RT")
{
x = img.Width - waterimg.Width;
y = 10;
}
else if (location == "LC")
{
x = 10;
y = img.Height / 2 - waterimg.Height / 2;
}
else if (location == "C")
{
x = img.Width / 2 - waterimg.Width / 2;
y = img.Height / 2 - waterimg.Height / 2;
}
else if (location == "RC")
{
x = img.Width - waterimg.Width;
y = img.Height / 2 - waterimg.Height / 2;
}
else if (location == "LB")
{
x = 10;
y = img.Height - waterimg.Height;
}
else if (location == "B")
{
x = img.Width / 2 - waterimg.Width / 2;
y = img.Height - waterimg.Height;
}
else
{
x = img.Width - waterimg.Width;
y = img.Height - waterimg.Height;
}
loca.Add(x);
loca.Add(y);
return loca;
}
#endregion
#region 文字水印
/// <summary>
/// 文字水印处理方法
/// </summary>
/// <param name="path">图片路径(绝对路径)</param>
/// <param name="size">字体大小</param>
/// <param name="letter">水印文字</param>
/// <param name="color">颜色</param>
/// <param name="location">水印位置</param>
public static string LetterWatermark(string path, int size, string letter, Color color, string location)
{
#region
string kz_name = Path.GetExtension(path);
if (kz_name == ".jpg" || kz_name == ".bmp" || kz_name == ".jpeg")
{
DateTime time = DateTime.Now;
string filename = "" + time.Year.ToString() + time.Month.ToString() + time.Day.ToString() + time.Hour.ToString() + time.Minute.ToString() + time.Second.ToString() + time.Millisecond.ToString();
Image img = Bitmap.FromFile(path);
Graphics gs = Graphics.FromImage(img);
ArrayList loca = GetLocation(location, img, size, letter.Length);
Font font = new Font("宋体", size);
Brush br = new SolidBrush(color);
gs.DrawString(letter, font, br, float.Parse(loca[0].ToString()), float.Parse(loca[1].ToString()));
gs.Dispose();
string newpath = Path.GetDirectoryName(path) + filename + kz_name;
img.Save(newpath);
img.Dispose();
File.Copy(newpath, path, true);
if (File.Exists(newpath))
{
File.Delete(newpath);
}
}
return path;
#endregion
}
/// <summary>
/// 文字水印位置的方法
/// </summary>
/// <param name="location">位置代码</param>
/// <param name="img">图片对象</param>
/// <param name="width">宽(当水印类型为文字时,传过来的就是字体的大小)</param>
/// <param name="height">高(当水印类型为文字时,传过来的就是字符的长度)</param>
private static ArrayList GetLocation(string location, Image img, int width, int height)
{
#region
ArrayList loca = new ArrayList(); //定义数组存储位置
float x = 10;
float y = 10;
if (location == "LT")
{
loca.Add(x);
loca.Add(y);
}
else if (location == "T")
{
x = img.Width / 2 - (width * height) / 2;
loca.Add(x);
loca.Add(y);
}
else if (location == "RT")
{
x = img.Width - width * height;
}
else if (location == "LC")
{
y = img.Height / 2;
}
else if (location == "C")
{
x = img.Width / 2 - (width * height) / 2;
y = img.Height / 2;
}
else if (location == "RC")
{
x = img.Width - height;
y = img.Height / 2;
}
else if (location == "LB")
{
y = img.Height - width - 5;
}
else if (location == "B")
{
x = img.Width / 2 - (width * height) / 2;
y = img.Height - width - 5;
}
else
{
x = img.Width - width * height;
y = img.Height - width - 5;
}
loca.Add(x);
loca.Add(y);
return loca;
#endregion
}
#endregion
#region 调整光暗
/// <summary>
/// 调整光暗
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
/// <param name="val">增加或减少的光暗值</param>
public Bitmap LDPic(Bitmap mybm, int width, int height, int val)
{
Bitmap bm = new Bitmap(width, height);//初始化一个记录经过处理后的图片对象
int x, y, resultR, resultG, resultB;//x、y是循环次数,后面三个是记录红绿蓝三个值的
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前像素的值
resultR = pixel.R + val;//检查红色值会不会超出[0, 255]
resultG = pixel.G + val;//检查绿色值会不会超出[0, 255]
resultB = pixel.B + val;//检查蓝色值会不会超出[0, 255]
bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB));//绘图
}
}
return bm;
}
#endregion
#region 反色处理
/// <summary>
/// 反色处理
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap RePic(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);//初始化一个记录处理后的图片的对象
int x, y, resultR, resultG, resultB;
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
resultR = 255 - pixel.R;//反红
resultG = 255 - pixel.G;//反绿
resultB = 255 - pixel.B;//反蓝
bm.SetPixel(x, y, Color.FromArgb(resultR, resultG, resultB));//绘图
}
}
return bm;
}
#endregion
#region 浮雕处理
/// <summary>
/// 浮雕处理
/// </summary>
/// <param name="oldBitmap">原始图片</param>
/// <param name="Width">原始图片的长度</param>
/// <param name="Height">原始图片的高度</param>
public Bitmap FD(Bitmap oldBitmap, int Width, int Height)
{
Bitmap newBitmap = new Bitmap(Width, Height);
Color color1, color2;
for (int x = 0; x < Width - 1; x++)
{
for (int y = 0; y < Height - 1; y++)
{
int r = 0, g = 0, b = 0;
color1 = oldBitmap.GetPixel(x, y);
color2 = oldBitmap.GetPixel(x + 1, y + 1);
r = Math.Abs(color1.R - color2.R + 128);
g = Math.Abs(color1.G - color2.G + 128);
b = Math.Abs(color1.B - color2.B + 128);
if (r > 255) r = 255;
if (r < 0) r = 0;
if (g > 255) g = 255;
if (g < 0) g = 0;
if (b > 255) b = 255;
if (b < 0) b = 0;
newBitmap.SetPixel(x, y, Color.FromArgb(r, g, b));
}
}
return newBitmap;
}
#endregion
#region 拉伸图片
/// <summary>
/// 拉伸图片
/// </summary>
/// <param name="bmp">原始图片</param>
/// <param name="newW">新的宽度</param>
/// <param name="newH">新的高度</param>
public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH)
{
try
{
Bitmap bap = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(bap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(bap, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bap.Width, bap.Height), GraphicsUnit.Pixel);
g.Dispose();
return bap;
}
catch
{
return null;
}
}
#endregion
#region 滤色处理
/// <summary>
/// 滤色处理
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap FilPic(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);//初始化一个记录滤色效果的图片对象
int x, y;
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
bm.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B));//绘图
}
}
return bm;
}
#endregion
#region 左右翻转
/// <summary>
/// 左右翻转
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap RevPicLR(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);
int x, y, z; //x,y是循环次数,z是用来记录像素点的x坐标的变化的
Color pixel;
for (y = height - 1; y >= 0; y--)
{
for (x = width - 1, z = 0; x >= 0; x--)
{
pixel = mybm.GetPixel(x, y);//获取当前像素的值
bm.SetPixel(z++, y, Color.FromArgb(pixel.R, pixel.G, pixel.B));//绘图
}
}
return bm;
}
#endregion
#region 上下翻转
/// <summary>
/// 上下翻转
/// </summary>
/// <param name="mybm">原始图片</param>
/// <param name="width">原始图片的长度</param>
/// <param name="height">原始图片的高度</param>
public Bitmap RevPicUD(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);
int x, y, z;
Color pixel;
for (x = 0; x < width; x++)
{
for (y = height - 1, z = 0; y >= 0; y--)
{
pixel = mybm.GetPixel(x, y);//获取当前像素的值
bm.SetPixel(x, z++, Color.FromArgb(pixel.R, pixel.G, pixel.B));//绘图
}
}
return bm;
}
#endregion
#region 压缩图片
/// <summary>
/// 压缩到指定尺寸
/// </summary>
/// <param name="oldfile">原文件</param>
/// <param name="newfile">新文件</param>
public bool Compress(string oldfile, string newfile)
{
return Compress(oldfile, newfile, 100, 125);
}
/// <summary>
/// 压缩指定尺寸,如果写的和图片大家一样表示大小不变,只是把图片压缩下一些
/// </summary>
/// <param name="oldfile">原文件</param>
/// <param name="newfile">新文件</param>
/// <param name="width">长</param>
/// <param name="height">高</param>
public bool Compress(string oldfile, string newfile, int width, int height)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(oldfile);
System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;
Size newSize = new Size(width, height);
Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.FromImage(outBmp);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();
EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 100;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICI = null;
for (int x = 0; x < arrayICI.Length; x++)
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICI = arrayICI[x]; //设置JPEG编码
break;
}
img.Dispose();
if (jpegICI != null) outBmp.Save(newfile, System.Drawing.Imaging.ImageFormat.Jpeg);
outBmp.Dispose();
return true;
}
catch
{
return false;
}
}
#endregion
#region 图片灰度化
public Color Gray(Color c)
{
int rgb = Convert.ToInt32((double)(((0.3 * c.R) + (0.59 * c.G)) + (0.11 * c.B)));
return Color.FromArgb(rgb, rgb, rgb);
}
#endregion
#region 转换为黑白图片
/// <summary>
/// 转换为黑白图片
/// </summary>
/// <param name="mybt">要进行处理的图片</param>
/// <param name="width">图片的长度</param>
/// <param name="height">图片的高度</param>
public Bitmap BWPic(Bitmap mybm, int width, int height)
{
Bitmap bm = new Bitmap(width, height);
int x, y, result; //x,y是循环次数,result是记录处理后的像素值
Color pixel;
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
pixel = mybm.GetPixel(x, y);//获取当前坐标的像素值
result = (pixel.R + pixel.G + pixel.B) / 3;//取红绿蓝三色的平均值
bm.SetPixel(x, y, Color.FromArgb(result, result, result));
}
}
return bm;
}
#endregion
#region 获取图片中的各帧
/// <summary>
/// 获取图片中的各帧
/// </summary>
/// <param name="pPath">图片路径</param>
/// <param name="pSavePath">保存路径</param>
public void GetFrames(string pPath, string pSavedPath)
{
Image gif = Image.FromFile(pPath);
FrameDimension fd = new FrameDimension(gif.FrameDimensionsList[0]);
int count = gif.GetFrameCount(fd); //获取帧数(gif图片可能包含多帧,其它格式图片一般仅一帧)
for (int i = 0; i < count; i++) //以Jpeg格式保存各帧
{
gif.SelectActiveFrame(fd, i);
gif.Save(pSavedPath + "\\frame_" + i + ".jpg", ImageFormat.Jpeg);
}
}
#endregion
#region 下载图片操作
/// <summary>
/// 获取图片标志
/// </summary>
private string[] GetImgTag(string htmlStr)
{
Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] strAry = new string[regObj.Matches(htmlStr).Count];
int i = 0;
foreach (Match matchItem in regObj.Matches(htmlStr))
{
strAry[i] = GetImgUrl(matchItem.Value);
i++;
}
return strAry;
}
/// <summary>
/// 获取图片URL地址
/// </summary>
private string GetImgUrl(string imgTagStr)
{
string str = "";
Regex regObj = new Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match matchItem in regObj.Matches(imgTagStr))
{
str = matchItem.Value;
}
return str;
}
/// <summary>
/// 下载图片到本地
/// </summary>
/// <param name="strHTML">HTML</param>
/// <param name="path">路径</param>
/// <param name="nowyymm">年月</param>
/// <param name="nowdd">日</param>
public string SaveUrlPics(string strHTML, string path)
{
string nowym = DateTime.Now.ToString("yyyy-MM"); //当前年月
string nowdd = DateTime.Now.ToString("dd"); //当天号数
path = path + nowym + "/" + nowdd;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
string[] imgurlAry = GetImgTag(strHTML);
try
{
for (int i = 0; i < imgurlAry.Length; i++)
{
string preStr = System.DateTime.Now.ToString() + "_";
preStr = preStr.Replace("-", "");
preStr = preStr.Replace(":", "");
preStr = preStr.Replace(" ", "");
WebClient wc = new WebClient();
wc.DownloadFile(imgurlAry[i], path + "/" + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
}
}
catch (Exception ex)
{
return ex.Message;
}
return strHTML;
}
#endregion
#region 生成缩略图
/// <summary>
/// 生成缩略图,不超出尺寸,比它小就不截了,不留白,大就缩小到最佳尺寸,主要为手机用
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
/// <param name="isaddwatermark">是否添加水印</param>
/// <param name="imagePosition">水印位置</param>
/// <param name="waterImage">水印图片名称</param>
/// <param name="quality">图片品质</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, bool isaddwatermark, ImagePosition imagePosition, string waterImage = null, int quality = 75)
{
Image originalImage = Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if (originalImage.Width >= towidth && originalImage.Height >= toheight)
{
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
}
else
{
x = (originalImage.Width - towidth) / 2;
y = (originalImage.Height - toheight) / 2;
ow = towidth;
oh = toheight;
}
break;
case "Fit"://不超出尺寸,比它小就不截了,不留白,大就缩小到最佳尺寸,主要为手机用
if (originalImage.Width > towidth && originalImage.Height > toheight)
{
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
toheight = originalImage.Height * width / originalImage.Width;
else
towidth = originalImage.Width * height / originalImage.Height;
}
else if (originalImage.Width > towidth)
{
toheight = originalImage.Height * width / originalImage.Width;
}
else if (originalImage.Height > toheight)
{
towidth = originalImage.Width * height / originalImage.Height;
}
else
{
towidth = originalImage.Width;
toheight = originalImage.Height;
ow = towidth;
oh = toheight;
}
break;
default:
break;
}
//新建一个bmp图片
Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.White);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);
//加图片水印
if (isaddwatermark)
{
if (string.IsNullOrEmpty(waterImage))
waterImage = "watermarker.png";
Image copyImage = System.Drawing.Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, waterImage));
//g.DrawImage(copyImage, new Rectangle(bitmap.Width-copyImage.Width, bitmap.Height-copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
int xPosOfWm;
int yPosOfWm;
int wmHeight = copyImage.Height;
int wmWidth = copyImage.Width;
int phHeight = toheight;
int phWidth = towidth;
switch (imagePosition)
{
case ImagePosition.LeftBottom:
xPosOfWm = 70;
yPosOfWm = phHeight - wmHeight - 70;
break;
case ImagePosition.LeftTop:
xPosOfWm = 70;
yPosOfWm = 0 - 70;
break;
case ImagePosition.RightTop:
xPosOfWm = phWidth - wmWidth - 70;
yPosOfWm = 0 - 70;
break;
case ImagePosition.RigthBottom:
xPosOfWm = phWidth - wmWidth - 70;
yPosOfWm = phHeight - wmHeight - 70;
break;
default:
xPosOfWm = 10;
yPosOfWm = 0;
break;
}
g.DrawImage(copyImage, new Rectangle(xPosOfWm, yPosOfWm, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
}
// 以下代码为保存图片时,设置压缩质量
EncoderParameters encoderParams = new EncoderParameters();
long[] qualityArray = new long[1];
qualityArray[0] = quality;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityArray);
encoderParams.Param[0] = encoderParam;
//获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象.
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICI = null;
for (int i = 0; i < arrayICI.Length; i++)
{
if (arrayICI[i].FormatDescription.Equals("JPEG"))
{
jpegICI = arrayICI[i];
//设置JPEG编码
break;
}
}
try
{
if (jpegICI != null)
{
bitmap.Save(thumbnailPath, jpegICI, encoderParams);
}
else
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch
{
throw;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
#endregion
}
/// <summary>
/// 水印位置
/// </summary>
public enum ImagePosition
{
/// <summary>
/// 默认
/// </summary>
Default = 1,
/// <summary>
/// 左上
/// </summary>
LeftTop = 2,
/// <summary>
/// 左下
/// </summary>
LeftBottom = 3,
/// <summary>
/// 右上
/// </summary>
RightTop = 4,
/// <summary>
/// 右下
/// </summary>
RigthBottom = 5,
//TopMiddle, //顶部居中
//BottomMiddle, //底部居中
//Center //中心
}
评论列表: