按比例缩小图片

来源:互联网 发布:重庆时时彩组六软件 编辑:程序博客网 时间:2024/05/01 07:45

以前转载过一个,不过发现根本不能压缩,现在重新代码。现在可以定义width和height最大值并按照图片的横或者竖输出。

 public static class ImageHelper
    {
        
/// <summary>
        
/// 按Width或者Height最大值缩小图片,也就是with或这height都不会超过指定的最大值进行缩小
        
/// </summary>
        
/// <param name="srcPictureFilePath">被压缩文件路径</param>
        
/// <param name="tagPicturePath">目标路径</param>
        
/// <param name="maxWidth">width的最大值</param>
        
/// <param name="maxHeight">height的最大值</param>
        public static void ReduceMaxScale(string srcPictureFilePath,
                                          
string tagPicturePath, int maxWidth, int maxHeight)
        {
            Bitmap srcBitmap 
= new Bitmap(srcPictureFilePath);
            
int tagWidth, tagHeight;

            
if (srcBitmap.Width > srcBitmap.Height)
            {
                tagWidth 
= maxWidth;
                
float scale = maxWidth/Convert.ToSingle(srcBitmap.Width);
                tagHeight 
= Convert.ToInt32(scale*srcBitmap.Height);
            }
            
else
            {
                tagHeight 
= maxHeight;
                
float scale = maxHeight/Convert.ToSingle(srcBitmap.Height);
                tagWidth 
= Convert.ToInt32(scale*srcBitmap.Width);
            }
            Bitmap tagBitMap 
= new Bitmap(srcBitmap, tagWidth, tagHeight);
            tagBitMap.Save(tagPicturePath);
        }
    }

 

原创粉丝点击