Metro APP - BitmapImage to Byte[] or Download Image from Web and convert it to a Byte[] Array

巧了我就是萌 提交于 2019-12-07 16:55:19

问题


Is there a way to convert a BitmapImage (Windows.UI.Xaml.Media.BitmapImage) to an Byte[] Array? Nothing I've tried work.... Another possible scenario (if BitmapImage cannot be converted to Byte array) is to download the image from web and then convert it to an array...

But I don't know how I can do that... It would be really nice, if someone have an idea.

Current try:

        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();
        }

But it doesn't work... i & i2 are always set to 0. So ras doesn't work correctly.... What's going on?

Thanks


回答1:


In your code you're never waiting for the BitmapImage to load the image from the web, so it does not know its PixelWidth/PixelHeight when you access them. You could wait for it to load - for example using the AsyncUI library by calling "await bi.WaitForLoadedAsync()". This would not really help you here if you want to access the decoded pixels since BitmapImage does not give you access to the pixels and there is currently no API to convert a BitmapImage into a WriteableBitmap.

You can check an earlier question about the topic. You would need to get the image file from the web with something like HttpClient.GetAsync(), then load it using something like BitmapDecoder.



来源:https://stackoverflow.com/questions/10472282/metro-app-bitmapimage-to-byte-or-download-image-from-web-and-convert-it-to-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!