另存为 PNG 时为空文件
本文关键字:文件 PNG 另存为 | 更新日期: 2023-09-27 17:56:15
我有一个方法,它获取输入图像,对图像执行一些操作,然后将其保存到另一个文件中。在最基本的情况下,它会调整图像大小,但它可以做一些更复杂的事情,例如转换为灰度、量化等,但对于这个问题,我只是尝试调整图像大小而不执行任何其他操作。
它看起来像:
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);
这应该打开"图像.png"文件,调整为 300×300,然后将其保存为"输出.png"作为 PNG 文件。但它不起作用 - 创建的文件位于正确的位置,但文件大小为零,并且不包含任何图像。
这似乎也只发生在我传入参数ImageFormat.Png
时;如果我传递ImageFormat.Jpeg
,那么它工作正常并完美地创建图像文件。
我想知道在创建图像和代码中的其他地方尝试访问已创建的图像(不在上面的代码中)之间是否发生了某种延迟,这会锁定文件,因此永远不会写入?会是这样吗?
任何想法还会发生什么?
干杯
编辑:
- 删除劳埃德指出的冗余演员表
将位图另存为 png 存在一些历史问题。
使用System.Windows.Media.Imaging.PngBitmapEncoder
可以解决此问题
请参阅 System.Windows.Media.Imaging.PngBitmapEncoder
以及如何:对示例的 PNG 图像进行编码和解码。
将 Save() 参数与 Stream 而不是文件名一起使用,可以确保在释放对象之前将文件刷新到磁盘。
但是,我强烈建议在这里使用服务器安全的图像处理库,因为您正在玩火。