优化代码,使用using块 参考 public bool SaveCheckPicture(string path, string fileName, Image img, int dpi = 600, int maxWidth = 0, int maxHeight = 0,out string msg ) { msg = string.Empty; try { // 计算缩放比例 float scale = (float)dpi / img.HorizontalResolution; // 计算缩放后的尺寸 int width = (int)(img.Width * scale); int height = (int)(img.Height * scale); // 如果指定了最大宽度或最大高度,则按比例缩放 //if (maxWidth > 0 && width > maxWidth) //{ // height = (int)(height * ((float)maxWidth / width)); // width = maxWidth; //} //if (maxHeight > 0 && height > maxHeight) //{ // width = (int)(width * ((float)maxHeight / height)); // height = maxHeight; //} // 创建缩放后的位图 Bitmap bmp = new Bitmap(width, height); // 设置位图的DPI bmp.SetResolution(dpi, dpi); // 创建绘图对象 Graphics g = Graphics.FromImage(bmp); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // 绘制缩放后的图片 g.DrawImage(img, new Rectangle(0, 0, width, height)); // 保存缩放后的图片 //bmp.Save(Path.Combine(path, fileName), System.Drawing.Imaging.ImageFormat.Jpeg); MemoryStream stream = new MemoryStream(); bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] data = stream.ToArray(); // 释放资源 stream.Dispose(); g.Dispose(); bmp.Dispose(); img.Dispose(); return SaveCheckPicture(path, fileName, data, out msg); // return true; } catch (Exception ex) { msg = ex.ToString(); return false; } }
时间: 2024-02-05 08:05:06 浏览: 102
可以使用 using 块来自动释放资源,同时对代码进行优化,如下所示:
```
public bool SaveCheckPicture(string path, string fileName, Image img, int dpi = 600, int maxWidth = 0, int maxHeight = 0, out string msg)
{
msg = string.Empty;
try
{
// 计算缩放比例
float scale = (float)dpi / img.HorizontalResolution;
// 计算缩放后的尺寸
int width = (int)(img.Width * scale);
int height = (int)(img.Height * scale);
// 如果指定了最大宽度或最大高度,则按比例缩放
//if (maxWidth > 0 && width > maxWidth)
//{
// height = (int)(height * ((float)maxWidth / width));
// width = maxWidth;
//}
//if (maxHeight > 0 && height > maxHeight)
//{
// width = (int)(width * ((float)maxHeight / height));
// height = maxHeight;
//}
// 创建缩放后的位图
using (Bitmap bmp = new Bitmap(width, height))
{
// 设置位图的DPI
bmp.SetResolution(dpi, dpi);
// 创建绘图对象
using (Graphics g = Graphics.FromImage(bmp))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// 绘制缩放后的图片
g.DrawImage(img, new Rectangle(0, 0, width, height));
// 保存缩放后的图片
using (MemoryStream stream = new MemoryStream())
{
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] data = stream.ToArray();
// 释放资源
img.Dispose();
return SaveCheckPicture(path, fileName, data, out msg);
}
}
}
}
catch (Exception ex)
{
msg = ex.ToString();
return false;
}
}
```
这样可以自动释放资源,避免手动释放时出现异常。
阅读全文