以下文章來源于碼農(nóng)很忙 ,作者碼農(nóng)很忙
之前寫過一篇博文,用來獲取圖片的正確格式。博文所示代碼一直工作良好,直到今天在將程序部署到阿里云函數(shù)計算時,發(fā)生了以下報錯:
System.Drawing is not supported on this platform.
這表明我們不能在阿里云函數(shù)計算服務(wù)器上使用 GDI+ 相關(guān)的函數(shù),即便如此我們?nèi)匀豢梢酝ㄟ^讀取文件頭獲取圖片格式:
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"); // BMP
var gif = Encoding.ASCII.GetBytes("GIF"); // GIF
var png = new byte[] {137, 80, 78, 71}; // PNG
var tiff = new byte[] {73, 73, 42}; // TIFF
var tiff2 = new byte[] {77, 77, 42}; // TIFF
var jpeg = new byte[] {255, 216, 255, 224}; // jpeg
var jpeg2 = new byte[] {255, 216, 255, 225}; // jpeg canon
if (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
需要一個二進制數(shù)組作為參數(shù),但這并不代表需要將全部的文件內(nèi)容都讀取到內(nèi)存。使用以下代碼可以獲得較好的運行效果:
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(); }