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

标签 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:参数无效。

最佳答案

如果您遇到的错误是在线:

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);

关于c# - 将 TIFF 调色板从 8 位更改为 32 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12510340/

相关文章:

c# - 简单的网络服务器 : The format of the specified network name is invalid

iphone - 图像旋转不正确

java - TIFF 编码的 JPEG

python - 创建多帧 .tif 文件

c# - 使用套接字发送回复广播

c# - Getters 和 Setters 与类方法

c# - 将集合写入 Excel

asp.net - 如何在 ASP.NET 中设置图片作为背景?

image - 当我将 URL 从网站粘贴到 Facebook 或 slack 等时,如何显示图像

java - 使用 Java 创建多页 Tiff