Metro应用程序 - 将BitmapImage转换为Byte[]数组或从Web下载图像并将其转换为Byte[]数组

3

有没有办法将BitmapImage(Windows.UI.Xaml.Media.BitmapImage)转换为Byte []数组?我试过的一切都没用...

另一个可能的情况(如果BitmapImage无法转换为字节数组)是从Web下载图像,然后将其转换为数组...

但我不知道该如何做...

如果有人有想法,那就太好了。

当前尝试:

        HttpClient http = new HttpClient();
        Stream resp = await http.GetStreamAsync("http://localhost/img/test.jpg");

        var ras = new InMemoryRandomAccessStream();
        await resp.CopyToAsync(ras.AsStreamForWrite());

        BitmapImage bi = new BitmapImage();
        bi.SetSource(ras);


        byte[] pixeBuffer = null;

        using (MemoryStream ms = new MemoryStream())
        {
            int i = bi.PixelHeight;
            int i2 = bi.PixelWidth;
            WriteableBitmap wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);

            Stream s1 = wb.PixelBuffer.AsStream();
            s1.CopyTo(ms);

            pixeBuffer = ms.ToArray();
        }

但是它不起作用...... i和i2总是被设置为0。因此,ras不能正常工作......发生了什么?谢谢
1个回答

1
在您的代码中,您从未等待BitmapImage从Web加载图像,因此当您访问它们时,它不知道其PixelWidth / PixelHeight。您可以等待它加载-例如使用{{link1:AsyncUI}}库通过调用“await bi.{{link2:WaitForLoadedAsync()}}”。如果您想访问解码像素,则这并不真正帮助您,因为BitmapImage不会向您提供访问像素的权限,并且目前没有API将BitmapImage转换为WriteableBitmap。

您可以查看有关该主题的早期问题。您需要使用类似于HttpClient.GetAsync()的方法从Web获取图像文件,然后使用类似于BitmapDecoder的方法加载它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接