检查设备是否支持JPEG和PNG格式的保存

本文关键字:PNG 格式 保存 JPEG 是否 支持 检查 | 更新日期: 2023-09-27 18:12:01

我需要将图像保存为PNG格式。不幸的是,在旧设备(WinCE 5.0)上,图像只能保存为BMP格式:

 try
 {
   destinationBmp.Save(fileName+".png", ImageFormat.Png);
 }
 catch (NotSupportedException)
 {
   // No PNG & JPG support on Windows CE 5.0 devices
   //
   destinationBmp.Save(fileName+".bmp", ImageFormat.Bmp);
}
finally
{
    destinationBmp.Dispose();
}

是否有可能检查图像格式支持而不处理NotSupportedException?

检查设备是否支持JPEG和PNG格式的保存

Windows CE 5.0能够支持JPEG和PNG编码,但这取决于您的设备供应商如何配置操作系统映像。如果他们没有包括编解码器,那么它将无法工作。如果您是创建windows映像的供应商,您可以使用平台构建器将这些映像添加到您的设备。

您正在使用的方法可能是决定它是否能够保存PNG或JPG图像的最简单方法。然而,从一般意义上说,假设它不支持PNG也不支持JPG是不正确的(查看您的try/catch代码,您将需要每种格式的try/catch)。

如果你知道你的代码运行在所有可能的设备上,那么使用@HansPassant检查Environment.OSVersion的建议可能是合理的,你可以决定它是Win CE 5.0设备之一,你知道它不支持JPG和PNG。否则,假定Windows CE 5.0不具备此功能是不正确的。

如果您想要确定安装了哪些编解码器的确切方法,您可以通过与Imaging COM接口(此处参考)交互来找到解决方案。具体来说,您似乎需要调用IImagingFactory.GetInstalledEncoders

我的建议可能是保持简单,创建一个测试图像,并尝试将其以每种格式保存到MemoryStream一次,并捕获NotSupportedExceptions以确定设备的能力。这样就不需要创建文件了。

注意:

COM导入看起来像这样,但是你需要用正确的参数填充GetInstallEncoders方法的占位符(对不起,我没有使用这个)。然后调用Activator.CreateInstance(...),你需要熟悉与。net中的COM接口交互。

    [ComImport, Guid("327ABDA7-072B-11D3-9D7B-0000F81EF32E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [ComVisible(true)]
    public interface IImagingFactory
    {
        uint CreateImageFromStream();       // This is a place holder, note the lack of arguments
        uint CreateImageFromFile(string filename, out IImage image);
        // We need the MarshalAs attribute here to keep COM interop from sending the buffer down as a Safe Array.
        uint CreateImageFromBuffer([MarshalAs(UnmanagedType.LPArray)] byte[] buffer, uint size, BufferDisposalFlag disposalFlag, out IImage image);
        uint CreateNewBitmap(uint width, uint height, PixelFormatID pixelFormat, out IBitmapImage bitmap);
        uint CreateBitmapFromImage(IImage image, uint width, uint height, PixelFormatID pixelFormat, InterpolationHint hints, out IBitmapImage bitmap);
        uint CreateBitmapFromBuffer();      // This is a place holder, note the lack of arguments
        uint CreateImageDecoder();          // This is a place holder, note the lack of arguments
        uint CreateImageEncoderToStream();  // This is a place holder, note the lack of arguments
        uint CreateImageEncoderToFile();    // This is a place holder, note the lack of arguments
        uint GetInstalledDecoders();        // This is a place holder, note the lack of arguments
        uint GetInstalledEncoders();        // This is a place holder, note the lack of arguments
        uint InstallImageCodec();           // This is a place holder, note the lack of arguments
        uint UninstallImageCodec();         // This is a place holder, note the lack of arguments
    }