.netCore 图片压缩处理
参考了一些开源的代码,自己加工了一下,相当好用的图片压缩实现。 代码简单,返回的是byte[], 当然也可以直接保存成文件。
图片压缩处理
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
namespace SuperErp.Common
{
public class ImageParam
{
public int Width { get; set; }
public int Height { get; set; }
public int ToWidth { get; set; }
public int ToHeight { get; set; }
public string Mode { get; set; }
}
public class ImageHelper
{
public static byte[] CompressImage(IFormFile file, int toWidth, int toHeight, string mode = "HW")
{
var compressImageBytes = new byte[] { };
//上传文件的byte数组转为Stream
Image img = ReadStreamToImage(file);
//获得图片宽高比例
ImageParam imageParam = new ImageParam() {
Height = img.Height,
Width = img.Width,
ToHeight = toHeight,
ToWidth = toWidth,
Mode = mode
};
//可以按MODE调整宽高
InitImageParameters(imageParam);
//按照新的宽高用画布重新画一张
Bitmap bitmap = DrawImage(img, imageParam);
return GetBitmapBytes(bitmap);
}
private static Image ReadStreamToImage(IFormFile file)
{
var length = (int)file.Length;
var stream = file.OpenReadStream();
var imageBytes = new byte[length];
stream.Read(imageBytes, 0, length);
return Image.FromStream(stream);
}
private static void InitImageParameters(ImageParam imageParam)
{
switch (imageParam.Mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
imageParam.ToHeight = imageParam.Height * imageParam.ToWidth / imageParam.Width;
break;
case "H"://指定高,宽按比例
imageParam.ToWidth = imageParam.Width * imageParam.ToHeight / imageParam.Height;
break;
default:
break;
}
}
private static Bitmap DrawImage(Image img,ImageParam imageParam) {
Bitmap bitmap = new Bitmap(imageParam.ToWidth, imageParam.ToHeight);
Graphics g = Graphics.FromImage(bitmap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(img, new Rectangle(0, 0, imageParam.ToWidth, imageParam.ToHeight), new Rectangle(0, 0, imageParam.Width, imageParam.Height), GraphicsUnit.Pixel);
return bitmap;
}
private static byte[] GetBitmapBytes(Bitmap bitmap)
{
var compressImageBytes = new byte[] { };
using (MemoryStream memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, ImageFormat.Png);
compressImageBytes = new byte[memoryStream.Length];
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.Read(compressImageBytes, 0, Convert.ToInt32(memoryStream.Length));
}
return compressImageBytes;
}
}
}