Skip to content

Instantly share code, notes, and snippets.

@AlexRasch
Last active November 16, 2022 20:51
Show Gist options
  • Save AlexRasch/66ad4097a2d477f0fc222af0f8a1c90f to your computer and use it in GitHub Desktop.
Save AlexRasch/66ad4097a2d477f0fc222af0f8a1c90f to your computer and use it in GitHub Desktop.
Convert byte[] to bitmap
public static Bitmap CreateBitmapFromData(byte[] binaryData)
{
// calc padding amount
int iPaddedSize = binaryData.Length + (3 - binaryData.Length % 3) + 6;
int iPixelCount = iPaddedSize / 3;
int iCountPerRow = (int)Math.Ceiling(Math.Sqrt(iPixelCount));
Bitmap bmp = new Bitmap(iCountPerRow, iCountPerRow, PixelFormat.Format24bppRgb);
byte[] paddedData = new byte[iPaddedSize];
Buffer.BlockCopy(BitConverter.GetBytes(binaryData.Length), 0, paddedData, 0, 4);
Buffer.BlockCopy(binaryData, 0, paddedData, 4, binaryData.Length);
int columnIndex = 0;
int rowNumber = bmp.Height - 1;
for (int i = 0; i < iPixelCount; i++)
{
if (columnIndex == iCountPerRow)
{
columnIndex = 0;
rowNumber--;
}
Color pixelColor = Color.FromArgb(
paddedData[i * 3 + 2],
paddedData[i * 3 + 1],
paddedData[i * 3]);
bmp.SetPixel(columnIndex, rowNumber, pixelColor);
columnIndex++;
}
return bmp;
}
public static byte[] ReadDataFromBitmap(Bitmap bitmap)
{
byte[] buffer = new byte[bitmap.Width * bitmap.Height * 3];
int i = 0;
for (int y = bitmap.Height - 1; y >= 0; y--)
{
for (int x = 0; x < bitmap.Width; x++)
{
Color pixelColor = bitmap.GetPixel(x, y);
buffer[i * 3 + 2] = pixelColor.R;
buffer[i * 3 + 1] = pixelColor.G;
buffer[i * 3] = pixelColor.B;
i++;
}
}
byte[] data = new byte[BitConverter.ToInt32(buffer, 0)];
Buffer.BlockCopy(buffer, 4, data, 0, data.Length);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment