zoukankan      html  css  js  c++  java
  • .NetCore 图片压缩

    using System;
    using System.Drawing;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    namespace 图片压缩
    {
        public class Program
        {
            static void Main(string[] args)
            {
                DirectoryInfo root = new DirectoryInfo(@"D:桌面测试");
    
                foreach (FileInfo f in root.GetFiles())
                {
                    GetImage(f.FullName,f.Name);
                    Console.WriteLine(f.Name);
                }
                Console.WriteLine("Hello World!");
            }
    
            public static void GetImage(string path,string name)
            {
    
                var imageStr = ImageToBase64(path);
    
                var newImageStr = GetImg(imageStr, 1);
                using (var stream = new FileStream($@"D:桌面测试新	u{name}", FileMode.Create))
                {
                    var match = Regex.Match(newImageStr, "data:image/png;base64,([\w\W]*)$");
                    if (match.Success)
                    {
                        newImageStr = match.Groups[1].Value;
                    }
                    var imgByte = Convert.FromBase64String(newImageStr);
                    stream.Write(imgByte, 0, imgByte.Length);
                    stream.Flush();
                }
            }
    
            /// <summary>
            /// Image 转成 base64
            /// </summary>
            /// <param name="filePath"></param>
            public static string ImageToBase64(string filePath)
            {
                Bitmap bmp = new Bitmap(filePath);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, bmp.RawFormat);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
    
            /// <summary>
            /// 图片压缩
            /// </summary>
            /// <param name="imgstr">图片base64</param>
            /// <param name="type">图片类型,默认宽高</param>
            /// <param name="length">图片最大限制</param>
            /// <returns></returns>
            public static string GetImg(string imgstr,int type, int length = 1024 * 1536)
            {
                //1.5MB以内的图片,不做压缩处理
                if (imgstr.Length < length)
                    return imgstr;
                int width = 800, height = 560;
                if (type == 1)
                {
                    width = 1230;
                    height = 870;
                }
                byte[] imgBytes = Convert.FromBase64String(imgstr);
                var stream = new MemoryStream(imgBytes);
    
                var image = Image.FromStream(stream);
                double newWidth, newHeight;
                if (image.Width > image.Height)
                {
                    newWidth = width;
                    newHeight = image.Height * (newWidth / image.Width);
                }
                else
                {
                    newHeight = height;
                    newWidth = (newHeight / image.Height) * image.Width;
                }
                if (newWidth > width)
                {
                    newWidth = width;
                }
                if (newHeight > height)
                {
                    newHeight = height;
                    newWidth = image.Width * (newHeight / image.Height);
                }
                var outStream = new MemoryStream();
                ImgThumbnail.Thumbnail(stream, outStream,Convert.ToInt32(newWidth),Convert.ToInt32(newHeight), 100, ImgThumbnail.ImgThumbnailType.WH);
                var newImageStr = Convert.ToBase64String(outStream.ToArray());
                while (newImageStr.Length>= length)
                {
                    newImageStr= GetImg(newImageStr, type,length);
                }
                return newImageStr;
            }
        }
    }
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Net.Mime;
    using System.Text;
    
    namespace 图片压缩
    {
        public class ImgThumbnail
        {
            #region 枚举
            /// <summary>
            /// 指定缩放类型
            /// </summary>
            public enum ImgThumbnailType
            {
                /// <summary>
                ////// </summary>
                Nothing = 0,
    
    
                /// <summary>
                /// 指定高宽缩放(可能变形)
                /// </summary>
                WH = 1,
    
    
                /// <summary>
                /// 指定宽,高按比例
                /// </summary>
                W = 2,
    
    
                /// <summary>
                /// 指定高,宽按比例
                /// </summary>
                H = 3,
    
    
                /// <summary>
                /// 指定高宽裁减(不变形)
                /// </summary>
                Cut = 4,
    
    
                /// <summary>
                /// 按照宽度成比例缩放后,按照指定的高度进行裁剪
                /// </summary>
                W_HCut = 5,
    
                /// <summary>
                /// 长边优先
                /// </summary>
                W_L = 5,
    
                /// <summary>
                /// 短边优先
                /// </summary>
                W_S = 5,
            }
    
            public enum ImgResize
            {
                /// <summary>
                ////// </summary>
                Nothing = 0,
    
                /// <summary>
                /// 按长边优先
                /// </summary>
                M_lfit = 1,
    
                /// <summary>
                /// 按短边优先
                /// </summary>
                M_mfit = 2,
            }
            #endregion
    
    
            #region 图片压缩
            /// <summary>
            /// 无损压缩图片
            /// </summary>
            /// <param name="sourceFile">原图片</param>
            /// <param name="height">高度</param>
            /// <param name="width"></param>
            /// <param name="quality">压缩质量 1-100</param>
            /// <param name="type">压缩缩放类型</param>
            /// <param name="tFormat"></param>
            /// <returns></returns>
            private static Bitmap Thumbnail(Stream sourceStream, int width, int height, int quality
              , ImgThumbnailType type, out ImageFormat tFormat)
            {
                using (Image iSource = Image.FromStream(sourceStream))
                {
                    tFormat = iSource.RawFormat;
                    //缩放后的宽度和高度
                    int toWidth = width;
                    int toHeight = height;
                    //
                    int x = 0;
                    int y = 0;
                    int oWidth = iSource.Width;
                    int oHeight = iSource.Height;
    
                    if (type == ImgThumbnailType.W_L) type = oWidth > oHeight ? ImgThumbnailType.W : ImgThumbnailType.H;
                    if (type == ImgThumbnailType.W_S) type = oWidth > oHeight ? ImgThumbnailType.H : ImgThumbnailType.W;
    
    
                    switch (type)
                    {
                        case ImgThumbnailType.WH://指定高宽缩放(可能变形)           
                            {
                                break;
                            }
                        case ImgThumbnailType.W://指定宽,高按比例     
                            {
                                toHeight = iSource.Height * width / iSource.Width;
                                break;
                            }
                        case ImgThumbnailType.H://指定高,宽按比例
                            {
                                toWidth = iSource.Width * height / iSource.Height;
                                break;
                            }
                        case ImgThumbnailType.Cut://指定高宽裁减(不变形)     
                            {
                                if (iSource.Width / (double)iSource.Height > toWidth / (double)toHeight)
                                {
                                    oHeight = iSource.Height;
                                    oWidth = iSource.Height * toWidth / toHeight;
                                    y = 0;
                                    x = (iSource.Width - oWidth) / 2;
                                }
                                else
                                {
                                    oWidth = iSource.Width;
                                    oHeight = iSource.Width * height / toWidth;
                                    x = 0;
                                    y = (iSource.Height - oHeight) / 2;
                                }
                                break;
                            }
                        case ImgThumbnailType.W_HCut://按照宽度成比例缩放后,按照指定的高度进行裁剪
                            {
                                toHeight = iSource.Height * width / iSource.Width;
                                if (height < toHeight)
                                {
                                    oHeight = oHeight * height / toHeight;
                                    toHeight = toHeight * height / toHeight;
                                }
                                break;
                            }
                        default:
                            break;
                    }
    
                    Bitmap ob = new Bitmap(toWidth, toHeight);
                    //ImgWaterMark iwm = new ImgWaterMark();
                    //iwm.AddWaterMark(ob, towidth, toheight, "www.***.com");
                    Graphics g = Graphics.FromImage(ob);
                    g.Clear(Color.WhiteSmoke);
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(iSource
                      , new Rectangle(x, y, toWidth, toHeight)
                      , new Rectangle(0, 0, oWidth, oHeight)
                      , GraphicsUnit.Pixel);
                    g.Dispose();
    
                    return ob;
    
                }
            }
    
    
            /// <summary>
            /// 无损压缩图片
            /// </summary>
            /// <param name="sourceStream">原图片文件流</param>
            /// <param name="outStream">压缩后保存到流中</param>
            /// <param name="height">高度</param>
            /// <param name="width"></param>
            /// <param name="quality">压缩质量 1-100</param>
            /// <param name="type">压缩缩放类型</param>
            /// <returns></returns>
            public static bool Thumbnail(Stream sourceStream, Stream outStream, int width, int height, int quality, ImgThumbnailType type)
            {
                ImageFormat tFormat;
                Bitmap ob = Thumbnail(sourceStream, width, height, quality, type, out tFormat);
                //水印
                //ImgWaterMark.AddWaterMark(ob, "www.***.com");
                //以下代码为保存图片时,设置压缩质量
                EncoderParameters ep = new EncoderParameters();
                long[] qy = new long[1] { quality };//设置压缩的比例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 i = 0; i < arrayICI.Length; i++)
                    {
                        if (arrayICI[i].FormatDescription.Equals("JPEG"))
                        {
                            jpegICIinfo = arrayICI[i];
                            break;
                        }
                    }
                    if (jpegICIinfo != null)
                    {
                        ob.Save(outStream, jpegICIinfo, ep);//jpegICIinfo是压缩后的新路径
                    }
                    else
                    {
                        ob.Save(outStream, tFormat);
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    //iSource.Dispose();
    
                    ob.Dispose();
    
                }
            }
    
            /// <summary>
            /// 无损压缩图片
            /// </summary>
            /// <param name="sourceFile">原图片</param>
            /// <param name="targetFile">压缩后保存位置</param>
            /// <param name="height">高度</param>
            /// <param name="width"></param>
            /// <param name="quality">压缩质量 1-100</param>
            /// <param name="type">压缩缩放类型</param>
            /// <returns></returns>
            public static bool Thumbnail(string sourceFile, string targetFile, int width, int height, int quality, ImgThumbnailType type)
            {
                ImageFormat tFormat = null;
                var fileBytes = File.ReadAllBytes(sourceFile);
                var sourceStream = new MemoryStream(fileBytes);
                Bitmap ob = Thumbnail(sourceStream, width, height, quality, type, out tFormat);
                //以下代码为保存图片时,设置压缩质量
                EncoderParameters ep = new EncoderParameters();
                long[] qy = new long[1] { quality };//设置压缩的比例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 i = 0; i < arrayICI.Length; i++)
                    {
                        if (arrayICI[i].FormatDescription.Equals("JPEG"))
                        {
                            jpegICIinfo = arrayICI[i];
                            break;
                        }
                    }
                    if (jpegICIinfo != null)
                    {
                        ob.Save(targetFile, jpegICIinfo, ep);//jpegICIinfo是压缩后的新路径
                    }
                    else
                    {
                        ob.Save(targetFile, tFormat);
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    //iSource.Dispose();
    
                    ob.Dispose();
    
                }
            }
            #endregion
    
    
            #region 生成缩略图
    
            /// <summary>
            /// 生成缩略图
            /// </summary>
            /// <param name="sourceFile">原始图片文件</param>
            /// <param name="quality">质量压缩比</param>
            /// <param name="w"></param>
            /// <param name="h"></param>
            /// <param name="outputFile">输出文件名</param>
            /// <returns>成功返回true,失败则返回false</returns>
            public static bool GetThumImage(string sourceFile, long quality, int w, int h, string outputFile)
            {
                try
                {
                    long imageQuality = quality;
                    Bitmap sourceImage = new Bitmap(sourceFile);
                    ImageCodecInfo myImageCodecInfo = GetEncoder(ImageFormat.Jpeg);
                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);
                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    sourceImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
    
    
                    float xWidth = sourceImage.Width;
                    float yWidth = sourceImage.Height;
                    Bitmap newImage = new Bitmap(w, h);
                    Graphics g = Graphics.FromImage(newImage);
    
                    g.DrawImage(sourceImage, 0, 0, w, h);
                    g.Dispose();
                    newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
    
            private static ImageCodecInfo GetEncoder(ImageFormat format)
            {
    
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.FormatID == format.Guid)
                    {
                        return codec;
                    }
                }
                return null;
            }
            #endregion
    
    
            public static ImgThumbnailType GetThumbnailType(string w, string h, string t, string sourceFile)
            {
                //参数只有一个
                if (w == "0" || h == "0")
                {
                    return w == "0" ? ImgThumbnailType.H : ImgThumbnailType.W;
                }
                else
                {
                    return t == "0" ? ImgThumbnailType.W_L : ImgThumbnailType.W_S;
                }
            }
    
            /// <summary>
            /// 比较原图的高宽大小
            /// </summary>
            /// <param name="w">宽度</param>
            /// <param name="h">高度</param>
            /// <param name="t"></param>
            /// <returns></returns>
            public static int GetImgResize(int w, int h, int t)
            {
                if (w > h) return t == 0 ? w : h;
                return t == 0 ? h : w;
            }
        }
    }
  • 相关阅读:
    关于故事和段子
    SQLserver2008数据库备份和还原问题(还原是必须有完整备份)
    百度文库破解方法
    如何识别病毒,转自百度文库,千辛万苦破解出来的
    20个人艰不拆的事实:知道真相的我眼泪掉下来 T.T
    linux学习网站分享
    个人对于腾讯和优酷的看法
    今天去客户现场的一些感想
    基于 Blazui 的 Blazor 后台管理模板 Blazui.Admin 正式尝鲜
    新手福利!Blazor 从入门到砖家系列教程(你真的可以成为砖家)
  • 原文地址:https://www.cnblogs.com/ShenJA/p/14677364.html
Copyright © 2011-2022 走看看