【问题标题】:Why does my code throw a generic error in GDI+?为什么我的代码会在 GDI+ 中引发一般错误?
【发布时间】:2011-07-28 14:38:05
【问题描述】:

我正在尝试将一批 .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 包含有效路径,并且程序具有对该目录的写访问权限。我错过了什么?

【问题讨论】:

    标签: vb.net gdi+


    【解决方案1】:

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

    Dim newfile As String = Path
    newfile = IO.Path.Combine(newpath, IO.Path.GetFileNameWithoutExtension(file) & ".jpg")
    

    【讨论】:

    • newpath 是一个常量(不同的)目录,传递给IO.Path.Combine,而不是newfile
    • @Dan:我明白了,问题出在newfile,相信我。供您测试代码。只需将newpath 替换为path,结果是一个新的jepg 文件将添加到与Path 目录相同的目录中。
    • @Dan:还要注意Path.Combine 的行为会根据要组合的字符串而有所不同。例如,将"C:\testing\""tested\" 结合起来会给你一个与"C:\testing\""tested\" 不同的字符串。最后一个字符串上会有"\" ..
    【解决方案2】:

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

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

    顺便说一句:我设法重写了我的 C# 代码,因此它不会引发异常,我将以类似的方式重写你的 VB sn-p(虽然我还没有测试过 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
    

    希望它有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-07
      • 2016-12-02
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      相关资源
      最近更新 更多