-1

Can someone explain me how an image converted to byte array? I need the theory. I want to use the image for AES encryption {VB .Net), so after I use OpenFile Dialog, my app will load the image and then process it into byte array, but I need the explanation for that process (how pixels turn into byte array) Thanks for the answer and sorry for the beginner question. Reference link accepted :)

2 Answers2

1

When you read the bytes from the image file via File.ReadAllBytes(), their meaning depends on the image's file format.
The image file format (e.g. Bitmap, PNG, JPEG2000) defines how pixel values are converted to bytes, and conversely, how you get pixel values back from bytes.
The PNG and JPEG formats are compressed formats, so it would be difficult for you to write code to do that. For Bitmaps, it would be rather easy because it's a simple format. (See Wikipedia.)

But it's much simpler. You can just use .NET's Bitmap class to load any common image file into memory and then use Bitmap.GetPixel() to access pixels via their x,y coordinates.
Bitmap.GetPixel() is slow for larger images, though. To speed this up, you'll want to access the raw representation of the pixels directly in memory. No matter what kind of image you load with the Bitmap class, it always creates a Bitmap representation for it in memory. Its exact layout depends on Bitmap.PixelFormat. You can access it using a pattern like this. The work flow would be:

  1. Copy memory bitmap to byte array using Bitmap.LockBits() and Marshal.Copy().
  2. Extract R, G, B values from byte array using e.g. this formula in case of PixelFormat.RGB24:

    // Access pixel at (x,y)
    B = bytes[bitmapData.Scan0 + x * 3 + y * bitmapData.Stride + 0]
    G = bytes[bitmapData.Scan0 + x * 3 + y * bitmapData.Stride + 1]
    R = bytes[bitmapData.Scan0 + x * 3 + y * bitmapData.Stride + 2]  
    

    Or for PixelFormat.RGB32:

    // Access pixel at (x,y)
    B = bytes[bitmapData.Scan0 + x * 4 + y * bitmapData.Stride + 0]
    G = bytes[bitmapData.Scan0 + x * 4 + y * bitmapData.Stride + 1]
    R = bytes[bitmapData.Scan0 + x * 4 + y * bitmapData.Stride + 2]
    A = bytes[bitmapData.Scan0 + x * 4 + y * bitmapData.Stride + 3]
    
Community
  • 1
  • 1
Norman
  • 1,975
  • 1
  • 20
  • 25
0

Each Pixel is a byte and the image is made by 3 or 4 bytes, depending of its pattern. Some images has 3 bytes per pixel (related to Red, Greed and Blue), other formats may require 4 bytes (ALpha Channel, R, G and B).

You may use something like:

 Dim NewByteArray as Byte() = File.ReadAllbytes("c:\folder\image")

The NewByteArray will be fulfilled with every byte of image and you need to process them using AES, regardless of its position or meaning.

David BS
  • 1,822
  • 1
  • 19
  • 35