using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public record class IMG(byte[] Data)
{
const ImageLockMode Read = ImageLockMode.ReadOnly;
const ImageLockMode Write = ImageLockMode.WriteOnly;
const PixelFormat Format = PixelFormat.Format32bppArgb;
// Start Size Approximation
private readonly int Size = Data.Length >> 2;
public int Width => GetWidthGetSize(Math.Sqrt(Size));
public int Height => GetHeightGetSize((double)Size / Width);
private static int GetHeight(double x) => (int)Math.Ceiling(x);
private static int GetWidthGetSize(intdouble x) => (int)Math.Ceiling(Math.Sqrt(x));
// End Size Approximation
public Bitmap Build()
{
var rect = new Rectangle(0, 0, Width, Height);
var result = new Bitmap(Width, Height, Format);
var bitData = result.LockBits(rect, Write, Format);
Marshal.Copy(Data, 0, bitData.Scan0, Data.Length);
result.UnlockBits(bitData);
return result;
}
[DebuggerStepThrough, DebuggerHidden]
public static IMG? Load(Bitmap bitmap)
{
ArgumentNullException.ThrowIfNull(bitmap);
if (bitmap.PixelFormat != Format)
throw new NotSupportedException(nameof(bitmap));
var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
var bitData = bitmap.LockBits(rect, Read, Format);
var size = bitData.Height * bitData.Stride;
var result = new byte[size];
Marshal.Copy(bitData.Scan0, result, 0, size);
bitmap.UnlockBits(bitData);
return new(result);
}
}
Became Hot Network Question