有没有办法通过读取图像标题来了解 png 图像的透明度?
有没有办法通过读取图像标题来了解 png 图像的透明度?
Is there a way to find out about a png image transparency by reading the image header?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
谢谢大家。使用 ChrisF 的链接使其正常工作
确定图像中是否使用 Alpha 通道
谢谢克里斯F。
这是我的代码:
Thanks everyone. Got it to work by using ChrisF's link
Determine if Alpha Channel is Used in an Image
Thanks ChrisF.
Here is my code:
二进制访问
在我对
GetPixel
对于每个像素的性能不佳发表评论之后,我尝试编写一个代码片段来查找图像(包括 PNG)中是否存在透明像素。这里是。优点:
GetPixel
快得多,缺点:
不安全
,调色板
一种较少手动的方法是使用调色板。可能存在一些 .NET Framework 或第三方库可以让您执行此操作。我尝试了以下操作(使用 WPF):
但我不起作用,因为
bitmapSource.Palette
大部分时间为null
。此外,与第一个片段相比,使用调色板会严重降低性能,因为在继续之前必须将每种颜色加载到颜色列表中。Binary access
Following my comment about the poor performance of
GetPixel
for each pixel, I tried to write a snippet which finds if there are transparent pixels or not in an image (including PNG). Here it is.Pros:
GetPixel
,Cons:
unsafe
,Palettes
A less manual approach would be to use palettes. There might probably exist some .NET Framework or third party libraries which let you do that. I tried the following (using WPF):
but I does not work, since
bitmapSource.Palette
isnull
most of the time. Further, using palettes will heavily decrease performance, compared to the first snippet, since every color must be loaded into a list of colors before proceeding.找出什么?图像是否具有透明度?您可以检查位深度,24位(RGB)通常意味着没有透明度,32位(RGBA)意味着有不透明/透明层
Find out what? If the image HAS transparency? You could check the bit depth, 24 bit (RGB) usually means there is no transparency, and 32 bit (RGBA) means there is an opacity/transparency layer
有时您可以看出,如果位深度为 24 或位深度较低且调色板成员都不包含相关的 alpha 值(您没有说明是否要将部分透明度计为透明或不是)。
然而,为了确保确实存在一定的透明度,确实需要检查整个图像。因此,流大小为 O(n)(图像大小大致为 O(x * y)),但在某些情况下可能有来自标头的捷径。
You can sometimes tell that it definitely doesn't have transparency if either the bit depth is 24 or if it's lower and none of the palette members contain a relevant alpha value (you don't say whether you want to count partial transparency as transparent or not).
However, to be sure that there actually is some transparency, does require one to examine the entire image. Hence, it's O(n) for the stream size (which is roughly O(x * y) for the image size), but with a possible short-cut from the header for some cases.
如果 png 已被索引,那么您可以检查 TRNS 块 Png 块描述。如果没有,那么您需要像在该方法中那样逐像素获取它。
If the png is indexed then you can check the TRNS chunk Png chunks description. If not then you need the get it pixel by pixel as you do it in that method.