NPOI EXCEL 插入图片 导致EXCEL 文件过大,可以进行压缩图片在插入
时间: 2024-03-12 16:50:27 浏览: 109
是的,可以进行图片压缩以减小导出的Excel文件大小。在使用NPOI插入图片时,可以先将图片进行压缩,然后再将压缩后的图片插入Excel中。可以使用.NET中的System.Drawing.Bitmap类进行图片压缩,具体实现可以参考以下代码:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
// 压缩图片并返回压缩后的Image对象
private Image CompressImage(Image image, int maxWidth, int maxHeight, long quality)
{
// 对图片进行等比缩放
int width = image.Width;
int height = image.Height;
if (width > maxWidth)
{
height = (int)(height * ((double)maxWidth / width));
width = maxWidth;
}
if (height > maxHeight)
{
width = (int)(width * ((double)maxHeight / height));
height = maxHeight;
}
// 创建压缩后的图片
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, new Rectangle(0, 0, width, height));
// 保存压缩后的图片
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, codecInfo, encoderParams);
Image compressedImage = Image.FromStream(stream);
// 释放资源
graphics.Dispose();
bitmap.Dispose();
stream.Dispose();
return compressedImage;
}
// 获取指定格式的Image编码器
private ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i < encoders.Length; i++)
{
if (encoders[i].MimeType == mimeType)
{
return encoders[i];
}
}
return null;
}
```
在插入图片时,调用上述方法对图片进行压缩,然后再将压缩后的图片插入Excel中即可。
阅读全文