I'm trying to translate the following code using System.Drawing
to use the cross-platform ImageSharp library.
Image originalImage = Image.FromFile(filename);
Bitmap resizedImage = new Bitmap((int)format.Width, (int)format.Height, PixelFormat.Format16bppRgb565);
Graphics gfxContext = Graphics.FromImage(resizedImage);
gfxContext.CompositingQuality = CompositingQuality.HighQuality;
gfxContext.SmoothingMode = SmoothingMode.HighQuality;
gfxContext.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle rect = new Rectangle(0, 0, (int)format.Width, (int)format.Height);
gfxContext.DrawImage(originalImage, rect);
BitmapData bitmapData = resizedImage.LockBits(new Rectangle(0, 0, resizedImage.Width, resizedImage.Height), ImageLockMode.ReadOnly, resizedImage.PixelFormat);
byte[] bmpBytes = new byte[bitmapData.Stride * bitmapData.Height];
System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, bmpBytes, 0, bmpBytes.Length);
bmp.UnlockBits(bitmapData);
return bmpBytes;
I know how to resize images with ImageSharp, but what I'm struggling to figure out is how to convert the image to a Bitmap with a particular pixel format, and then from that get the raw bytes. ImageSharp seems to want me to save the image with a particular extension to trigger a conversion, but I need the image in a specific pixel format (RGB565).
ImageSharp doesn't natively support the Rgb565 pixel format, however pixel formats are completely customizable so you could create a custom Rgb565 pixel type and then you will be able to load it as
Image.Load<Rgb565>(filename)
.You can use https://github.com/SixLabors/ImageSharp/blob/main/src/ImageSharp/PixelFormats/PixelImplementations/Bgr565.cs as a bases for your custom Rgb565 pixel format (it should just requiring you switch the bit packing order)
Then you can use the
image.CopyPixelDataTo()
to get a copy of the pixels back out as a byte array.