Now, I use StbImageSharp to load image and convert by:
using StbImageSharp;
namespace TestUiAOT.Helper;
public static class BmpWriter
{
public static void ConvertToBmp(string inputPath, string outputBmpPath)
{
using var fs = File.OpenRead(inputPath);
var img = ImageResult.FromStream(fs, ColorComponents.RedGreenBlueAlpha);
using var bw = new BinaryWriter(File.Create(outputBmpPath));
WriteBmp32(bw, img.Width, img.Height, img.Data);
}
public static byte[] ConvertToBmp(byte[] data)
{
var img = ImageResult.FromMemory(data, ColorComponents.RedGreenBlueAlpha);
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
WriteBmp32(bw, img.Width, img.Height, img.Data);
return ms.ToArray();
}
// rgba: length = width*height*4, top-left origin
private static void WriteBmp32(BinaryWriter bw, int width, int height, byte[] rgba)
{
const int fileHeaderSize = 14;
const int infoHeaderSize = 40;
int pixelDataSize = width * height * 4;
int fileSize = fileHeaderSize + infoHeaderSize + pixelDataSize;
int pixelDataOffset = fileHeaderSize + infoHeaderSize;
// BITMAPFILEHEADER
bw.Write((byte)'B');
bw.Write((byte)'M');
bw.Write(fileSize);
bw.Write((short)0);
bw.Write((short)0);
bw.Write(pixelDataOffset);
// BITMAPINFOHEADER
bw.Write(infoHeaderSize);
bw.Write(width);
bw.Write(-height); // top-down
bw.Write((short)1); // planes
bw.Write((short)32); // bpp
bw.Write(0); // BI_RGB (no compression)
bw.Write(pixelDataSize);
bw.Write(2835); // 72 DPI ~= 2835 ppm
bw.Write(2835);
bw.Write(0); // colors used
bw.Write(0); // important colors
// Pixel data: BGRA
for (int i = 0; i < rgba.Length; i += 4)
{
byte r = rgba[i + 0];
byte g = rgba[i + 1];
byte b = rgba[i + 2];
byte a = rgba[i + 3];
bw.Write(b);
bw.Write(g);
bw.Write(r);
bw.Write(a);
}
}
}
to convert Gif like:
var ys = EmbeddedResourceService.LoadEmbedded("Embed.Earth.gif");
var bmpData = BmpWriter.ConvertToBmp(ys);
convertedImage = ImageSource.FromBytes(bmpData)!;
I think using a "separate package" (Mention in #31) to load/convert the image is a quick way.
This solution is AOT-Friendly.
Now, I use StbImageSharp to load image and convert by:
to convert Gif like:
I think using a "separate package" (Mention in #31) to load/convert the image is a quick way.
This solution is AOT-Friendly.