Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Reading RAW RGBA Data into a bitmap

$
0
0
I am converting a piece of image manipulation from Python to C#
and basically I am getting nothing but garbage out

I have a byte array of Raw RGBA data and I am trying to copy it into a bitmap.
The code I have is as follows:

        public Bitmap RawToBitmap(byte[] rawdata)
        {

            for (int i = 0; i < rawdata.Length - 1; i+=4)
            {
                byte R = rawdata[i];
                byte G = rawdata[i + 1];
                byte B = rawdata[i + 2];
                byte A = rawdata[i + 3];

                rawdata[i] = A;
                rawdata[i + 1] = R;
                rawdata[i + 2] = G;
                rawdata[i + 3] = B;
            }

            int width = 128;
            int height = 128;

            // Set the stride... 
            int stride = width;

            // Ensure it is padded to a multiple of 4
            if (stride%4 != 0)
            {
                stride = width + (4 - width % 4);
            }

            IntPtr myPointer = System.Runtime.InteropServices.Marshal.AllocHGlobal(rawdata.Length);
            System.Runtime.InteropServices.Marshal.Copy(rawdata, 0, myPointer, rawdata.Length);

            Bitmap output = new Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppArgb, myPointer);
            Bitmap realOutput = (Bitmap)output.Clone();
           
            System.Runtime.InteropServices.Marshal.FreeHGlobal(myPointer);

            return realOutput;

        }

The only difference between this code and the original python is that the PNG library for python supports RGBA where as I can seem to find an equivelent in dot net so I am doing a byte swap.

I have tried both with and without the byte swap.
I have tried various PixelFormats but I never get anything but a munged image.

Any help at all would be appreciated.

Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>