Convert RGB8 byte[] to Bitmap - c#

I have raw pixel data coming from a camera in RGB8 format which I need to convert to a Bitmap. However, the Bitmap PixelFormat only seems to support RGB 16, 24, 32, and 48 formats.
I attempted to use PixelFormat.Format8bppIndexed, but the image appears discolored and inverted.
public static Bitmap CopyDataToBitmap(byte[] data)
{
var bmp = new Bitmap(640, 480, PixelFormat.Format8bppIndexed);
var bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(data, 0, bmpData.Scan0, data.Length);
bmp.UnlockBits(bmpData);
return bmp;
}
Is there any other way to convert this data type correctly?

This creates a linear 8-bit grayscale palette in your image.
bmp.UnlockBits(bmpData);
var pal = bmp.Palette;
for (int i = 0; i < 256; i++) pal.Entries[i] = Color.FromArgb(i, i, i);
bmp.Palette = pal;
return bmp;
You will still need to invert the scan lines, maybe like this:
for (int y = 0; y < bmp.Height; y++)
Marshal.Copy(data, y * bmp.Width,
bmpData.Scan0 + ((bmp.Height - 1 - y) * bmpData.Stride), bmpData.Stride);

Related

Saving a single channel of a bitmap image to a file [duplicate]

This question already has answers here:
Split PNG into RGB and Alpha Channels
(2 answers)
Closed 3 years ago.
I'm using this code to save a bitmap as binary data.
Bitmap bmp = new Bitmap(screenWidth, position);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
bmp.UnlockBits(bmpData);
File.WriteAllBytes(filename, bmp);
g.Dispose();
As I only need the first channel's values, is it possible to retrieve that from the bitmap? Performance is essential.
You're almost there, but there are a few key details missing:
Instead of using bmp.PixelFormat, force the pixel format for the BitmapData object to PixelFormat.Format32BppArgb, then you're 100% sure what structure you will get, and in 32-bit mode, the stride will always exactly match a predictable width * 4. If you don't do this, you may get unexpected results if the read image happens to be paletted or some sort of 16bpp format where each pixel can't be divided into simple colour component bytes.
Loop over the data and extract the channel. The order of the letters 'ARGB' refers to the a hexadecimal value 0xAARRGGBB (like, for example, 0xFF428ED0), which is a little-endian Uint32 value, meaning the actual order of the colour component bytes is the reverse: { BB, GG, RR, AA }.
So, to extract your channel:
// Channels are: B=0, G=1, R=2, A=3
Int32 channel = 1 // for this example, extract the Green channel.
Int32 width;
Int32 height;
Byte[] rgbaValues;
using (Bitmap bmp = new Bitmap(screenWidth, position))
using (Graphics g = Graphics.FromImage(bmp))
{
width = bmp.Width
height = bmp.Height;
g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
Int32 bytes = bmpData.Stride * bmp.Height;
rgbaValues = new byte[bytes];
Marshal.Copy(bmpData.Scan0, rgbValues, 0, bytes);
bmp.UnlockBits(bmpData);
g.Dispose();
}
Byte[] channelValues = new byte[width * height];
Int32 lineStart = 0;
Int32 lineStartChannel = 0;
for (Int32 y = 0; y < height; ++y)
{
Int32 offset = lineStart;
Int32 offsetChannel = lineStartChannel;
for (Int32 x = 0; x < width; ++x)
{
// For reference:
//Byte blue = rgbaValues[offset + 0];
//Byte green = rgbaValues[offset + 1];
//Byte red = rgbaValues[offset + 2];
//Byte alpha = rgbaValues[offset + 3];
channelValues[offsetChannel] = rgbaValues[offset + channel];
offset += 4;
offsetChannel++;
}
lineStart += stride;
lineStartChannel += width;
}
File.WriteAllBytes(filename, channelValues);
This just saves the data as byte array. If you want to write it as image, the simplest way is probably to make an 8-bit bitmap, open a BitmapData object on it, and write the lines into it one by one, and then set its colour palette to a generated range from 0,0,0 to 255,255,255.
I posted a function that takes a byte array, image dimensions and a palette and makes an image out of it in this answer.

Slanted bitmap, stride calculation for RGB565 C#

Some of my resulting images are slanted, some are not.
Expected Result: (529x22)
Actual Result: (529x22)
Don't mind the different image sizes, these are screenshots. They are both 529x22.
The code I am using, I just got this from an answer on a question here at SO.
// some other method
byte[] pixels = new byte[size - 16];
Array.Copy(this.data, offset, pixels, 0, pixels.Length);
this.ByteToImage(w, h, pixels);
// builds the pixels to a image
private Bitmap ByteToImage(int w, int h, byte[] pixels)
{
var bmp = new Bitmap(w, h, PixelFormat.Format16bppRgb565);
var BoundsRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
bmp.PixelFormat);
// bytes => not using this because it gives error
// eg. pixel.Length = 16032, bytes = 16064
int bytes = bmpData.Stride * bmp.Height;
Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
bmp.UnlockBits(bmpData);
return bmp;
}
I'm confused because some works ok, not slanted. But others are slanted. What did I miss?
Update
As stated in the comments and answers, the problem is how I'm calculating stride. I'm still confused on how to do it but I tried this:
public static void RemovePadding(this Bitmap bitmap)
{
int bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
var pixels = new byte[bitmapData.Width * bitmapData.Height * bytesPerPixel];
for (int row = 0; row < bitmapData.Height; row++)
{
var dataBeginPointer = IntPtr.Add(bitmapData.Scan0, row * bitmapData.Stride);
Marshal.Copy(dataBeginPointer, pixels, row * bitmapData.Width * bytesPerPixel, bitmapData.Width * bytesPerPixel);
}
Marshal.Copy(pixels, 0, bitmapData.Scan0, pixels.Length);
bitmap.UnlockBits(bitmapData);
}
But the result is (more slanted):
This seems to work here:
private Bitmap ByteToImage(int w, int h, byte[] pixels)
{
var bmp = new Bitmap(w, h, PixelFormat.Format16bppRgb565);
byte bpp = 2;
var BoundsRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
bmp.PixelFormat);
// copy line by line:
for (int y = 0; y < h; y++ )
Marshal.Copy(pixels, y * w * bpp, bmpData.Scan0 + bmpData.Stride * y, w * bpp);
bmp.UnlockBits(bmpData);
return bmp;
}
I use a loop to place each row of data at the right spot. The data do not include the padding, but the target address must do so.
Therefore we need to multiply the data access by the actual width * bytePerPixel but the target adress by the Stride, i.e. the length of the scanline, padded to the next multiple of four bytes. For width=300 it is stride=300, for width=301 it is stride=304..
Moving all pixel data in one step can only work when there is no padding, i.e. when the width is a multiple of 4.
This expects the stride to correspond to the width, without padding. There can be padding. The padding would "eat" some of the next line, which will therefore appear to shift left.
Since the padding breaks up the lines, the only real way to deal with it (other than using the same padding everywhere) is copying line by line. You can calculate the starting address of a line with bmpData.Scan0 + y * bmpData.Stride. Copy starting there, for every y.
// bytes => not using this because it gives error
Yes, because your array does not have padding. So you were telling it to copy more data than the array held.

raw pixel array to gray scale BitmapImage

I have an array of raw pixel data. I would like to convert it into 8bpp Bitmap.
public static Bitmap ByteToGrayBitmap(byte[] rawBytes, int width, int height)
{
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.WriteOnly, bitmap.PixelFormat);
Marshal.Copy(rawBytes, 0, bitmapData .Scan0, rawBytes.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
bitmap looks like a color image instead of grayscale.
You need a 8-bit grayscale palette in your image.
Add this before you return:
var pal = bmp.Palette;
for (int i = 0; i < 256; i++) pal.Entries[i] = Color.FromArgb(i, i, i);
bmp.Palette = pal;
return bmp;
Try adding this before you return the bitmap:
for (int c = 0; c < bitmap.Palette.Entries.Length; c++)
bitmap.Palette.Entries[c] = Color.FromArgb(c, c, c);
It will create a typical grayscale palette.

Compare two image data using unsafe method

I am writing a function to get difference between two bitmap images in visual studio 2010. I have a function that takes two bitmap images as parameters, I use unlock bits to get data of each pixel,both the images are of equal resolution and dimensions.
When I use unlock bits for only one image it works well, but when I use it for both simultaneously in the same function it gives an exception
BITMAP REGION IS ALREADY LOCKED
code:
public Bitmap Invert(Bitmap b,Bitmap c)
{
BitmapData bmData =
b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadWrite,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
// for image 2
BitmapData data2 =
c.LockBits(new System.Drawing.Rectangle(0,
0,
c.Width,
c.Height),
ImageLockMode.ReadWrite,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
int stride1 = data2.Stride;
System.IntPtr Scan1 = data2.Scan0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
byte* q = (byte*)(void*)Scan1;
nOffset = stride - b.Width * 3;
nWidth = b.Width * 3;
for (y = 0; y < b.Height; ++y)
{
for (x = 0; x < nWidth; ++x)
{
p[0] = (byte)(p[0]-q[0]);
++p;
++q;
}
p += nOffset;
q += nOffset;
}
}
b.UnlockBits(bmData);
c.UnlockBits(data2);
return b;
}
Becuase you only need to compare images , I would suggesst opening them in read mode only i.e:
BitmapData data2 = c.LockBits(new System.Drawing.Rectangle(0,
0,
c.Width,
c.Height),
ImageLockMode.ReadOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);

C# convert stride/buffer/width/height to bitmap

I have an image width/height/stride and buffer.
How do I convert this information to a System.Drawing.Bitmap? Can I get the original image back if I have these 4 things?
There is a Bitmap constructor overload, which requires everything you have (plus PixelFormat):
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);
This might work (if args.Buffer is an array of blittable type, like byte for example):
Bitmap bitmap;
var gch = System.Runtime.InteropServices.GCHandle.Alloc(args.Buffer, GCHandleType.Pinned);
try
{
bitmap = new Bitmap(
args.Width, args.Height, args.Stride,
System.Drawing.Imaging.PixelFormat.Format24bppRgb,
gch.AddrOfPinnedObject());
}
finally
{
gch.Free();
}
Update:
Probably it's better to copy image bytes to newly created Bitmap manually, because it seems like that constructors doesn't do that, and if byte[] array of image data gets garbage collected all sorts of bad things can happen.
var bitmap = new Bitmap(args.Width, args.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var data = bitmap.LockBits(
new Rectangle(0, 0, args.Width, args.Height),
System.Drawing.Imaging.ImageLockMode.WriteOnly,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
if(data.Stride == args.Stride)
{
Marshal.Copy(args.Buffer, 0, data.Scan0, args.Stride * args.Height);
}
else
{
int arrayOffset = 0;
int imageOffset = 0;
for(int y = 0; y < args.Height; ++y)
{
Marshal.Copy(args.Buffer, arrayOffset, (IntPtr)(((long)data.Scan0) + imageOffset), data.Stride);
arrayOffset += args.Stride;
imageOffset += data.Stride;
}
}
bitmap.UnlockBits(data);
This should work if you have the buffer as byte[], a width and the height + the pixelformat (stride)
public Bitmap CreateBitmapFromRawDataBuffer(int width, int height, PixelFormat imagePixelFormat, byte[] buffer)
{
Size imageSize = new Size(width, height);
Bitmap bitmap = new Bitmap(imageSize.Width, imageSize.Height, imagePixelFormat);
Rectangle wholeBitmap = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
// Lock all bitmap's pixels.
BitmapData bitmapData = bitmap.LockBits(wholeBitmap, ImageLockMode.WriteOnly, imagePixelFormat);
// Copy the buffer into bitmapData.
System.Runtime.InteropServices.Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);
// Unlock all bitmap's pixels.
bitmap.UnlockBits(bitmapData);
return bitmap;
}

Categories