【问题标题】:When converting a .tif to a .jpg, I get the error "a generic error occurred in GDI+"将 .tif 转换为 .jpg 时,出现错误“GDI+ 中发生一般错误”
【发布时间】:2015-10-06 22:56:24
【问题描述】:

我正在尝试将图像从 .tif 转换为 .jpg,但遇到了错误:

GDI+ 中出现一般错误。

我不知道问题是什么,而且我很难在网上找到解决方案。有人可以帮忙吗?

错误发生在bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);

public static void ConvertTiffToJpeg(string tiffFile, string destinationDirectory)
            {
                using (Image imageFile = Image.FromFile(tiffFile))
                {
                    FrameDimension frameDimensions = new FrameDimension(
                        imageFile.FrameDimensionsList[0]);

                    // Gets the number of pages from the tiff image (if multipage) 
                    int frameNum = imageFile.GetFrameCount(frameDimensions);
                    string[] jpegPaths = new string[frameNum];

                    for (int frame = 0; frame < frameNum; frame++)
                    {
                        // Selects one frame at a time and save as jpeg. 
                        imageFile.SelectActiveFrame(frameDimensions, frame);
                        using (Bitmap bmp = new Bitmap(imageFile))
                        {
                            jpegPaths[frame] = String.Format("{0}\\{1}.jpg",
                                //Path.GetDirectoryName(tiffFile),
                                destinationDirectory,
                                Path.GetFileNameWithoutExtension(tiffFile),
                                frame);

                            bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
                        }
                    }
                }
            } 

【问题讨论】:

    标签: c# bitmap jpeg tiff


    【解决方案1】:

    该错误几乎肯定会发生,因为您试图将图像保存到不存在的目录中。如果该目录尚不存在,则需要创建该目录 - Bitmap.Save 不会自动执行此操作。您可能应该首先检查Directory.Exists 以确保您不会无意中覆盖文件(提示用户覆盖或输入新名称?)。

    最重要的是,jpegPaths[frame] 的输出,如所写,将看起来像 C:\temp\inputfile.jpg,而不是 C:\temp\inputfile\1.jpg,这可能是您想要的。要解决此问题,您需要这样做:jpegPaths[frame] = String.Format("{0}\\{1}\\{2}.jpg",或者如果您不想使用另一个子目录,则可能是 "{0}\\{1}_{2}.jpg"。同样,请确保在尝试使用之前创建了 inputfile 目录。

    最后,没有必要将imageFile 框架加载到它自己的Bitmap 中——你可以调用imageFile.Save(jpegPaths[frame], ImageFormat.Jpeg),一旦你解决了其他问题。

    【讨论】:

    • 谢谢丹。我想我找到了问题所在。 String.Format 正在生成 "C:\\00346A23.jpg" ...注意两个反斜杠。我不确定为什么会这样。我想保存在C盘。
    • 好的,所以我通过删除反斜杠来修复它。但我仍然遇到同样的错误。这就是我现在所拥有的:jpegPaths[frame] = String.Format("{0}{1}.jpg", destinationDirectory, Path.GetFileNameWithoutExtension(tiffFile), frame);
    • 该输出目录是否存在?您只是想保存到不同的目录。顺便说一句,您确实需要两个反斜杠,因为它们会变成一个反斜杠...首先尝试使用硬编码路径测试您知道存在的目录,然后从那里构建。或者在尝试保存之前在每个路径上调用 Directory.CreateDirectory。
    • 我明白了。这是两件事:1 它放了 2 个反斜杠,2 目标 UNC 路径错误。我们让它工作了。感谢您的帮助!
    • 对于任何到达这里的人来说,图像文件都可能严重损坏,以至于在读取时会产生它。
    猜你喜欢
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多