现在的位置: 首页 > 综合 > 正文

magicknet

2012年01月08日 ⁄ 综合 ⁄ 共 2598字 ⁄ 字号 评论关闭
使用开源组件MagickNet处理高质量缩略图

     MagickNet是著名的图像处理组件ImageMagick的.NET版本,适用于使用.NET开发的WEB应用或者WINFORM,MagickNet是迄今为止功能最强大、效果最好的开源组件,MagickNet是VC++编写的,可以下载源文件自己编译使用或直接下载已经编译好的DLL,在.NET程序中使用MagickNet是很简单的,首先,在VS2005中添加引用,以下以C#为例来实现缩略图的处理。

    protected void Page_Load(object sender, EventArgs e)
    {
        
string infile = Server.MapPath("7.jpg");
        
string outfile = Server.MapPath("2.jpg");
        MakeThumbnail(infile, outfile, 
7575"Cut");
        Response.Write(
"<img src=\"2.jpg\" />");
    }
    
/**/
    
/// <summary>
    
/// 生成缩略图
    
/// </summary>
    
/// <param name="originalImagePath">源图路径(物理路径)</param>
    
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
    
/// <param name="width">缩略图宽度</param>
    
/// <param name="height">缩略图高度</param>
    
/// <param name="mode">生成缩略图的方式</param>   
    public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        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;
        }

        //使用MagickNet对图片进行处理,首先按指定大小比例对图片进行剪切,然后进行缩放,采用CUT方式
        MagickNet.Image img = new MagickNet.Image(originalImagePath);
        img.Crop(
new System.Drawing.Rectangle(x, y, ow, oh));
        img.Resize(
new System.Drawing.Size(towidth, toheight));
        img.Write(thumbnailPath);
        MagickNet.Magick.Term();
    }

抱歉!评论已关闭.