0

I am using the following code and I am trying to convert a Bitmap into an array of RGB pixels (0-255). In the code below, I have comments over pseudo-code that I need help with:

    private class Rgb
    {
        public byte Red { get; set; }
        public byte Green { get; set; }
        public byte Blue { get; set; }

        public Rgb(byte red, byte green, byte blue)
        {
            Red = red;
            Green = green;
            Blue = blue;
        }
    }

    private class MyImage
    {
        private Rgb[] _pixels;
        private readonly int _width;
        private readonly int _height;

        public int Width
        {
            get { return _width; }
        }

        public int Height
        {
            get { return _height; }
        }

        public Rgb[] Pixels
        {
            get { return _pixels; }
        }

        public MyImage(int width, int height)
        {
            _width = width;
            _height = height;

            _pixels = new Rgb[_width*_height];
        }

        public static MyImage FromBitmap(Bitmap bmp)
        {
            var myImage = new MyImage(bmp.Width, bmp.Height);

            int i = 0;
            // foreach(pixel in myImage)
            // {
            //     myImage._pixels[i] = new Rgb(pixel.red, pixel.green, pixel.blue);
            //     i++;
            // }

            return myImage;
        }

        public static Bitmap ToBitmap(MyImage myImage)
        {
            var bitmap = new Bitmap(myImage.Width, myImage.Height);

            int i = 0;
            // foreach(pixel in myImage)
            // {
            //     bitmap.pixel[i].red = myImage.Pixels[i].Red;
            //     bitmap.pixel[i].green = myImage.Pixels[i].Green;
            //     bitmap.pixel[i].blue = myImage.Pixels[i].Blue;
            //     i++;
            // }

            return bitmap;
        }

I'm stuck on how to get the pixel data from a Bitmap. In addition, I need to be able to go the other way around and create a Bitmap from pixel data. Any help would be appreciated!

Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • 1
    Take a look [this](http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp) CodeProject article, you can start from there. – Alessandro D'Andria Apr 16 '14 at 17:27
  • And also take a look on [this](http://stackoverflow.com/questions/6020406/travel-through-pixels-in-bmp). – Dmitry Apr 16 '14 at 17:38

1 Answers1

0

Look at this link: http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx Careful with images in 24 bit, because (if I remember it good) they need line align to 4 bytes.

apocalypse
  • 5,764
  • 9
  • 47
  • 95