为什么我的代码在GDI +中抛出一般错误?

时间:2011-07-28 14:38:05

标签: vb.net gdi+

我正在尝试将一批.pngs转换为.jpgs,如this question中所示:

For Each file As String In Directory.EnumerateFiles(path).Where(Function(s) s.EndsWith(".png"))
    Dim newfile As String = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
    Using png As Bitmap = Bitmap.FromFile(file)
        Using jpg As New Bitmap(png.Width, png.Height)
            Using g As Graphics = Graphics.FromImage(jpg)
                g.Clear(Color.FromArgb(255, 212, 208, 200))
                g.DrawImageUnscaled(png, 0, 0)
                jpg.Save(newfile, ImageFormat.Jpeg)
            End Using
       End Using
    End Using
Next

jpg.Save的调用,但在GDI +中出现“一般错误”。最初在最内层的Using语句之外,我按照this answer向内移动了调用,但它没有改变任何内容。我已经验证newfile包含有效路径,并且程序具有对目录的写访问权。我错过了什么?

2 个答案:

答案 0 :(得分:0)

我知道您说的是您确定文件路径,但在此我可以看到您传递给newfile的{​​{1}}具有空值。 我只是用IO.Path.Combine字符串初始化newfile字符串,并成功运行您的代码而没有任何问题:

Path

答案 1 :(得分:0)

我已经尝试过您的代码(用C#重写)并发现了一件事:只有当您尝试将新图像保存在列出PNG的同一目录中时才会发生异常。如果您更改代码以将图像写入其他目录,则代码可以正常工作。

我无法真正解释为什么会发生这种情况(除了Bitmap.FromFile()可能会以某种方式锁定目录)。有很多GDI + Bitmap怪癖。

BTW:我设法修改了我的C#代码,所以它不会抛出异常,我会以类似的方式重写你的VB代码段(我还没有测试过VB代码):

For Each file As String In Directory.EnumerateFiles(path).Where(Function(s) s.EndsWith(".png"))
    Dim newfile As String = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
    Using jpg As New Bitmap(png.Width, png.Height)
        Using g As Graphics = Graphics.FromImage(jpg)
            Using png As Bitmap = Bitmap.FromFile(file)
                g.Clear(Color.FromArgb(255, 212, 208, 200))
                g.DrawImageUnscaled(png, 0, 0)
            End Using

            jpg.Save(newfile, ImageFormat.Jpeg)
       End Using
    End Using
Next

希望它有效。

相关问题