C# 压缩图片

第一种:
        private string CompressPictures(FileInfo file)
        {
            Image image = null;
            try
            {
                string fullpath = String.Empty;
                //获取未压缩的图片进行压缩
                if (file!=null&&file.Length>0)
                {
                    if(!file.Name.Contains("_compress"))
                    {
                        //压缩图片
                        image = ImgCompressionHelper.GetPicThumbnail(file.FullName);
                        if (image != null)
                        {
                            //压缩后的图片,图片名称增加_compress
                            string newName = file.Name.Replace(file.Extension, "") + "_compress" + file.Extension;
                            fullpath = file.FullName.Replace(file.Name, newName);
                            image.Save(fullpath);
                            file.Delete();
                        }
                    }
                    else
                    {
                        fullpath = file.FullName;
                    }
                }
                return fullpath;
            }
            catch (Exception ex)
            {
                Global.Logger.Error(file.FullName);
                Global.Logger.Error(ex, "MainViewModel.CompressPictures");
                return "";
            }
            finally
            {
                if (image != null)
                    image.Dispose();
            }
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="sFile">图片路径</param>
        /// <param name="flag">压缩比1-100</param>
        /// <returns>返回图片对象</returns>
        public static Image GetPicThumbnail(string sFile, int flag = 30)
        {
            Image result = null;
            if (sFile != null)
            {
                Image inputImage = Image.FromFile(sFile);
                try
                {
                    MemoryStream imgms = new MemoryStream();
                    var arrayICI = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo jpegICIinfo = arrayICI.Where(w => w.FormatDescription.Contains("JPEG")).FirstOrDefault();
                    if (jpegICIinfo != null)
                    {            //以下代码为保存图片时,设置压缩质量          
                        var ep = new EncoderParameters()
                        {
                            Param = new EncoderParameter[]
                            {
                              new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, new long[1]{ flag})
                            }
                        };
                        inputImage.Save(imgms, jpegICIinfo, ep);
                        result = Image.FromStream(imgms);
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    inputImage.Dispose();
                }
            }
            else
            {
                return result;
            }
        }

第二种:首先项目NuGet搜索nQuant,安装nQuant
 private string CompressPictures1(FileInfo file)
        {
            try
            {
                string fullpath = String.Empty;
                //获取未压缩的图片进行压缩
                if (file != null && file.Length > 0)
                {
                    if (!file.Name.Contains("_compress"))
                    {
                        string newPath = file.FullName;
                        var quantizer = new WuQuantizer();
                        //判断图片是否32位深度
                        using (Bitmap map = new Bitmap(file.FullName))
                        {
                            if(map.PixelFormat !=System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                            {
                                //图片转换为32位深度
                                using (Bitmap map1 = ConvertTo32bpp(map))
                                {
                                    string newName = file.Name.Replace(file.Extension, "") + "_32" + file.Extension;
                                    newPath = file.FullName.Replace(file.Name, newName);
                                    map1.Save(newPath);
                                }
                            }
                        }
                        using (var bitmap = new Bitmap(newPath))
                        {
                            //压缩图片
                            using (var quantized = quantizer.QuantizeImage(bitmap))
                            {
                                string newName = file.Name.Replace(file.Extension, "") + "_compress" + file.Extension;
                                fullpath = file.FullName.Replace(file.Name, newName);
                                quantized.Save(fullpath, ImageFormat.Jpeg);
                            }
                        }
                        File.Delete(file.FullName);
                        File.Delete(newPath);
                    }
                    else
                    {
                        fullpath = file.FullName;
                    }
                }
                return fullpath;
            }
            catch (Exception ex)
            {
                //AsyncLoger.AddErrorLog($"压缩图片:{file.FullName}出错,错误原因:{ex.Message}");
                return "";
            }
        }

        public static Bitmap ConvertTo32bpp(Image img)
        {
            var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            using (var gr = Graphics.FromImage(bmp))
                gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
            return bmp;
        }

  

  

posted @ 2022-08-15 16:58  微笑着微笑  阅读(1512)  评论(0编辑  收藏  举报