How to Convert 2-D array into Image in c#

后端 未结 5 726
忘掉有多难
忘掉有多难 2020-12-11 05:57

I have a 2D array of integers in c#.

Each entry in the 2-D array correspond to a pixel value

How can i make this 2-D array into an image file (in C#)

<
相关标签:
5条回答
  • 2020-12-11 06:39

    Bitmap.LockBits should work, if you're wanting a WinForms image.

    0 讨论(0)
  • 2020-12-11 06:41

    Here is a very fast, albeit unsafe, way of doing it:

    [Edit] This example took 0.035 ms

    // Create 2D array of integers
    int width = 320;
    int height = 240;
    int stride = width * 4;
    int[,] integers = new int[width,height];
    
    // Fill array with random values
    Random random = new Random();
    for (int x = 0; x < width; ++x)
    {
        for (int y = 0; y < height; ++y)
        {
            byte[] bgra = new byte[] { (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255), 255 };
            integers[x, y] = BitConverter.ToInt32(bgra, 0);
        }
    }
    
    // Copy into bitmap
    Bitmap bitmap;
    unsafe
    {
        fixed (int* intPtr = &integers[0,0])
        {
            bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppRgb, new IntPtr(intPtr));
        }
    }
    

    and the result:

    result

    0 讨论(0)
  • 2020-12-11 06:41

    Would projecting the array into a base64 string for streaming into a Bitmap be slow too?

    0 讨论(0)
  • 2020-12-11 06:47

    If you have the need for speed look at my Kinect sample. Basically it creates a memory area and uses an unsafe pointer to generate an Int32 array towards the memory. A BitmapSource object is used to map a bitmap (image) directly onto the same area. This particular example also uses unmanaged memory to make it compatible with P/Invoke.

    This blogpost describes the difference in performance of using unsafe. Part from that have a look at:

    • http://www.bytemycode.com/snippets/snippet/412/
    • http://www.jmsoftware.co.uk/blog/c-snippet-for-accessing-bitmap-data-with-unsafe-code
    • http://www.vcskicks.com/fast-image-processing.php

    Note that you can just as well make a Int32[]-pointer instead of the examples which uses Byte[]-pointer.

    0 讨论(0)
  • 2020-12-11 06:54

    If speed is not a concern - Bitmap + SetPixel and than save to a file: http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.setpixel.aspx

    0 讨论(0)
提交回复
热议问题