- /*
- * Created by SharpDevelop.
- * User: Edwin
- * Date: 2008-12-18
- * Time: 10:02
- */
- using System;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Drawing.Imaging;
- namespace Edwin.Graphic
- {
- /// <summary>
- /// 产生缩略图的模式.
- /// </summary>
- public enum GraphicMode
- { //着重宽度模式
- EmphasizedWidth = 1,
- //着重高度模式
- EmphasizedHeight= 2,
- //切割模式
- Cut=3,
- //指定模式
- Appointed=4
- }
- /// <summary>
- /// 主要用来产生缩略图.
- /// </summary>
- public class GraphicUtil
- {
- public GraphicUtil()
- {
- }
- public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, GraphicMode mode)
- {
- //----------------------------添加参数校验区-------------------------------//
- //如果需要可以添加识别文件是否存在的方法。(采用正则判断格式和文件流判断存在即可)
- //如果添加,反倒不适合批处理,如下的判断也可删除,全部在外围实在判断.
- if(originalImagePath!=null&&thumbnailPath!=null)
- {
- //防止文件同名
- if(originalImagePath.ToLower().Equals(thumbnailPath.ToLower()))
- {
- return;
- }
- }else
- {
- return;
- }
- //------------------------------END------------------------------------------//
- int makeMode = (int)mode;
- Image image = Image.FromFile(originalImagePath);
- int appointedWidth = width;
- int appointedHeight = height;
- int x = 0;
- int y = 0;
- int originalWidth = image.Width;
- int originalHeight = image.Height;
- //----------------------------模式转化区-------------------------------//
- switch (makeMode)
- {
- case 1:
- appointedWidth = (image.Width * height) / image.Height;;
- break;
- case 2:
- appointedHeight = (image.Height * width) / image.Width;
- break;
- case 3:
- if ((((double) image.Width) / ((double) image.Height)) > (((double) appointedWidth) / ((double) appointedHeight)))
- {
- originalHeight = image.Height;
- originalWidth = (image.Height * appointedWidth) / appointedHeight;
- y = 0;
- x = (image.Width - originalWidth) / 2;
- }
- else
- {
- originalWidth = image.Width;
- originalHeight = (image.Width * height) / appointedWidth;
- x = 0;
- y = (image.Height - originalHeight) / 2;
- }
- break;
- default:
- break;
- }
- //------------------------------END------------------------------------------//
- //----------------------------缩略图生成区-------------------------------//
- Image imageNew = new Bitmap(appointedWidth, appointedHeight);
- Graphics graphics = Graphics.FromImage(imageNew);
- graphics.InterpolationMode = InterpolationMode.High;
- graphics.SmoothingMode =SmoothingMode.HighQuality;
- graphics.Clear(Color.Transparent);
- graphics.DrawImage(image, new Rectangle(0, 0, appointedWidth, appointedHeight), new Rectangle(x, y, originalWidth, originalHeight), GraphicsUnit.Pixel);
- try
- {
- imageNew.Save(thumbnailPath, ImageFormat.Jpeg);
- }
- catch (Exception exception)
- {
- throw exception;
- }
- finally
- {
- image.Dispose();
- imageNew.Dispose();
- graphics.Dispose();
- }
- //------------------------------END------------------------------------------//
- }
- }
- }
生成缩略图
最新推荐文章于 2024-08-13 18:51:22 发布