2

我有一些 TIFF 文件(8 位调色板)。我需要将位深度更改为 32 位。我尝试了下面的代码,但得到一个错误,参数不正确......你能帮我解决它吗?或者也许 some1 能够为我的问题提出一些不同的解决方案。

public static class TiffConverter
{
    public static void Convert8To32Bit(string fileName)
    {
        BitmapSource bitmapSource;
        using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            bitmapSource = decoder.Frames[0];
        }

        using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))
        {
            ImageCodecInfo tiffCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(ImageFormat.Tiff.Guid));
            if (tiffCodec != null)
            {
                Image image = BitmapFromSource(bitmapSource);
                EncoderParameters parameters = new EncoderParameters();
                parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
                image.Save(stream, tiffCodec, parameters);
            }
        }
    }

    private static Bitmap BitmapFromSource(BitmapSource bitmapSource)
    {
        Bitmap bitmap;
        using (MemoryStream outStream = new MemoryStream())
        {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapSource));
            enc.Save(outStream);
            bitmap = new Bitmap(outStream);
        }
        return bitmap;
    }
}

提前致谢!

[编辑]

我注意到错误出现在这一行:

image.Save(stream, tiffCodec, parameters);

ArgumentException occured: Parameter is not valid.

4

1 回答 1

2

如果您遇到的错误在线:

parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);

那么问题是编译器无法知道您是指System.Text.Encoder还是System.Drawing.Imaging.Encoder...

您的代码应如下所示以避免任何歧义:

parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 32);

编辑:

这是做同样事情的另一种方法(并且经过测试:)):

Image inputImg = Image.FromFile("input.tif");

var outputImg = new Bitmap(inputImg.Width, inputImg.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (var gr = Graphics.FromImage(outputImg))
    gr.DrawImage(inputImg, new Rectangle(0, 0, inputImg.Width, inputImg.Height));

outputImg.Save("output.tif", ImageFormat.Tiff);
于 2012-09-20T10:40:20.760 回答