public static DecodedImage DecodeImage(ReadOnlySpan <byte> data) { var result = new DecodedImage(); result.info = DetectImageFormat(data); switch (result.info.format) { case ImageFileFormat.BMP: result.data = StbNative.DecodeBitmap(data); break; case ImageFileFormat.PNG: result.data = StbNative.DecodePng(data); break; case ImageFileFormat.JPEG: result.data = DecodeJpeg(data); break; case ImageFileFormat.TGA: result.data = DecodeTga(data); break; case ImageFileFormat.FNTART: return(DecodeFontArt(data)); default: case ImageFileFormat.Unknown: throw new ImageIOException("Unrecognized image format."); } return(result); }
/// <summary> /// Tries to detect the image format of the given data by /// inspecting the header only. /// </summary> /// <param name="data"></param> /// <returns></returns> public static ImageFileInfo DetectImageFormat(ReadOnlySpan <byte> data) { ImageFileInfo info; if (StbNative.GetPngInfo(data, out info.width, out info.height, out info.hasAlpha)) { info.format = ImageFileFormat.PNG; return(info); } if (StbNative.GetBitmapInfo(data, out info.width, out info.height, out info.hasAlpha)) { info.format = ImageFileFormat.BMP; return(info); } using var jpegDecompressor = new JpegDecompressor(); if (jpegDecompressor.ReadHeader(data, out info.width, out info.height)) { info.hasAlpha = false; info.format = ImageFileFormat.JPEG; return(info); } if (TargaImage.DetectTga(data, out info)) { return(info); } // Not a very good heuristic if (data.Length == 256 * 256) { info.width = 256; info.height = 256; info.hasAlpha = true; info.format = ImageFileFormat.FNTART; return(info); } return(info); }