之前写过一篇博文,用来获取图片的正确格式。博文所示代码一直工作良好,直到今天在将程序部署到阿里云函数计算时,发生了以下报错:
System.Drawing is not supported on this platform.
这表明我们不能在阿里云函数计算服务器上使用 GDI+ 相关的函数,即便如此我们仍然可以通过读取文件头获取图片格式:
public static class ImageHelper{public enum ImageFormat{Bmp,Jpeg,Gif,Tiff,Png,Unknown}public static ImageFormat GetImageFormat(byte[] bytes){var bmp = Encoding.ASCII.GetBytes("BM"); // BMPvar gif = Encoding.ASCII.GetBytes("GIF"); // GIFvar png = new byte[] {137, 80, 78, 71}; // PNGvar tiff = new byte[] {73, 73, 42}; // TIFFvar tiff2 = new byte[] {77, 77, 42}; // TIFFvar jpeg = new byte[] {255, 216, 255, 224}; // jpegvar jpeg2 = new byte[] {255, 216, 255, 225}; // jpeg canonif (bmp.SequenceEqual(bytes.Take(bmp.Length))){return ImageFormat.Bmp;}if (gif.SequenceEqual(bytes.Take(gif.Length))){return ImageFormat.Gif;}if (png.SequenceEqual(bytes.Take(png.Length))){return ImageFormat.Png;}if (tiff.SequenceEqual(bytes.Take(tiff.Length))){return ImageFormat.Tiff;}if (tiff2.SequenceEqual(bytes.Take(tiff2.Length))){return ImageFormat.Tiff;}if (jpeg.SequenceEqual(bytes.Take(jpeg.Length))){return ImageFormat.Jpeg;}if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length))){return ImageFormat.Jpeg;}return ImageFormat.Unknown;}}
新的 ImageHelper
需要一个二进制数组作为参数,但这并不代表需要将全部的文件内容都读取到内存。使用以下代码可以获得较好的运行效果:
var fn = @"D:\1.jpg";using (var fs = File.OpenRead(fn)){var header = new byte[10];await fs.ReadAsync(header, 0, 10);var ext = ImageHelper.GetImageFormat(header);ext.Dump();}