0

I have an array of UInt32 elements, where every element represents RGB pixel on an image (for the record, I'm receiving this array from LabView c++ DLL). I'm trying to convert this array to System.Drawing.Bitmap to save it later as file or display in the application.

For now, my code iterate through every element, convert it to uint r, g and b, create SystemDrawing.Color from it and set pixel in Bitmap image object. This is the code (i'm using pointers):

fixed (uint* arrPtr = img.elt)
{
    uint* pixelPtr = arrPtr;
    Bitmap image = new Bitmap(img.dimSizes[1], img.dimSizes[0]);
    for (int y = 0; y < img.dimSizes[0]; y++)
    {
        for (int x = 0; x < img.dimSizes[1]; x++)
        {
            uint r = (arrPtr[img.dimSizes[1] * y + x] >> 16) & 255;
            uint g = (arrPtr[img.dimSizes[1] * y + x] >> 8) & 255;
            uint b = arrPtr[img.dimSizes[1] * y + x] & 255;
            Color c = Color.FromArgb(255, (int)r, (int)g, (int)b);
            image.SetPixel(x, y, c);
         }
     }
     image.Save("Test.jpg");
    }
}

Of course this method is SO MUCH inefficient so my question is: Is there any faster method to convert my UInt32 array, which represents RGB pixels of an image, to an actual System.Drawing.Image object?

user1916778
  • 137
  • 1
  • 4
  • 13
  • Does this answer your question? [Turning int array into BMP in C#](https://stackoverflow.com/questions/49046376/turning-int-array-into-bmp-in-c-sharp) – Momoro Mar 21 '20 at 07:53
  • 2
    [Bitmap.LockBits](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.lockbits) is commonly used for that. – Jimi Mar 21 '20 at 09:06
  • Btw, `image.Save("Test.jpg");` actually saves a `PNG` Image with a `.jpg` extension. – Jimi Mar 21 '20 at 13:20

1 Answers1

1

Use an overlay :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Convert convert = new Convert();
            convert.integers = new uint[100];
            convert.bytes = new byte[4 * 100];
            convert.integers = Enumerable.Range(0, 100).Select(x => (uint)x).ToArray();

            foreach (byte b in convert.bytes)
            {
                Console.WriteLine(b);
            }
            Console.ReadLine();
       }
        [StructLayout(LayoutKind.Explicit)]
        public struct Convert
        {
            [FieldOffset(0)]
            public uint[] integers;
            [FieldOffset(0)]
            public byte[] bytes;
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20