C# Convert Pixel Data to Image (JPEG)

A quick and easy way of converting custom image data (e.g. RGB Array) to an actual image and saving it. Note that my way of converting it to a RGB struct first is unnecessary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    class JPEGEncoding
    {
        public struct RGB
        {
            public byte Red;
            public byte Green;
            public byte Blue;
 
            public RGB(Color inputColor)
            {
                Red = inputColor.R;
                Green = inputColor.G;
                Blue = inputColor.B;
            }
 
            public RGB(byte red, byte green, byte blue)
            {
                Red = red;
                Green = green;
                Blue = blue;            
            }
        }
 
        Bitmap RawImageSource;
 
        public JPEGEncoding(RGB[,] colorInputArray)
        {
            RawImageSource = new Bitmap(colorInputArray.GetLength(0), colorInputArray.GetLength(1));
 
            for (int j = 0; j < colorInputArray.GetLength(0); j++)
            {
                for (int i = 0; i < colorInputArray.GetLength(1); i++)
                {
                    RawImageSource.SetPixel(j, i, Color.FromArgb(colorInputArray[j, i].Red, colorInputArray[j, i].Green, colorInputArray[j, i].Blue));
                }
            }
 
        }
 
        public void SaveImage(string path)
        {
            RawImageSource.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
 
        }
    }

Leave a message

Your email address will not be published. Required fields are marked *

*