从 .NET 中的图像文件读取像素数据
我正在尝试从图像文件中读取像素数据作为 byte[]
,用于内存存储。 (字节数组稍后将被提供给位图图像对象,但我希望将数据存储在内存中,这样就不会出现 I/O 阻塞。)
这就是我目前正在做的事情:
private byte[] GetImageBytes(Uri imageUri) {
//arraySize and stride previously defined
var pixelArray = new byte[arraySize];
new BitmapImage(imageUri).CopyPixels(pixelArray , stride, 0);
return pixelArray ;
}
我想知道是否有人知道一种方法获取 byte[]
数据,而不是制作 BitmapImage
然后复制所有字节。即,是否有一个 .NET 类仅从文件中传输像素数据? (我最初使用的是 File.ReadAllBytes,但这引入了图像元数据等其他内容,但没有成功。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否考虑过将图像加载到 CachedBitmap 中而不是使用您自己的缓存机制?
http://msdn.microsoft.com/ en-us/library/system.windows.media.imaging.cachedbitmap.aspx
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
我将回答我自己的问题,以防其他人发现它有用:
我最初想将数据读入字节数组的原因是这样我可以在后台线程上执行文件或网络 IO。但后来我了解了 Freeze() 方法,该方法允许在后台线程上读取图像,然后在线程之间共享。
因此,如果我冻结
BitmapImage
,将数据临时存储在byte[]
中的动力就会消失,问题就解决了。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.在 .NET 4.5 中,以下内容实际上有效:
我的实际实现是:
In .NET 4.5, the following actually works:
My actual implementation was:
您是否使用过 System.Drawing 中的 ImageConverter 类?
您也许可以执行类似的操作
There might be somemethods related to copyingpixels in the ImageConverter class or in a kind of class in System.Drawing
Have you played around with the ImageConverter class in System.Drawing?
You might be able to do something like
There might be some methods relating to copying pixels in the ImageConverter class or in a similar class in System.Drawing