C# PNG Jpeg图片压缩

接口:

 [HttpPost]
        public HttpResponseMessage UploadImg()
        {
            var result = new BaseResponse<List<ImageDto>>() { Data = new List<ImageDto>() };
            result.Code = 1;
            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection fileCollection = request.Files;
            var apiHost = $"https://{HttpContext.Current.Request.Url.Authority}";

            if (fileCollection.Count > 0)
            {
                //"~/Upload/3m/UserUpload/
                //源文件
                string folderPath = "/Upload/3m/UserUpload/";//文件路径
                string hostFolderPath = HttpContext.Current.Server.MapPath(folderPath);
                if (!Directory.Exists(hostFolderPath))
                {
                    Directory.CreateDirectory(hostFolderPath);
                }


                var list = new List<string>() { "jpg", "jpeg", "png"}; //jpg/jpeg/bmp 
                HttpPostedFile httpPostedFile = fileCollection[0];
                ImageDto imgItem = new ImageDto();
                // 获取文件 不带点
                string fileExtension = httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf('.') + 1).ToLower();
                //string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名 带点

                if (!list.Contains(fileExtension))
                {
                    result.BuildError("上传失败:请上传jpg,jpeg,png格式的图片文件");
                    return Request.CreateResponse<BaseResponse<List<ImageDto>>>(HttpStatusCode.OK, result);
                }

                var newFileName = $"{DateTime.Now:yyMMddhhmmss}{new System.Random().Next(100, 999)}.{fileExtension}";
                //原图
                string filePath = $"{folderPath}{(folderPath.EndsWith("/") ? "" : "/")}{newFileName}";
                string hostFilePath = $"{hostFolderPath}{(hostFolderPath.EndsWith(@"\") ? "" : @"\")}{newFileName}";
                //存储原图
                httpPostedFile.SaveAs(hostFilePath);

                string thumbfilePath = $"{folderPath}{(folderPath.EndsWith("/") ? "" : "/")}thumb_{newFileName}";
                string thumbhostFilePath = $"{hostFolderPath}{(hostFolderPath.EndsWith(@"\") ? "" : @"\")}thumb_{newFileName}";

                if (fileExtension == "jpg" || fileExtension == "jpeg")
                {
                    //生成缩略图
                    ImageToolsB.CompressImage(hostFilePath, thumbhostFilePath);
                }
                else
                {
                    ImageToolsB.CompressionImage(hostFilePath, thumbhostFilePath, 25L);
                }

                if (File.Exists(thumbhostFilePath))
                {
                    if (File.Exists(hostFilePath))
                    {
                        File.Delete(hostFilePath);
                    }

                    var id = _imbBll.Add(new UploadThumbImgEntity()
                    {
                        ImageUrl = thumbfilePath,
                        CreateTime = DateTime.Now
                    });

                    result.Data.Add(new ImageDto()
                    {
                        Id = id,
                        ThumbImg = thumbfilePath,
                    });

                }
            }
            else
            {
                result.Error("获取上传文件失败");
                return Request.CreateResponse<BaseResponse<List<ImageDto>>>(HttpStatusCode.OK, result);
            }

            return Request.CreateResponse<BaseResponse<List<ImageDto>>>(HttpStatusCode.OK, result);
        }

工具方法:

 public class ImageToolsB
    {

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 500, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);
            if (sfsc == true && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return true;
            }
            Image iSource = Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;

            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                iSource.Dispose();

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }


        #region ImageCompress

        /// <summary>
        /// 图片压缩         ImageCompress.CompressionImage(fileSelect,@"d:\",50);
        /// </summary>
        /// <param name="imagePath">图片文件路径</param>
        /// <param name="targetFolder">保存文件夹</param>
        /// <param name="quality">压缩质量</param>
        /// <param name="fileSuffix">压缩后的文件名后缀(防止直接覆盖原文件)</param>
        public static void CompressionImage(string imagePath, string targetFolder, long quality = 100, string fileSuffix = "compress")
        {
            if (!File.Exists(imagePath))
            {
                throw new FileNotFoundException();
            }
            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }
            var fileInfo = new FileInfo(imagePath);
            var fileName = fileInfo.Name.Replace(fileInfo.Extension, "");
            var fileFullName = Path.Combine($"{targetFolder}", $"{fileName}_{fileSuffix}{fileInfo.Extension}");

            var imageByte = CompressionImage(imagePath, quality);
            var ms = new MemoryStream(imageByte);
            var image = Image.FromStream(ms);
            image.Save(fileFullName);
            ms.Close();
            ms.Dispose();
            image.Dispose();
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="imagePath">压缩前图片全路径</param>
        /// <param name="compressfilefullName">压缩后图片全路径</param>
        /// <param name="quality">压缩质量</param>
        public static void CompressionImage(string imagePath, string compressfilefullName, long quality = 100)
        {
            if (!File.Exists(imagePath))
            {
                throw new FileNotFoundException();
            }

            var imageByte = CompressionImage(imagePath, quality);
            var ms = new MemoryStream(imageByte);
            var image = Image.FromStream(ms);
            image.Save(compressfilefullName);
            ms.Close();
            ms.Dispose();
            image.Dispose();
        }

        private static byte[] CompressionImage(string imagePath, long quality)
        {
            using (var fileStream = new FileStream(imagePath, FileMode.Open))
            {
                using (var img = Image.FromStream(fileStream))
                {
                    using (var bitmap = new Bitmap(img))
                    {
                        //var codecInfo = GetEncoder(img.RawFormat);
                        //转成jpg
                        var codecInfo = GetEncoder(ImageFormat.Jpeg);

                        var myEncoder = System.Drawing.Imaging.Encoder.Quality;
                        var myEncoderParameters = new EncoderParameters(1);
                        var myEncoderParameter = new EncoderParameter(myEncoder, quality);
                        myEncoderParameters.Param[0] = myEncoderParameter;
                        using (var ms = new MemoryStream())
                        {
                            bitmap.Save(ms, codecInfo, myEncoderParameters);
                            myEncoderParameters.Dispose();
                            myEncoderParameter.Dispose();
                            return ms.ToArray();
                        }
                    }
                }
            }
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();
            return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
        }
        #endregion


    }

在压缩png时,发现图片文件没有变小,反面变大了,

在网上找方法:C# Bitmap/png转成jpg格式,压缩图片

//转成jpg
var codecInfo = GetEncoder(ImageFormat.Jpeg);

 

string fileExtension = request.fileFullName.Substring(request.fileFullName.LastIndexOf('.') + 1).ToLower();
var fileName = request.fileFullName.Substring(request.fileFullName.LastIndexOf(@"\") + 1);

 

参考:https://www.cnblogs.com/testsec/p/6095729.html    C# Bitmap/png转成jpg格式,压缩图片

https://blog.csdn.net/nodeman/article/details/80661995    c# 无损高质量压缩图片代码

https://www.cnblogs.com/wdw984/p/13112621.html  C#进行图片压缩(对jpg压缩效果最好)

 

posted @ 2021-10-22 17:06  BloggerSb  阅读(945)  评论(0编辑  收藏  举报