如何解决 GDI+ 中的一般错误和内存不足
How to solve Generic error in GDI+ and Out of memory
在 C# 中,我启动了一个线程来查找、裁剪并保存图片中的一些单元格。但是当 运行 抛出异常时:
这是我的代码:
Global.ThreadManager.StartThread(a =>
{
try
{
System.Drawing.Bitmap croppedBitmap = new System.Drawing.Bitmap(this.Path + "image.jpg");
croppedBitmap = croppedBitmap.Clone(
new System.Drawing.Rectangle(
Convert.ToInt32(xCenter - width),
Convert.ToInt32(yCenter - width),
width * 2,
width * 2),
System.Drawing.Imaging.PixelFormat.DontCare
);
if (!File.Exists(Path + "MorphologySperms"))
{
Directory.CreateDirectory(Path + "MorphologySperms");
}
croppedBitmap.Save(Path + "Sperms\" + "sperm_" + i.ToString() + ".jpg");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
};
});
您需要 处理您的图像,您不能依赖垃圾收集器及时找到这些图像并释放非托管 GDI资源,这是一条通往例外的单向街道
还有
ConvertTo
好像有点浪费,有需要就投
- 如果需要合并路径,使用
Path.Combine
- 使用 string interpolation 而不是将字符串加在一起
- 如果您需要转义反斜杠等字符,请使用 Verbatim String Literal @"..."
固定
using (var image = new System.Drawing.Bitmap(this.Path + "image.jpg"))
{
using (var croppedBitmap = image.Clone(new Rectangle((int)xCenter - width, (int)yCenter - width, width * 2, width * 2), PixelFormat.DontCare))
{
// not sure what you are doing here, though it doesnt make sense
if (!File.Exists(Path + "MorphologySperms"))
{
// why are you creating a directory and not using it
Directory.CreateDirectory(Path + "MorphologySperms");
}
// use Path.Combine
var somePath = Path.Combine(path, "Sperms");
croppedBitmap.Save( Path.Combine(somePath, $"sperm_{I}.jpg"));
}
}
也非常值得商榷和怀疑像这样使用clone
在 C# 中,我启动了一个线程来查找、裁剪并保存图片中的一些单元格。但是当 运行 抛出异常时:
这是我的代码:
Global.ThreadManager.StartThread(a =>
{
try
{
System.Drawing.Bitmap croppedBitmap = new System.Drawing.Bitmap(this.Path + "image.jpg");
croppedBitmap = croppedBitmap.Clone(
new System.Drawing.Rectangle(
Convert.ToInt32(xCenter - width),
Convert.ToInt32(yCenter - width),
width * 2,
width * 2),
System.Drawing.Imaging.PixelFormat.DontCare
);
if (!File.Exists(Path + "MorphologySperms"))
{
Directory.CreateDirectory(Path + "MorphologySperms");
}
croppedBitmap.Save(Path + "Sperms\" + "sperm_" + i.ToString() + ".jpg");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
};
});
您需要 处理您的图像,您不能依赖垃圾收集器及时找到这些图像并释放非托管 GDI资源,这是一条通往例外的单向街道
还有
ConvertTo
好像有点浪费,有需要就投- 如果需要合并路径,使用
Path.Combine
- 使用 string interpolation 而不是将字符串加在一起
- 如果您需要转义反斜杠等字符,请使用 Verbatim String Literal @"..."
固定
using (var image = new System.Drawing.Bitmap(this.Path + "image.jpg"))
{
using (var croppedBitmap = image.Clone(new Rectangle((int)xCenter - width, (int)yCenter - width, width * 2, width * 2), PixelFormat.DontCare))
{
// not sure what you are doing here, though it doesnt make sense
if (!File.Exists(Path + "MorphologySperms"))
{
// why are you creating a directory and not using it
Directory.CreateDirectory(Path + "MorphologySperms");
}
// use Path.Combine
var somePath = Path.Combine(path, "Sperms");
croppedBitmap.Save( Path.Combine(somePath, $"sperm_{I}.jpg"));
}
}
也非常值得商榷和怀疑像这样使用clone