在 C# 中验证来自文件的图像 [英] Validate image from file in C#

查看:27
本文介绍了在 C# 中验证来自文件的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文件加载图像,我想知道如何在从文件中完全读取图像之前对其进行验证.

I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.

string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);

当 image.jpg 不是真正的 jpg 时会出现问题.例如,如果我创建一个空文本文件并将其重命名为 image.jpg,则在加载 image.jpg 时会抛出 OutOfMemory 异常.

The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.

我正在寻找一个函数来验证给定图像流或文件路径的图像.

I'm looking for a function that will validate an image given a stream or a file path of the image.

示例函数原型

bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);

推荐答案

JPEG 没有正式的标头定义,但它们确实有少量您可以使用的元数据.

JPEG's don't have a formal header definition, but they do have a small amount of metadata you can use.

  • 偏移量 0(两个字节):JPEG SOI 标记(FFD8 十六进制)
  • 偏移量 2(两个字节):以像素为单位的图像宽度
  • 偏移量 4(两个字节):以像素为单位的图像高度
  • 偏移量 6(字节):分量数(1 = 灰度,3 = RGB)

在那之后还有其他一些事情,但这些都不重要.

There are a couple other things after that, but those aren't important.

您可以使用二进制流打开文件,并读取此初始数据,并确保 OffSet 0 为 0,OffSet 6 为 1,2 或 3.

You can open the file using a binary stream, and read this initial data, and make sure that OffSet 0 is 0, and OffSet 6 is either 1,2 or 3.

那至少会让你更精确一些.

That would at least give you slightly more precision.

或者你可以捕获异常并继续前进,但我认为你想要一个挑战:)

Or you can just trap the exception and move on, but I thought you wanted a challenge :)

这篇关于在 C# 中验证来自文件的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆