Click to See Complete Forum and Search --> : Byte to float


Avcrash
August 2nd, 2009, 04:09 AM
Hi there. I have got a question. Here goes the task. I have a byte array needs to be converted to bitmap. Here the code I use.

public Bitmap return_bmp()
{
Bitmap bmp = new Bitmap(size_of_line, size_of_row,PixelFormat.Format24bppRgb);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;

byte[] rgbValues = new byte[bmpData.Stride*bmpData.Height];
for (int i = 0; i < number_of_elements_in_array; i++)
{
rgbValues[i] = (byte)vals[i];
rgbValues[2 * i] = (byte)vals[i];
rgbValues[3 * i] = (byte)vals[i];
}

System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bmpData.Stride*bmpData.Height);
bmp.UnlockBits(bmpData);
return bmp;
}

The problem is that I get the hodgepodge, not an image I crave for. The rgbValues structure is - the first size_of_line elements are the first line, the next value is the first pixel of the second line and so on. Please, help me. I've cudgeled my brain aboit it. Thanks in advance.

Avcrash
August 2nd, 2009, 04:50 AM
I 've mistaken having called this post so.

Avcrash
August 3rd, 2009, 01:03 AM
Would anybody help, please?

MadHatter
August 3rd, 2009, 04:15 AM
http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx

check your loop. shouldn't it be i += 3, not i++

Avcrash
August 3rd, 2009, 10:58 AM
Thanks for the link. I have seen it before. Every value in vals should represent a pixel in a resulting image, so I set every component of RGB to be vals[i]. Any other suggestions? i+=3 doesn't work either.

BigEd781
August 3rd, 2009, 01:50 PM
Have you tried something simple like this?


ImageConverter ic = new ImageConverter();
Image img = (Image)ic.ConvertFrom(byteArray);
Bitmap bitmap1 = new Bitmap(img);


Also, there is a Bitmap constructor which takes a Stream, so you could wrap the byte array in a stream and use that as well. Of course, this depends a bit on the structure of your data.

Also, you do know that Windows stores rgb values in revers byte order, right? When you are working directly with an image buffer you need to know this.