我正在尝试将一批.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
包含有效路径,并且程序具有对目录的写访问权。我错过了什么?
答案 0 :(得分:0)
我知道您说的是您确定文件路径,但在此我可以看到您传递给newfile
的{{1}}具有空值。
我只是用IO.Path.Combine
字符串初始化newfile
字符串,并成功运行您的代码而没有任何问题:
Path
答案 1 :(得分:0)
我已经尝试过您的代码(用C#重写)并发现了一件事:只有当您尝试将新图像保存在列出PNG的同一目录中时才会发生异常。如果您更改代码以将图像写入其他目录,则代码可以正常工作。
我无法真正解释为什么会发生这种情况(除了Bitmap.FromFile()
可能会以某种方式锁定目录)。有很多GDI + Bitmap
怪癖。
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
希望它有效。