使用透明度/ Alpha通道保存TIFF

时间:2018-02-22 14:22:19

标签: c# wpf tiff

这是我的问题:

我需要使用包含特定颜色和alpha的调色板创建TIFF和PNG。

我实际上能够处理PNG但不能处理TIFF。

我在互联网上搜索并发现TIFF应该处理透明度,但并非所有软件都可以。

我尝试过很多方法加载TIFF,但它们都会导致调色板重新设置Alpha值。

所以我认为问题来自于我如何保存TIFF,但我无法找到其他任何方式。

以防万一:调色板设置为#00FFFFFF,然后设置为#FFXXXXXX,#FEXXXXXX等。每当我加载TIFF时,颜色都会返回:#FFFFFFFF,#FFXXXXXX,#FFXXXXXX等

创建图像

public static BitmapSource CreateImage()
{
    int width = ImageGenerator.sizeW;
    int height = ImageGenerator.sizeH;
    int bytesPerPixel = (format.BitsPerPixel + 7) / 8;
    int stride = width * bytesPerPixel;
    byte[] pixels = new byte[height * stride];

    List<Color> colors = new List<Color>();
    PopuplateColors(ref colors);

    BitmapPalette myPalette = new BitmapPalette(colors);

    PopulatePixels(height, stride, ref pixels);

    BitmapSource image = BitmapSource.Create(width, height, 96, 96, format, myPalette, pixels, stride);

    if (imageStreamSource != null)
        imageStreamSource.Dispose();

    return image;
}

CreateTIFF

public static void CreateTIFF()
{
    BitmapSource image = CreateImage();

    FileStream stream = new FileStream("test.tif", FileMode.Create);
    TiffBitmapEncoder encoder = new TiffBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(image));
    encoder.Save(stream);
    stream.Dispose();
}

GetTIFF

public static ImageBrush GetTIFF()
{
    /* Another try
    BitmapImage bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.UriSource = new Uri("test.tif",UriKind.Relative);
    bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
    bitmap.EndInit();
    imagePalette = bitmap.Palette;

    CreateData(bitmap);
    return new ImageBrush(bitmap);*/

    //The last try i've done, i've looked at the palette through debug
    Bitmap bitmap = new Bitmap("test.tif");
    System.Drawing.Imaging.ColorPalette cp = bitmap.Palette;
    bitmap.MakeTransparent(cp.Entries[0]);

    return new ImageBrush();

    /* How I normally read the TIFF
    TiffBitmapDecoder decoder = new TiffBitmapDecoder(GetImage("test.tif"), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
    BitmapSource bitmapSource = decoder.Frames[0];
    imagePalette = bitmapSource.Palette;

    CreateData(bitmapSource);
    return new ImageBrush(bitmapSource);*/
}

1 个答案:

答案 0 :(得分:1)

调色板或索引颜色TIFF不支持颜色贴图中的Alpha值。条目是每颜色分量16位,但仅存储R,G,B(并且没有Alpha分量)。如果您尝试在颜色映射中存储带有alpha的TIFF,则alpha将丢失。

您可以使用单独的&#34;透明度掩码存储TIFF&#34; (单比特掩码)。这将是一个单独的IFD,这意味着某些软件可能不会将其与RGB值合并以显示透明图像。但是如果你控制读写TIFF文件的软件,我认为这是透明度的最佳选择。

另一个选项,如果您需要颜色贴图中的透明度信息(并且您控制读取和写入),则要么始终使颜色贴图中的第一种颜色透明,要么添加具有透明索引的自定义标记你可以设置透明。您的图像仍应在其他软件中正确显示,但没有透明度。

请参阅TIFF标记ColorMapPhotometricInterpretation(还有一个Indexed扩展标记,但它不会更改RGB颜色映射中存储的组件数量图像)。