图片压缩
程序员文章站
2022-07-06 19:55:51
...
项目中有遇到限制图片大小得特定情况
将图片压缩至100K以下,转为base64输出
// 图片路径
private string getThumImage(string SourceFile)
{
try
{
//检测图片 是否要压缩 《 100k
MemoryStream ms = new MemoryStream();
Image img = Image.FromFile(SourceFile);
img.Save(ms, img.RawFormat);
if (ms.Length / 1024 <= 100)
{
byte[] buffer = new byte[ms.Length];
ms.Position = 0;
ms.Read(buffer, 0, (int)ms.Length);
ms.Close();
return Convert.ToBase64String(buffer);
}
else
{
// MemoryStream newms = new MemoryStream();
byte[] newbuffer = ms.ToArray();
// 压缩到 100 k 以下
string filetype = Path.GetExtension(SourceFile);
// 设置压缩比例
long imageQuality = ms.Length/1024/100;
Bitmap sourceImage = new Bitmap(img);
ImageCodecInfo myImageCodecInfo = GetImgEncoderIfo(filetype);//GetEncoderInfo("image/" + filetype);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
while (newbuffer.Length / 1024 > 100) // 压缩后图片大小扔 大于100k 循环压缩
{
//imageQuality = newbuffer.Length / 1024 / 100;
imageQuality = ConvertType.ToInt64(Math.Ceiling(newbuffer.Length / 1024.0 / 100.0)); // 向上取整
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
myEncoderParameters.Param[0] = myEncoderParameter;
newbuffer = Compress(myEncoderParameters,myImageCodecInfo, sourceImage);
}
return Convert.ToBase64String(newbuffer);
}
}
catch
{
return "";
}
}
压缩图片返回二进制字节:
public byte[] Compress(EncoderParameters myEncoderParameters, ImageCodecInfo myImageCodecInfo, Bitmap sourceImage)
{
try
{
// 防止图片过大 固定压缩未 1920*1080geshi
float xWidth = 1920;// sourceImage.Width;
float yWidth = 1080;// sourceImage.Height;
Bitmap newImage = new Bitmap((int)xWidth, (int)yWidth);
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(sourceImage, 0, 0, xWidth, yWidth );
g.Dispose();
// newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
using (MemoryStream ms = new MemoryStream())
{
newImage.Save(ms, myImageCodecInfo, myEncoderParameters);
byte[] buffer = ms.ToArray();
return buffer;
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 获取图片编码信息
/// </summary>
private ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
// 根据图片后缀(格式) 获取图片编码信息:(.jpg)
private ImageCodecInfo GetImgEncoderIfo(string imgType)
{
try
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i < encoders.Length; i++)
{
if (encoders[i].FilenameExtension.Contains(imgType.ToUpper()))
{
return encoders[i];
}
}
return null;
}
catch
{
return null;
}
}
最后调用 getThumImage 方法 传入图片路径就行
上一篇: vue 笔记(持续更新)