从url下载并读取图像
本文关键字:读取 图像 下载 url | 更新日期: 2023-09-27 18:29:37
所以我基本上想做的是从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下载图像,对其进行解码,并检索像素缓冲区。非常感谢您的帮助。非常感谢。
试试这个。您需要手动添加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;
}