最近,項目上涉及到了圖像壓縮,發現原有的圖像壓縮功能,雖然保證了圖像的大小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 |
|
效果圖如下:
第一張的大小是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。