保存具有透明度/Alpha通道的TIFF

3

以下是我的问题:

我需要创建一个带有特定颜色和透明度的调色板的TIFF和PNG。

我已经可以处理PNG,但无法处理TIFF。

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

我尝试了许多加载TIFF的方法,但它们都导致重置Alpha值的调色板。

因此,我认为问题出在如何保存TIFF上,但我找不到其他方法。

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

CreateImage

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

获取TIFF文件

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个回答

3

调色板或索引颜色TIFF不支持在颜色映射中使用Alpha值。每个颜色分量的条目为16位,但只存储R、G、B(没有Alpha分量)。如果您尝试存储带有Alpha的TIFF,则Alpha将丢失。

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

另一个选项是,如果您需要颜色映射中的透明度信息(并且您控制读写),则始终使颜色映射中的第一种颜色透明,或添加一个自定义标记,其中包含可设置为透明的透明索引。您的图像应该仍能在其他软件中正确显示,但没有透明度。

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


好主意,但恐怕它没有起作用。我尝试导出PNG并得到了相同的结果,背景像素被渲染成白色。我认为在QGIS中有一些设置出了问题,因为我过去曾经能够获得透明的背景。 - Gary Lucas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接