码迷,mamicode.com
首页 > 其他好文 > 详细

压缩图片方法

时间:2017-09-27 13:29:37      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:gen   text   rip   namespace   mode   encoder   pixel   parameter   sha   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Utility
{     
    public static class CompressImage
    {
        public static Bitmap PercentImage(Image srcImage)
        {
            int newW = srcImage.Width < 1130 ? srcImage.Width : 1130;
            int newH = int.Parse(Math.Round(srcImage.Height * (double)newW / srcImage.Width).ToString());
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                g.DrawImage(srcImage, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
                g.Dispose();
                return b;
            }
            catch (Exception)
            {
                return null;
            }
        }

        //将图片按百分比压缩,flag取值1到100,越小压缩比越大

        public static bool YaSuo(Image iSource, string outPath, int flag)
        {
            ImageFormat tFormat = iSource.RawFormat;
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                    iSource.Save(outPath, jpegICIinfo, ep);
                else
                    iSource.Save(outPath, tFormat);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

  

压缩图片方法

标签:gen   text   rip   namespace   mode   encoder   pixel   parameter   sha   

原文地址:http://www.cnblogs.com/sharestone/p/7600852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!