开发者

Read pixel data from an image file in .NET

开发者 https://www.devze.com 2022-12-22 07:53 出处:网络
I am trying to read in the pixel data from an image file as a byte[], for in开发者_如何学JAVA-memory storage.(The byte array will later be fed to a bitmap image object, but I want the data in memory s

I am trying to read in the pixel data from an image file as a byte[], for in开发者_如何学JAVA-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.)


Have you considered just loading your image into a CachedBitmap instead of using your own caching mechanism?

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.cachedbitmap.aspx


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 a byte[] goes away, and the problem is solved.


In .NET 4.5, the following actually works:

ImageConverter ic = new ImageConverter(); 
return (byte[])ic.ConvertTo(imageUri, typeof(byte[]));

My actual implementation was:

Image img;
img = Image.FromFile(fi.FullName);
ImageConverter ic = new ImageConverter();
byte[] pixels = (byte[])ic.ConvertTo(img, typeof(byte[]));


Have you played around with the ImageConverter class in System.Drawing?

You might be able to do something like

private byte[] GetImageBytes(Uri imageUri) 
{
    ImageConverter ic = new ImageConverter();
    return (byte[])ic.ConvertTo(imageUri, typeof(byte[]));
}

There might be some methods relating to copying pixels in the ImageConverter class or in a similar class in System.Drawing

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号