将TIFF调色板从8位更改为32位

时间:2012-09-20 10:06:00

标签: c# image tiff

我有一些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.

1 个答案:

答案 0 :(得分:2)

如果您收到的错误在线:

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

然后问题是编译器无法知道您是否引用System.Text.EncoderSystem.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);