c# - 如何将图像 URL 转换为存储文件?

标签 c# url uwp storagefolder

我正在使用 Unsplash API 来获取图像。当我发送图像请求时,部分答案是图像 URL,如下所示:

https://images.unsplash.com/photo-1535159530326-d7bf54bfb24e?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjM1NDkzfQ&s

我能够将此 URL 设为 BitmapImage 并使其成为应用程序 UI 中的图像源。但我无法下载它以使其成为存储文件。

如何从此类 URL 下载图像和/或将其设为存储文件?

最佳答案

以下代码会将文件下载到本地存储,然后为您提供一个可用于设置图像源的 Uri:

    private async Task<String> DownloadImage(string url, String fileName)
    {
        const String imagesSubdirectory = "DownloadedImages";
        var rootFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(imagesSubdirectory, CreationCollisionOption.OpenIfExists);

        var storageFile = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

        using (HttpClient client = new HttpClient())
        {
            byte[] buffer = await client.GetByteArrayAsync(url);
            using (Stream stream = await storageFile.OpenStreamForWriteAsync())
                stream.Write(buffer, 0, buffer.Length);
        }

        // Use this path to load image
        String newPath = String.Format("ms-appdata:///local/{0}/{1}", imagesSubdirectory, fileName);

        return newPath;
    }

    // Here is an example of how to use the new DownloadImage() method
    private async void Button_Download(object sender, RoutedEventArgs e)
    {
        var uniqueFileName = $@"{Guid.NewGuid()}.jpg";

        String newPath = await DownloadImage("https://images.unsplash.com/photo-1535159530326-d7bf54bfb24e?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjM1NDkzfQ&s=6dbf8e03a25f469d0f845992e6b2eb9e",
            uniqueFileName);
        myImage.Source = new BitmapImage(new Uri(newPath));
    }

关于c# - 如何将图像 URL 转换为存储文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131168/

相关文章:

c# - 如何根据menustrip项目单击Windows应用程序更改按钮的css

javascript - 将 json 从 js 传递到 java 的 url 问题

xaml - 绑定(bind)到 ElementName 取决于绑定(bind)顺序

.net - dotnet 构建 UWP.sln |错误 MSB4019 Microsoft.Windows.UI.Xaml.CSharp.targets 未找到

c# - 仅限英文字符

c# - 如何将 StackFrame 集合转换为字符串?

c# - 分组依据和过滤多列

java - URL 证书问题

java - Android:如何将带有空格的 URL 字符串解析为 URI 对象?

c# - 使用AudioRender设备作为AudioGraph UWP的输入