4

我有一个方法可以获取输入图像,对图像执行一些操作,然后将其保存到另一个文件中。在最基本的情况下,它会调整图像的大小,但它可以做一些更复杂的事情,比如转换为灰度、量化等,但对于这个问题,我只是试图调整图像的大小而不执行任何其他操作.

它看起来像:

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了,那么它可以正常工作并完美地创建图像文件。

我想知道在创建图像和尝试访问已创建的图像(不是在上面的代码中)的代码中的其他位置之间是否存在某种延迟,该图像锁定了文件,因此它永远不会被写入?会是这样吗?

任何想法还有什么可能发生的?

干杯

编辑:

  • 删除劳埃德指出的多余演员表
4

2 回答 2

3

将位图保存为 png 存在一些历史问题。

使用System.Windows.Media.Imaging.PngBitmapEncoder可以解决这个问题

请参阅 System.Windows.Media.Imaging.PngBitmapEncoder

以及如何:对示例的 PNG 图像进行编码和解码。

于 2013-01-28T14:17:42.573 回答
0

将 Save() 参数与 Stream 而不是文件名一起使用将允许您确保在释放对象之前将文件刷新到磁盘。

但是,我强烈建议您在这里使用服务器安全的图像处理库,因为您正在玩火

于 2013-02-12T13:55:37.770 回答