C# 减少任何图像大小 计划

C# 减少任何图像大小 计划,c#,asp.net,image,image-processing,image-size,C#,Asp.net,Image,Image Processing,Image Size,我需要减少图像大小,同时保持一些质量。 但是,我接受GIF、JPEG、JPG和PNG 现状 上传的图像功能齐全,我已经能够成功地缩放其宽度和/或高度 我找到了一个,这给了我一个非常好的代码示例: Image myImage = //... load the image somehow //以50%的质量保存图像 SaveJpeg(destImagePath,myImage,50); //加上这个! 使用系统、绘图、成像 /// <summa

我需要减少图像大小,同时保持一些质量。 但是,我接受GIF、JPEG、JPG和PNG


现状 上传的图像功能齐全,我已经能够成功地缩放其宽度和/或高度

我找到了一个,这给了我一个非常好的代码示例:

Image myImage = //... load the image somehow 
//以50%的质量保存图像 SaveJpeg(destImagePath,myImage,50); //加上这个! 使用系统、绘图、成像

                      /// <summary> 
    /// Saves an image as a jpeg image, with the given quality 
    /// </summary> 
    /// <param name="path">Path to which the image would be saved.</param> 
    // <param name="quality">An integer from 0 to 100, with 100 being the 
    /// highest quality</param> 
    public static void SaveJpeg (string path, Image img, int quality) 
    { 
        if (quality<0  ||  quality>100) 
            throw new ArgumentOutOfRangeException("quality must be between 0 and 100."); 


        // Encoder parameter for image quality 
        EncoderParameter qualityParam = 
            new EncoderParameter (Encoder.Quality, quality); 
        // Jpeg image codec 
        ImageCodecInfo   jpegCodec = GetEncoderInfo("image/jpeg"); 

        EncoderParameters encoderParams = new EncoderParameters(1); 
        encoderParams.Param[0] = qualityParam; 

        img.Save (path, jpegCodec, encoderParams); 
    } 

    /// <summary> 
    /// Returns the image codec with the given mime type 
    /// </summary> 
    private static ImageCodecInfo GetEncoderInfo(string mimeType) 
    { 
        // Get image codecs for all image formats 
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); 

        // Find the correct image codec 
        for(int i=0; i<codecs.Length; i++) 
            if(codecs[i].MimeType == mimeType) 
                return codecs[i]; 
        return null; 
    } 
//
///将图像保存为具有给定质量的jpeg图像
///  
///图像将保存到的路径。
//0到100之间的整数,其中100是
///最高质量
公共静态void SaveJpeg(字符串路径、图像img、整数质量)
{ 
if(质量100)
抛出新ArgumentOutOfRangeException(“质量必须介于0和100之间”);
//用于图像质量的编码器参数
编码器参数qualityParam=
新编码器参数(编码器、质量、质量);
//Jpeg图像编解码器
ImageCodecInfo jpegCodec=GetEncoderInfo(“图像/jpeg”);
EncoderParameters encoderParams=新的EncoderParameters(1);
encoderParams.Param[0]=qualityParam;
保存(路径、JPEG编解码器、编码器参数);
} 
///  
///返回具有给定mime类型的图像编解码器
///  
私有静态ImageCodeInfo GetEncoderInfo(字符串mimeType)
{ 
//获取所有图像格式的图像编解码器
ImageCodecInfo[]codecs=ImageCodecInfo.GetImageEncoders();
//找到正确的图像编解码器
对于(int i=0;i首先,JPEG使用“有损”压缩算法,这就是为什么可以调整质量。质量越低,压缩效果越好,但数据丢失率越高。此外,还应意识到JPEG格式是为类似照片的图像设计的,将JPEG应用于其他类型的图像可能会令人失望(谷歌)“jpeg伪影”)

PNG和GIF是无损的,因此它们不能支持质量参数。这并不是说你不能从它们中获得更好的压缩效果-有各种各样的工具可以减小PNG的大小(pngcrush、punypng等),但是这些工具(大部分)工作方式与JPEG压缩器完全不同。需要注意的是,GIF支持比PNG更小的调色板,最多只能支持256种颜色

因此,请按顺序回答您的问题:

  • 无法进行真正的比较,因为JPEG压缩有一个折衷,而PNG和GIF压缩没有,折衷的程度取决于图像的类型。也就是说,JPEG通常会提供更好的压缩,但如果图像不是照片,结果会明显变差

  • 你的JPEG代码很好。谷歌搜索C#-兼容PNG的工具

  • 你需要尝试你期望的图像类型


  • 您可能想阅读我的文章。它涵盖了您的4个问题中的3个。

    我们可以通过不同的方式来实现这一点

    最好的方法之一是将所有图像转换为jpeg格式,因为它将以较小的大小提供更好的清晰度,在这种情况下,我们不需要更改特定图像的任何高度或宽度

    方法1:将所有图像转换为jpeg(无需额外压缩)

    方法2:通过更改图像的高度和宽度(无jpeg转换)

    CommonConstant.CS

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace EmptyDemo.compression
    {
    #region[Directive]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    #endregion[Directive]
    
    /// <summary>
    /// This class is used to get the constants
    /// </summary>
    public class CommonConstant
    {
        public const string JPEG = ".jpeg";
        public const string PNG = ".png";
        public const string JPG = ".jpg";
        public const string BTM = ".btm";
    }
    }
    

    我使用同样的概念来调整图片的大小,而不只是通过改变比例因子来降低质量。在社交网站上传图片后,他们会缩小图片的大小,但在看到我试图写这篇文章后,质量将是相同的

    using System.Drawing.Imaging;
    using System.Drawing;
    
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            VaryQualityLevel();
        }
        private void VaryQualityLevel()
        {
            Bitmap bmp1 = new Bitmap(Server.MapPath("test2.png"));
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder =System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            bmp1.Save(Server.MapPath("~/Images/1.jpg"), jgpEncoder, myEncoderParameters);
            //myEncoderParameter = new EncoderParameter(myEncoder, 75L);
            //myEncoderParameters.Param[0] = myEncoderParameter;
            //bmp1.Save(Server.MapPath("~/Images/2.jpg"), jgpEncoder, myEncoderParameters);
    
        }
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }
    

    GIF和PNG通过减少颜色进行压缩。对于Photoshot来说,颜色信息的丢失是非常明显的。是的,我不想减少像素深度,这可能是有效的,但也可能是明显的。我在考虑更多的是使用不同的gzip压缩级别。但是你是对的,这种技术要么非常有效,要么无法接受表,具体取决于输入。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace EmptyDemo.compression
    {
    #region[Directive]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    #endregion[Directive]
    
    /// <summary>
    /// This class is used to compress the image to
    /// provided size
    /// </summary>
    public class ImageCompress
    {
        #region[PrivateData]
        private static volatile ImageCompress imageCompress;
        private Bitmap bitmap;
        private int width;
        private int height;
        private Image img;
        #endregion[Privatedata]
    
        #region[Constructor]
        /// <summary>
        /// It is used to restrict to create the instance of the      ImageCompress
        /// </summary>
        private ImageCompress()
        {
        }
        #endregion[Constructor]
    
        #region[Poperties]
        /// <summary>
        /// Gets ImageCompress object
        /// </summary>
        public static ImageCompress GetImageCompressObject
        {
            get
            {
                if (imageCompress == null)
                {
                    imageCompress = new ImageCompress();
                }
                return imageCompress;
            }
        }
    
        /// <summary>
        /// Gets or sets Width
        /// </summary>
        public int Height
        {
            get { return height; }
            set { height = value; }
        }
    
        /// <summary>
        /// Gets or sets Width
        /// </summary>
        public int Width
        {
            get { return width; }
            set { width = value; }
        }
    
        /// <summary>
        /// Gets or sets Image
        /// </summary>
        public Bitmap GetImage
        {
            get { return bitmap; }
            set { bitmap = value; }
        }
        #endregion[Poperties]
    
        #region[PublicFunction]
        /// <summary>
        /// This function is used to save the image
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="path"></param>
        public void Save(string fileName, string path)
        {
            if (ISValidFileType(fileName))
            {
                string pathaname = path + @"\" + fileName;
                save(pathaname, 60);
            }
        }
        #endregion[PublicFunction]
    
        #region[PrivateData]
        /// <summary>
        /// This function is use to compress the image to
        /// predefine size
        /// </summary>
        /// <returns>return bitmap in compress size</returns>
        private Image CompressImage()
        {
            if (GetImage != null)
            {
                Width = (Width == 0) ? GetImage.Width : Width;
                Height = (Height == 0) ? GetImage.Height : Height;
                Bitmap newBitmap = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
                newBitmap = bitmap;
                newBitmap.SetResolution(80, 80);
                return newBitmap.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
            }
            else
            {
                throw new Exception("Please provide bitmap");
            }
        }
    
        /// <summary>
        /// This function is used to check the file Type
        /// </summary>
        /// <param name="fileName">String data type:contain the file name</param>
        /// <returns>true or false on the file extention</returns>
        private bool ISValidFileType(string fileName)
        {
            bool isValidExt = false;
            string fileExt = Path.GetExtension(fileName);
            switch (fileExt.ToLower())
            {
                case CommonConstant.JPEG:
                case CommonConstant.BTM:
                case CommonConstant.JPG:
                case CommonConstant.PNG:
                    isValidExt = true;
                    break;
            }
            return isValidExt;
        }
    
        /// <summary>
        /// This function is used to get the imageCode info
        /// on the basis of mimeType
        /// </summary>
        /// <param name="mimeType">string data type</param>
        /// <returns>ImageCodecInfo data type</returns>
        private ImageCodecInfo GetImageCoeInfo(string mimeType)
        {
            ImageCodecInfo[] codes = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < codes.Length; i++)
            {
                if (codes[i].MimeType == mimeType)
                {
                    return codes[i];
                }
            }
            return null;
        }
        /// <summary>
        /// this function is used to save the image into a
        /// given path
        /// </summary>
        /// <param name="path">string data type</param>
        /// <param name="quality">int data type</param>
        private void save(string path, int quality)
        {
            img = CompressImage();
            ////Setting the quality of the picture
            EncoderParameter qualityParam =
                new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            ////Seting the format to save
            ImageCodecInfo imageCodec = GetImageCoeInfo("image/jpeg");
            ////Used to contain the poarameters of the quality
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = qualityParam;
            ////Used to save the image to a  given path
            img.Save(path, imageCodec, parameters);
        }
        #endregion[PrivateData]
    }
    }
    
        [WebMethod]
        public void UploadFile()
         {
             if (HttpContext.Current.Request.Files.AllKeys.Any())
             {
                 // Get the uploaded image from the Files collection
                 var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
                 if (httpPostedFile != null)
                 {
                     ImageCompress imgCompress = ImageCompress.GetImageCompressObject;
                     imgCompress.GetImage = new System.Drawing.Bitmap(httpPostedFile.InputStream);
                     imgCompress.Height = 260;
                     imgCompress.Width = 358;
                     //imgCompress.Save(httpPostedFile.FileName, @"C:\Documents and Settings\Rasmi\My Documents\Visual Studio2008\WebSites\compressImageFile\Logo");
                     imgCompress.Save(httpPostedFile.FileName, HttpContext.Current.Server.MapPath("~/Download/"));
    
                 }
             }
         }
    
    using System.Drawing.Imaging;
    using System.Drawing;
    
    public partial class Default3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            VaryQualityLevel();
        }
        private void VaryQualityLevel()
        {
            Bitmap bmp1 = new Bitmap(Server.MapPath("test2.png"));
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            System.Drawing.Imaging.Encoder myEncoder =System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            bmp1.Save(Server.MapPath("~/Images/1.jpg"), jgpEncoder, myEncoderParameters);
            //myEncoderParameter = new EncoderParameter(myEncoder, 75L);
            //myEncoderParameters.Param[0] = myEncoderParameter;
            //bmp1.Save(Server.MapPath("~/Images/2.jpg"), jgpEncoder, myEncoderParameters);
    
        }
        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }