C#中按指定质量保存图片的实例代码 24位深度

 /// <summary>
        /// 按指定的压缩质量及格式保存图片(微软的Image.Save方法保存到图片压缩质量为75)
        /// </summary>
        /// <param name="sourceImage">要保存的图片的Image对象</param>
        /// <param name="savePath">图片要保存的绝对路径</param>
        /// <param name="imageQualityValue">图片要保存的压缩质量,该参数的值为1至100的整数,数值越大,保存质量越好</param>
        /// <returns>保存成功,返回true;反之,返回false</returns>
        public bool SaveImageForSpecifiedQuality(System.Drawing.Image sourceImage, string savePath, int imageQualityValue)
        {
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParameters = new EncoderParameters();
            EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, imageQualityValue);
            encoderParameters.Param[0] = encoderParameter;
            try
            {
                ImageCodecInfo[] ImageCodecInfoArray = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegImageCodecInfo = null;
                for (int i = 0; i < ImageCodecInfoArray.Length; i++)
                {
                    if (ImageCodecInfoArray[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegImageCodecInfo = ImageCodecInfoArray[i];
                        break;
                    }
                }
                sourceImage.Save(savePath, jpegImageCodecInfo, encoderParameters);
                return true;
            }
            catch
            {
                return false;
            }
        }

你可能感兴趣的:(C#)