Converting an array of Pixels to an image in C#

前端 未结 6 1532
孤城傲影
孤城傲影 2020-12-28 11:20

I have an array of int pixels in my C# program and I want to convert it into an image. The problem is I am converting Java source code for a program into equiva

6条回答
  •  -上瘾入骨i
    2020-12-28 11:57

    I like the WPF option already presented, but here it is using LockBits and Bitmap:

            // get the raw image data
            int width, height;
            int[] data = GetData(out width, out height);
    
            // create a bitmap and manipulate it
            Bitmap bmp = new Bitmap(width,height, PixelFormat.Format32bppArgb);
            BitmapData bits = bmp.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, bmp.PixelFormat);
            unsafe
            {
                for (int y = 0; y < height; y++)
                {
                    int* row = (int*)((byte*)bits.Scan0 + (y * bits.Stride));
                    for (int x = 0; x < width; x++)
                    {
                        row[x] = data[y * width + x];
                    }
                }
            }
            bmp.UnlockBits(bits);
    

    With (as test data):

        public static int[] GetData(out int width, out int height)
        {
            // diagonal gradient over a rectangle
            width = 127;
            height = 128;
            int[] data =  new int[width * height];
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int val = x + y;
                    data[y * width + x] = 0xFF << 24 | (val << 16) | (val << 8) | val;
                }
            }
            return data;
        }
    

提交回复
热议问题