C#无损高质量压缩图片实现代码

2024-06-11 21:32

本文主要是介绍C#无损高质量压缩图片实现代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近,项目上涉及到了图像压缩,发现原有的图像压缩功能,虽然保证了图像的大小300K以内,但是压缩后的图像看的不在清晰,并且,限定了图片的Height或者是Width。

在CSDN上看到了一个压缩算法:C#无损高质量压缩图片代码

进过测试这个算法,发现,将原始图像的大小进行对半处理,然后迭代跳转压缩质量参数,可以得到不错的效果。

修改后的算法如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

/// <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 = 300, bool sfsc = true)

{

Image iSource = Image.FromFile(sFile);

ImageFormat tFormat = iSource.RawFormat;

//如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true

FileInfo firstFileInfo = new FileInfo(sFile);

if (sfsc == true && firstFileInfo.Length < size * 1024)

{

firstFileInfo.CopyTo(dFile);

return true;

}

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);

}

return true;

}

catch

{

return false;

}

finally

{

iSource.Dispose();

ob.Dispose();

}

}

效果图如下:

第一张的大小是2.82M,尺寸是3680*4640。

 

第二张的大小是274KB,尺寸是1740*2320,清晰度方面还是不错的。

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

 

 

 

/// <summary>

        /// 图像缩略图处理

        /// </summary>

        /// <param name="bytes">图像源数据</param>

        /// <param name="compression">压缩质量 1-100</param>

        /// <param name="thumbWidth">缩略图的宽</param>

        /// <param name="thumbHeight">缩略图的高</param>

        /// <returns></returns>

        public static byte[] ConvertToThumbnail(byte[] bytes, int compression = 100, int thumbWidth = 0, int thumbHeight = 0)

        {

            byte[] bs = null;

 

            try

            {

                if (bytes != null)

                {

                    using (MemoryStream ms = new MemoryStream(bytes))

                    {

                        using (Bitmap srcimg = new Bitmap(ms))

                        {

                            if (thumbWidth == 0 && thumbHeight == 0)

                            {

                                thumbWidth = srcimg.Width;

                                thumbHeight = srcimg.Height;

                            }

                            using (Bitmap dstimg = new Bitmap(thumbWidth, thumbHeight))//图片压缩质量

                            {

                                //从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。

                                using (Graphics gr = Graphics.FromImage(dstimg))

                                {

                                    //把原始图像绘制成上面所设置宽高的缩小图

                                    Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight);

                                    gr.Clear(Color.WhiteSmoke);

                                    gr.CompositingQuality = CompositingQuality.HighQuality;

                                    gr.SmoothingMode = SmoothingMode.HighQuality;

                                    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

                                    gr.DrawImage(srcimg, rectDestination, 0, 0, srcimg.Width, srcimg.Height, GraphicsUnit.Pixel);

 

                                    EncoderParameters ep = new EncoderParameters(1);

                                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression);//设置压缩的比例1-100

                                    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                                    ImageCodecInfo jpegICIinfo = arrayICI.FirstOrDefault(t => t.FormatID == System.Drawing.Imaging.ImageFormat.Png.Guid);

                                    using (MemoryStream dstms = new MemoryStream())

                                    {

                                        if (jpegICIinfo != null)

                                        {

                                            dstimg.Save(dstms, jpegICIinfo, ep);

                                        }

                                        else

                                        {

                                            dstimg.Save(dstms, System.Drawing.Imaging.ImageFormat.Png);//保存到内存里

                                        }

                                        bs = new Byte[dstms.Length];

                                        dstms.Position = 0;

                                        dstms.Read(bs, 0, bs.Length);

                                    }

                                }

                            }

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), string.Concat("ConvertToThumbnail error.", thumbWidth, " ", thumbHeight));

            }

            return bs;

        }

 

有时候需要一些图片,但是太大了,又有限制,所以想到如何把一张图片的内存大小给缩小,这样就OK了。

1.代码如下:

借鉴:https://docs.microsoft.com/zh-cn/dotnet/api/system.drawing.imaging.encoderparameter?view=netframework-4.6

using System;
using System.Drawing;
using System.Drawing.Imaging;
//这里面有示例文档代码
//https://docs.microsoft.com/zh-cn/dotnet/api/system.drawing.imaging.encoderparameter?view=netframework-4.6
namespace WindowsFormsApp1 {
    class MyTool {
        //根据原图,得到压缩图片并保存在桌面,返回压缩图路径
        public static String compressImage(String  bmpPath , int quality) {
            //原图路径
            Bitmap bmp = new Bitmap(bmpPath);
            ImageCodecInfo codecInfo = GetEncoder(bmp.RawFormat); //图片编解码信息
            System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters encoderParameters = new EncoderParameters(1);
            EncoderParameter encoderParameter = new EncoderParameter(encoder , quality);
            encoderParameters.Param[0] = encoderParameter; //编码器参数
            //压缩图路径
            ImageFormat format = bmp.RawFormat;
            String newFilePath = String.Empty; //压缩图所在路径
            // Guid.NewGuid().ToString()
            //GUID 是一个 128 位整数 (16 个字节),它可用于跨所有计算机和网络中,任何唯一标识符是必需的。 此类标识符具有重复的可能性非常小
            String deskPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (format.Equals(ImageFormat.Jpeg)) {
                newFilePath = deskPath + @"\" + Guid.NewGuid().ToString() + ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png)) {
                newFilePath = deskPath + @"\" + Guid.NewGuid().ToString() + ".png";
            }
            else if (format.Equals(ImageFormat.Bmp)) {
                newFilePath = deskPath + @"\" + Guid.NewGuid().ToString() + ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif)) {
                newFilePath = deskPath + @"\" + Guid.NewGuid().ToString() + ".gif";
            }
            else if (format.Equals(ImageFormat.Icon)) {
                newFilePath = deskPath + @"\" + Guid.NewGuid().ToString() + ".icon";
            }
            else {
                newFilePath = deskPath + @"\" + Guid.NewGuid().ToString() + ".jpg";
            }
            bmp.Save(newFilePath , codecInfo , encoderParameters); //保存压缩图
            return newFilePath; //返回压缩图路径
        }
 
        private static ImageCodecInfo GetEncoder(ImageFormat rawFormat) {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs) {
                if (codec.FormatID == rawFormat.Guid) {
                    return codec;
                }
            }
            return null;
        }
    }
}
然后调用:

private void button1_Click_1(object sender, EventArgs e) {
            using (OpenFileDialog ofd = new OpenFileDialog()) {
                ofd.Filter = "图片|*.jpg;*.png;*.gif;*.jpeg;*.bmp";
                if (ofd.ShowDialog() == DialogResult.OK) {
                    String b = MyTool.compressImage(ofd.FileName , 50);
                }
            }
        }
2.结果

我试了把一张大于2M的图片压缩成了400多KB。
 

 

这篇关于C#无损高质量压缩图片实现代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1052327

相关文章

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

在.NET平台使用C#为PDF添加各种类型的表单域的方法

《在.NET平台使用C#为PDF添加各种类型的表单域的方法》在日常办公系统开发中,涉及PDF处理相关的开发时,生成可填写的PDF表单是一种常见需求,与静态PDF不同,带有**表单域的文档支持用户直接在... 目录引言使用 PdfTextBoxField 添加文本输入域使用 PdfComboBoxField

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

C#如何调用C++库

《C#如何调用C++库》:本文主要介绍C#如何调用C++库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录方法一:使用P/Invoke1. 导出C++函数2. 定义P/Invoke签名3. 调用C++函数方法二:使用C++/CLI作为桥接1. 创建C++/CL

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1