我有一个方法可以获取输入图像,对图像执行一些操作,然后将其保存到另一个文件中。在最基本的情况下,它会调整图像的大小,但它可以做一些更复杂的事情,比如转换为灰度、量化等,但对于这个问题,我只是试图调整图像的大小而不执行任何其他操作.
它看起来像:
public void SaveImage(string src, string dest, int width, int height, ImageFormat format, bool deleteOriginal, bool quantize, bool convertToGreyscale) {
// Open the source file
Bitmap source = (Bitmap)Image.FromFile(src);
// Check dimensions
if (source.Width < width)
throw new Exception();
if (source.Height < height)
throw new Exception();
// Output image
Bitmap output = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(output)) {
// Resize the image to new dimensions
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, width, height);
}
// Convert to greyscale if supposed to
if (convertToGreyscale) {
output = this.ConvertToGreyscale(output);
}
// Save the image
if (quantize) {
OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
using (var quantized = quantizer.Quantize(output)) {
quantized.Save(dest, format);
}
}
else {
output.Save(dest, format);
}
// Close all the images
output.Dispose();
source.Dispose();
// Delete the original
if (deleteOriginal) {
File.Delete(src);
}
}
然后使用它我会调用类似的东西:imageService.SaveImage("c:\image.png", "c:\output.png", 300, 300, ImageFormat.Png, false, false, false);
这应该会打开“image.png”文件,将其调整为 300×300,然后将其保存为“output.png”作为 PNG 文件。但它不起作用——创建的文件位于正确的位置,但文件大小为零并且根本不包含图像。
这似乎也只在我传入参数时发生ImageFormat.Png
;如果我通过ImageFormat.Jpeg
了,那么它可以正常工作并完美地创建图像文件。
我想知道在创建图像和尝试访问已创建的图像(不是在上面的代码中)的代码中的其他位置之间是否存在某种延迟,该图像锁定了文件,因此它永远不会被写入?会是这样吗?
任何想法还有什么可能发生的?
干杯
编辑:
- 删除劳埃德指出的多余演员表