C# 生成缩略图的代码

private void GetThumbnailImage(string originalPath, string destPath, int thumbnailWidth, int thumbnailHeight, string mode, int left, int top)
{
    System.Drawing.Image originalImage 
= System.Drawing.Image.FromFile(originalPath);

    
int originalWidth = originalImage.Width;
    
int originalHeight = originalImage.Height;

    
switch(mode)
    {
        
case "WH"://指定宽高缩放(可能变形)
            break;
        
case "W"://指定宽,高按比例
            thumbnailHeight = Convert.ToInt32(originalHeight*((double)thumbnailWidth/originalWidth));
            
break;
        
case "H"://指定高,宽按比例
            thumbnailWidth = Convert.ToInt32(originalWidth*((double)thumbnailHeight/originalHeight));
            
break;
        
case "Cut"://指定宽高剪切,不变形
            originalWidth = thumbnailWidth;
            originalHeight 
= thumbnailHeight;
            
break;
    }

    
//新建一个bmp图片
    System.Drawing.Bitmap bitmapX = new Bitmap(thumbnailWidth, thumbnailHeight);

    
//新建一个画板
    System.Drawing.Graphics graphicsX = System.Drawing.Graphics.FromImage(bitmapX);

    
//设置高质量插值法
    graphicsX.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

    
//设置高质量,低速度呈现平滑程度
    graphicsX.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

    
//清空画布并以透明背景色填充
    graphicsX.Clear(System.Drawing.Color.Transparent);

    
//在指定位置并且按指定大小绘制原图片的指定部分
    graphicsX.DrawImage(originalImage, new System.Drawing.Rectangle(00, thumbnailWidth, thumbnailHeight), new System.Drawing.Rectangle(left, top, originalWidth, originalHeight), System.Drawing.GraphicsUnit.Pixel);

    
try
    {
        bitmapX.Save(destPath,System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    
catch(Exception ex)
    {
        
throw ex;
    }
    
finally
    {
        originalImage.Dispose();
        bitmapX.Dispose();
        graphicsX.Dispose();
    }
}

要得到Image不必保存到文件
uploadFile.PostedFile.SaveAs(path);
System.Drawing.Image imageX = System.Drawing.Image.FromFile(path);
只要这样
imageX = Image.FromStream(uploadFile.PostedFile.InputStream);

要得到Image同样不必保存到文件
bitmapX.Save(destPath, ImageFormat.Jpeg);
imageX = System.Drawing.Image.FromFile(destPath);
只要这样
imageX = (Image)bitmapX;
Bitmap是继承自Image的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值