我正在编写捕获此代码的代码OutOfMemoryException并抛出一个新的,更直观的异常:
/// ...
/// <exception cref="FormatException">The file does not have a valid image format.</exception>
public static Image OpenImage( string filename )
{
try
{
return Image.FromFile( filename );
}
catch( OutOfMemoryException ex )
{
throw new FormatException( "The file does not have a valid image format.", ex );
}
}
Run Code Online (Sandbox Code Playgroud)
此代码是否为其用户所接受,或者是OutOfMemoryException出于特殊原因故意被抛出?
我需要调整 5000 张图像的大小并将它们保存在一个单独的文件夹中。我有一个这样的代码来创建一张图片的调整大小的副本(在互联网上找到):
Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
var destRect = new System.Drawing.Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
Run Code Online (Sandbox Code Playgroud)
我有这个代码,它首先创建所有必要的目录来保存图片,然后开始更改所有图像并将它们保存到新文件夹中。在执行程序的过程中,我的内存开始填满,直到达到~590mb(~1800张图像)的标记,然后抛出OutOfMemoryException错误。
void ResizeAllImages()
{
var files = Directory.GetFiles(ImagesDirectory, "*", SearchOption.AllDirectories);
if …Run Code Online (Sandbox Code Playgroud)