3

所以我基本上想做的是从一个url(png、jpg等)读取任何类型的图像,并能够获得它的纯像素数据。到目前为止,我有这个代码。

  public static async Task<BitmapImage> DownloadImageFromWebsiteAsync(string url)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            using (WebResponse response = await request.GetResponseAsync())
            {
                Stream imageStream = response.GetResponseStream();

                using (var result = new MemoryStream())
                {
                    await imageStream.CopyToAsync(result);
                    byte[] array = result.ToArray();
                    return await ByteArrayToBitmapImage(array);
                }

            }
        }
        catch (WebException ex)
        {
            Debug.WriteLine(ex.Message);
            return null;
        }
    }

    private static async Task<BitmapImage> ByteArrayToBitmapImage(byte[] byteArray)
    {
        var bitmapImage = new BitmapImage();

        var stream = new InMemoryRandomAccessStream();
        await stream.WriteAsync(byteArray.AsBuffer());
        stream.Seek(0);

        bitmapImage.SetSource(stream);

        return bitmapImage;
    } 

由于 jpeg 之类的编码,将纯 byte[] 作为像素获取是行不通的。我想知道他们是否有任何方式从 url 下载图像、解码并检索像素缓冲区。非常感谢您的帮助。谢谢你。

4

1 回答 1

2

试试这个。您需要using System.Runtime.InteropServices.WindowsRuntime;手动添加。

private async Task<byte[]> GetBytesFromImage(string URL)
{
    byte[] srcPixels;
    var uri = new Uri(URL);
    var streamRef = RandomAccessStreamReference.CreateFromUri(uri);

    using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
    {
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
        PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync();
        srcPixels = pixelProvider.DetachPixelData();
    }

    return srcPixels;
}
于 2013-08-31T03:48:52.877 回答