如何在 .NET 中使用 Aspose.Imaging FOSS Core API
Aspose.Imaging FOSS 用于 .NET 的公共表面由三个类组成:ImageProbe、ImageInfo 和 ImageFormat。本指南将演示如何安装该包并将这三者一起使用,以检测格式并从文件、流和字节数组读取头部元数据。
分步指南
步骤 1:安装包
git clone https://github.com/aspose-imaging-foss/Aspose.Imaging-FOSS-for-.NET.git
cd Aspose.Imaging-FOSS-for-.NET
dotnet build该包面向 net8.0 和 netstandard2.0,且没有任何外部运行时依赖。
步骤 2:导入命名空间
添加一个单一的 using 指令 — 它公开了 ImageProbe、ImageInfo 和 ImageFormat,以及整个 API 表面,因此无需再导入其他内容:
using Aspose.Imaging.Foss;步骤 3:按路径探测文件
ImageProbe.ProbeFile 读取足够的文件头信息以填充 ImageInfo 结果 — 它从不解码像素数据:
var info = ImageProbe.ProbeFile("photo.jpg");
Console.WriteLine($"{info.Format}: {info.Width}x{info.Height}, {info.BitDepth}-bit");步骤 4:探测流或字节数组
当图像已经在内存中或来自流(上传、网络响应)时,请使用直接接受这些数据的重载,而不是先写入临时文件:
byte[] bytes = File.ReadAllBytes("photo.jpg");
var infoFromBytes = ImageProbe.Probe(bytes);
using var stream = File.OpenRead("photo.jpg");
var infoFromStream = ImageProbe.Probe(stream);Probe(stream) 可用于可定位流和不可定位流。
步骤 5:仅在需要格式时使用 DetectFormat
如果您只需根据格式进行分支,而不需要尺寸、位深或帧数,DetectFormat 将跳过其余的头部解析:
var format = ImageProbe.DetectFormat(bytes);
if (format == ImageFormat.Dicom)
{
// route to DICOM-specific handling
}第6步:安全读取可为空的 ImageInfo 字段
Width、Height、BitDepth 和 FrameCount 是可为空的——仅在检测到的格式头部实际包含该值时才会填充。Format 是在识别头部后始终被设置的字段:
var info = ImageProbe.ProbeFile("scan.dcm");
if (info.Width.HasValue && info.Height.HasValue)
{
Console.WriteLine($"{info.Format}: {info.Width}x{info.Height}");
}
else
{
Console.WriteLine($"{info.Format}: dimensions not available in this header");
}常见问题与解决方案
格式显示为 ImageFormat.Unknown. 文件头不匹配任何已识别的 11 种格式 (PNG, JPEG, GIF, BMP, WebP, ICO, TIFF, PSD, EMF, WMF, DICOM)。请确认该文件确实是这些格式之一 — ImageProbe 从不为未识别的头抛出异常,它会报告 Unknown 而是。
Width/Height are null 即使 Format 已设置。 并非每种格式的头部都包含所有字段,且截断的文件可能在字段字节之前就被切掉。请检查 Format 首先,然后将其余部分视为可选。
Calling Probe when DetectFormat 会做到。 Probe and ProbeFile 解析完整的头部; DetectFormat 只读取足够的信息来识别格式。使用 DetectFormat 如果你从不读取 Width/Height/BitDepth/FrameCount.
期望已解码的像素数据。 ImageProbe 从不解码、渲染或转换图像内容——它仅读取头部元数据。解码和像素级操作需要商业 Aspose.Imaging SDK。
常见问题
如果我探测一个被截断或损坏的文件,会发生什么?
ImageProbe 在遇到格式错误或截断的输入时从不抛异常。它返回一个部分的 ImageInfo — Format 在检测到头部的格式标记时会被设定,即使文件的其余部分被截断。
ImageProbe 是线程安全的吗?
是的。ImageProbe 是静态的,在调用之间不保持可变状态,因此来自多个线程的并发调用是安全的。
我可以直接构造一个 ImageInfo,而不去探测真实文件吗?
是的。ImageInfo 的构造函数是公开的,只需要 format — 这对于构建测试替身很有用:new ImageInfo(ImageFormat.Png, width: 64, height: 48)。
我需要释放任何资源吗?
No. ImageProbe 本身不持有任何 IDisposable 资源。如果你传递一个你自己打开的 Stream,你仍需负责释放它。