Converting RGB bytes to a valid image

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HaLo2FrEeEk
    Contributor
    • Feb 2007
    • 404

    Converting RGB bytes to a valid image

    I have a file containing raw RGB bytes for an image. The image is 512x288 and has 3 color channels, so red, green, and blue. The images are always 3 channels, and are always 512x288, meaning there are always going to be 512*288*3 bytes (442,368).

    I need a way to load this up into a C Sharp program and display it or save it out as a PNG. Is something like this possible? I could have sworn that Bitmap() could automatically convert from raw bytes to an image, but it says a parameter is not valid. Here's the very simple starting code I'm using:

    Code:
    private void getImg(string filename)
            {
                FileStream fs = finfo.OpenRead();
                BinaryReader br = new BinaryReader(fs);
                byte[] imgBytes = br.ReadBytes((int)br.BaseStream.Length);
                memImg = new MemoryStream(imgBytes);
                img = new Bitmap(memImg);
                displayImg();
            }
    
            private void displayImg()
            {
                pictureBox1.Image = img;
            }
    When I open a "valid" image, like a png or jpg, it works fine. But when I try to open one of my rgb files it gives me the error.
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    With the RGB files, you could always set the pixel data on a blank bitmap, couldn't you?



    As long as you know how that RGB data is stored, you should be able to do this. You'd also need to initialize with width and height info. That's the reason what you haven't isn't working... the Bitmap class doesn't know what straight RGB data means... typically images have a header associated with them but in this case, that's not present.

    Comment

    • HaLo2FrEeEk
      Contributor
      • Feb 2007
      • 404

      #3
      Yeah, I actually ended up doing just that. Read the raw file into a byte array then iterated through it 3 bytes at a time with a while loop reading the individual bytes into a new Color.FromArgb( ), then progressing the loop until the index equaled the length of the byte array.

      I even figured out how to save the resulting Bitmap into a PNG file, which is what I actually wanted to be able to do.

      Comment

      Working...