I am trying to read in the pixel data from an image file as a byte[], for in-memory storage. (The byte array will later be fed to a bitmap image object, but I want the data in memory so that there’s no I/O holdup.)
This is what I’m currently doing:
private byte[] GetImageBytes(Uri imageUri) {
//arraySize and stride previously defined
var pixelArray = new byte[arraySize];
new BitmapImage(imageUri).CopyPixels(pixelArray , stride, 0);
return pixelArray ;
}
I am wondering if someone knows of a way to get the byte[] data other than making a BitmapImage and then copying all of the bytes out. I.e. is there a .NET class that will just stream pixel data from the file? (I was originally using File.ReadAllBytes, but that brings in other stuff like the image metadata, and wasn’t working out.)
I will answer my own question, in case anyone else finds it useful:
The reason I had originally wanted to read the data into a byte array was so that I could do the file or network IO on a background thread. But I have since learned about the
Freeze()method, which lets the image be read on a background thread and then shared across threads.So if I freeze the
BitmapImage, the impetus for temporarily storing the data in abyte[]goes away, and the problem is solved.