快速入门

快速入门

本页演示最小可工作示例:探测文件的格式和头部属性,然后查看库在遇到损坏文件时如何处理而不是抛出异常。


探测文件

ImageProbe 是唯一的静态入口点。ProbeFile 读取文件头部的足够信息以生成一个 ImageInfo 结果——它从不解码像素数据:

using Aspose.Imaging.Foss;

var info = ImageProbe.ProbeFile("photo.jpg");
Console.WriteLine($"{info.Format}: {info.Width}x{info.Height}, {info.BitDepth}-bit");

ImageInfo 暴露 Format、Width、Height、BitDepth 和 FrameCount ——仅在检测到的格式实际包含这些数据时才会填充。


探测流或字节数组

Probe 直接接受一个 Stream 或一个 byte[],并且 DetectFormat 在你不需要完整头部时仅返回 ImageFormat:

using Aspose.Imaging.Foss;
using System.IO;

byte[] bytes = File.ReadAllBytes("photo.jpg");
var format = ImageProbe.DetectFormat(bytes);

using var stream = File.OpenRead("photo.jpg");
var info = ImageProbe.Probe(stream);

处理被截断或格式错误的输入

ImageProbe 在遇到格式错误或被截断的输入时永不抛出异常。它不会抛出异常,而是返回一个部分的 ImageInfo,其中包含它能够读取的字段——只要识别到了头部的格式标记,即使文件其余部分被截断,Format 也总是会被设置:

using Aspose.Imaging.Foss;

byte[] truncated = fullGifBytes[..^2]; // last two bytes missing

var info = ImageProbe.Probe(truncated);
Console.WriteLine(info.Format);        // Gif — detected from the header alone

这使得 ImageProbe 在对不受信任或部分下载的文件运行时是安全的,无需在每次调用时都使用 try/catch 包裹。


后续步骤

另请参阅

 中文