WinRT将图像加载到字节数组中

时间:2012-04-16 20:15:47

标签: bytearray windows-8 microsoft-metro windows-runtime bitmapimage

我正在尝试学习如何与图像的某些WinRT(Metro)对象进行交互。基本上,我正在努力创建一个" GetPixel"和#34; SetPixel"方法易于使用(类似于System.Drawing.Bitmap中无法在Metro应用中使用的内容)。

为了测试,我创建了一个" Bitmap"类。它基于我从Metro文件选择器控件获得的IRandomAccessStream加载。我可以将像素数据加载到Byte数组中,然后从中创建一个BitmapImage,当我将其投入到Image控件中时,它会在XAML表单上正确呈现。

这是我的问题,我可以查看字节数组并查看单个ARGB值,但是它的像素数远远少于应有的值。例如,图像I加载是254×197像素(254×197×4 = 200,152)。当我使用下面的代码加载我的字节数组时,它只有16,382字节(它也没有等于4)。我想,这是压缩的?我不知道。

我的问题是,我做错了什么..我想返回代表50,038像素的200,152字节,这样我就可以创建GetPixel(x,y)和SetPixel(x,y,Color)方法。

Public Class Bitmap

    Public Sub New()

    End Sub

    Public Async Function Load(s As Windows.Storage.Streams.IRandomAccessStream) As Task
        Dim dr As New DataReader(s.GetInputStreamAt(0))
        Await dr.LoadAsync(s.Size)
        Me.Pixels = New Byte(s.Size - 1) {}
        dr.ReadBytes(Me.Pixels)

        ' We're going to get the height and the width of the image this way. ;)
        Dim bi As New BitmapImage
        Dim stream As New MemoryStream(Me.Pixels)
        bi.SetSource(New RandomStream(stream))
        Me.Width = bi.PixelWidth
        Me.Height = bi.PixelHeight
    End Function

    Public Function ToBitmapImage() As BitmapImage
        Dim bi As New BitmapImage
        Dim stream As New MemoryStream(Me.Pixels)
        bi.SetSource(New RandomStream(stream))
        Return bi
    End Function

    Public Property Pixels As Byte()
    Public Property Width As Integer = 0
    Public Property Height As Integer = 0

End Class

1 个答案:

答案 0 :(得分:6)

我有WriteableBitmapEx项目here的WinRT版本,可以满足您的需求。基本上你需要将图像加载到WriteableBitmap中,然后通过调用PixelBuffer.AsStream()来访问它的像素缓冲区。然后你需要寻找到x,y位置(y * bmp.PixelWidth + x)的流才能读取像素值。然后还将您获得的4个字节转换为适合您的像素格式。

编辑*

WriteableBitmapEx现在本身支持WinRT。