尝试将.tif文件转换为jpg时出错:GDI +中发生一般错误

时间:2018-12-17 12:55:30

标签: c# .net

我正在尝试将.tif文件转换为.jpg,但出现以下异常:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

我正在Windows 10计算机上运行它。

如何解决此错误?

这是我的程序:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Encoder = System.Drawing.Imaging.Encoder;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            SaveAsJpeg(@"C:\Temp\Target\test_converted.jpg", 70);

            if (!System.Diagnostics.Debugger.IsAttached) return;
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }

        public static FileInfo SaveAsJpeg(string newFilePath, long quality)
        {
            // File to convert
            var path = @"C:\Temp\test.tif";

            using (var stream = new MemoryStream(File.ReadAllBytes(path)))
            {
                using (var imageToConvert = Image.FromStream(stream))
                {
                    // This line throws the error
                    imageToConvert.Save(newFilePath, GetDecoder(ImageFormat.Jpeg), GetQualityEncoderParameters(quality));
                }
            }

            return new FileInfo(newFilePath);
        }

        private static ImageCodecInfo GetDecoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();
            return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
        }

        private static EncoderParameters GetQualityEncoderParameters(long quality)
        {
            var qualityParameter = new EncoderParameter(Encoder.Quality, quality);
            var encoderParameters = new EncoderParameters(1) { Param = { [0] = qualityParameter } };
            return encoderParameters;
        }
    }
}

到目前为止,我有...

  • 确保C:\Temp\Target存在
  • 确保Everyone拥有对C:\Temp\Target的完全读/写访问权限

这些是文件属性:

enter image description here

enter image description here

编辑:

在使用不同的图像尝试相同的代码之后,没有引发任何错误,我尝试转换的图像可能存在问题。具有以下属性的图像已成功转换:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

我不知道怎么做,但这似乎可以解决问题。没有引发任何错误,并且图像转换成功:

public static FileInfo SaveAsJpeg(string newFilePath, long quality)
{
    var path = @"C:\Temp\test.tif";

    using (var stream = new MemoryStream(File.ReadAllBytes(path)))
    {
        var imageToConvert = Image.FromStream(stream); 
        using (imageToConvert = new Bitmap(imageToConvert))
        {
            imageToConvert.Save(newFilePath, GetDecoder(ImageFormat.Jpeg), GetQualityEncoderParameters(quality));
        }
    }

    return new FileInfo(newFilePath);
}

如果任何人都可以详细说明为什么会这样,那太好了。