.NET 测试黑白 TIFF 图像而不捕获异常?
我正在开发一个处理 TIFF 图像的文档数据库应用程序。在注释图像时,为了使用户界面仅呈现黑白(Format1bppIndexed)图像作为选择,而不是具有较高颜色深度的图像的多种颜色,我需要测试 TIFF 是否是双色调。这是我的功能:
private bool IsBitonal(string filePath) { bool isBitonal = false; try { Bitmap bitmap = new Bitmap(sourceFilePath); Graphics graphics = Graphics.FromImage(bitmap); } catch (Exception ex) { isBitonal = true; } return isBitonal; }
它可以工作,但并不优雅。此处描述了引发的索引像素格式异常: http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx。
捕获正常程序流的异常是不好的做法。此外,可以想象可能会引发不同的异常。有没有更好的方法来实现不依赖于捕获异常的 IsBitonal 函数?
我尝试在网上搜索信息,找到了如何加载 TIFF 图像并通过转换为不同格式来避免异常的示例,但我找不到任何简单测试 TIFF 图像是否为双色调的示例。
谢谢。
I am developing a document database application that handles TIFF images. When annotating images, in order for the user-interface to present only black and white as choices for bitonal (Format1bppIndexed) images versus multiple colors for images with a higher color depth I need to test for whether or not a TIFF is bitonal. Here is my function:
private bool IsBitonal(string filePath) { bool isBitonal = false; try { Bitmap bitmap = new Bitmap(sourceFilePath); Graphics graphics = Graphics.FromImage(bitmap); } catch (Exception ex) { isBitonal = true; } return isBitonal; }
It works but it is not graceful. The indexed pixel format exception that is thrown is described here: http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx.
Trapping an exception for normal program flow is poor practice. Also, it is conceivable that a different exception could be thrown. Is there a better way to implement an IsBitonal function that does not rely on trapping an exception?
I tried searching the web for information and I found examples of how to load a TIFF image and avoid the exception by converting to a different format but I couldn't find any examples of a simple test for whether or not a TIFF image is bitonal.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以检查位图的 PixelFormat 属性吗?
如果这不起作用,您应该能够查看 Bitmap 类中的 PropertyItems 集合并直接从图像中读取 TIFF 标签。
请参阅此处的 TIFF 规范:http://www.awaresystems.be/imaging/ tiff/tifftags/baseline.html
您还可以查看图像的尺寸和分辨率,并将其与文件大小进行对比,以了解每个像素有多少位。 (考虑到图像中的压缩和元数据,这可能不是很精确)。
Can you just check the PixelFormat Property of your bitmap?
If that doesn't work, You should be able to look at the PropertyItems Collection in the Bitmap class and directly read the TIFF tags from the image.
See the TIFF spec here: http://www.awaresystems.be/imaging/tiff/tifftags/baseline.html
You could also look at the dimensions and Resolution of the image and contrast it with the filesize to get and idea of how many bits per pixel there are. (This probably wouldn't be very exact given compression and Metadata in the image).