【问题标题】:How to identify corrupt tiff files in C#?如何识别 C# 中损坏的 tiff 文件?
【发布时间】:2018-07-02 14:02:01
【问题描述】:

我在 C# 应用程序中加载 Tiff 文件时遇到问题。当 tiff 文件上传到应用程序时,它会被挂起。 发生这种情况是因为该 tiff 文件已损坏。

请推荐一种解决方案来识别此损坏的 tiff 文件,以便应用程序在上传时不会崩溃或挂起。

下面是sn-p代码,在bmp对象中打开文件时,应用程序在该行代码处挂起。

public void ReadTiff(byte[] fileData)
{
        try
        {
            using (var ms = new MemoryStream(fileData))
            {
                using (var bmp = new Bitmap(ms))
                {
                    // Some code
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
}

我已尝试对文件进行以下操作:

  1. 尝试在油漆中打开,但无法打开。
  2. 还尝试在 Windows 查看器中打开,但无法打开。
  3. 尝试在多个在线图像查看器中打开,仍然无法打开。

【问题讨论】:

  • 您需要展示如何创建要在绘图中打开的文件。您还需要展示如何将文件读入字节数组。
  • catch (Exception ex) { throw ex; } 完全没有意义,只是增加了重新抛出异常的开销。你打算做一些你还没有实现的日志记录吗?如果没有,那就去掉try/catch,没用
  • “应用程序挂起”...它就在那里?你等了多久?没有任何例外?
  • 您是否在二进制编辑器中打开了 TIFF 文件以查看可能损坏的内容?它可能与错误的文件扩展名一样简单(例如,图像实际上是 JPEG 格式,但文件扩展名是 .TIF)这可能会让您知道要查找什么来确定它是否已损坏。
  • @ADyson throw ex; 不仅完全没有意义,而且有害,因为它丢失了异常的堆栈跟踪,使调试更加困难。您应该改用throw;。也看这里:stackoverflow.com/q/730250/2557263

标签: c# tiff corruption


【解决方案1】:

使用以下函数获取图像类型,如果它为您的图像返回 ImageFormat.unknown,它已损坏且不是有效图像

public static ImageFormat GetImageFormat(byte[] bytes)
{
    var bmp    = Encoding.ASCII.GetBytes("BM");     // BMP
    var gif    = Encoding.ASCII.GetBytes("GIF");    // GIF
    var png    = new byte[] { 137, 80, 78, 71 };    // PNG
    var tiff   = new byte[] { 73, 73, 42 };         // TIFF
    var tiff2  = new byte[] { 77, 77, 42 };         // TIFF
    var jpeg   = new byte[] { 255, 216, 255, 224 }; // jpeg
    var jpeg2  = new byte[] { 255, 216, 255, 225 }; // jpeg canon

    if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
        return ImageFormat.bmp;

    if (gif.SequenceEqual(bytes.Take(gif.Length)))
        return ImageFormat.gif;

    if (png.SequenceEqual(bytes.Take(png.Length)))
        return ImageFormat.png;

    if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
        return ImageFormat.tiff;

    if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
        return ImageFormat.tiff;

    if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
        return ImageFormat.jpeg;

    if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
        return ImageFormat.jpeg;

    return ImageFormat.unknown;
}

public enum ImageFormat
{
    bmp,
    jpeg,
    gif,
    tiff,
    png,
    unknown
}

参考:-Validate image from file in C#

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多