从C#文件验证图片 [英] Validate image from file in C#

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

问题描述

我从文件加载图像,我想知道如何验证图像之前它完全从文件中读取。

 字符串文件路径=image.jpg的;
图片newImage = Image.FromFile(文件路径);
 

在image.jpg的是不是一个真正的JPG时,会出现问题。举例来说,如果我创建一个空的文本文件,并将其重命名为image.jpg的,当image.jpg文件被加载的内存不足,会引发异常。

我正在寻找将验证给定的一个流或图像的文件路径的图像的功能。

实例函数原型

 布尔IsValidImage(字符串文件名);
布尔IsValidImage(流的ImageStream);
 

解决方案

JPEG的没有一个正式的报头的定义,但他们确实有少量的元数据可以使用。

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

有后,一对夫妇其他的东西,但这些都不是重要的。

您可以用二进制流打开该文件,并读取该初始数据,并确保偏移0是0,和偏移6可以是1,2或3。

这将至少给你稍微precision。

或者你也可以捕获该异常,并动了,而我还以为你想要一个挑战:)

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

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.

Example function prototype

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

解决方案

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

  • Offset 0 (Two Bytes): JPEG SOI marker (FFD8 hex)
  • Offset 2 (Two Bytes): Image width in pixels
  • Offset 4 (Two Bytes): Image height in pixels
  • Offset 6 (Byte): Number of components (1 = grayscale, 3 = RGB)

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

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天全站免登陆