从 url/http 下载并打开图片 [Android Xamarin App]

Download and open picture from url/http [Android Xamarin App]

你好,你们中的任何一个都可以发送一个工作代码来从 android Xamarin c# 上的给定 http 地址下载照片吗? 首先,我需要为我的应用程序文件创建一个新文件夹。 我的目标是将文件从 Internet 下载到我的 Android 文件夹(最好以其原始名称保存此文件)。 下一步是在“ImageView”中显示该文件夹中的图像。同样重要的是android里面有权限,我不是很懂。 有谁能发给我,或者帮我理解和解释一下题目吗?

*实际上我有这个代码:

string address = "https://i.stack.imgur.com/X3V3w.png";
using (WebClient webClient = new WebClient())
{
     webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
     webClient.DownloadFile(address, Path.Combine(pathDire, "MyNewImage1.png"));
     //System.Net.WebException: 'An exception occurred during a WebClient request.'
}

正在从 url 加载图像并在图像视图中显示。

 private void Btn1_Click(object sender, System.EventArgs e)
    {
        var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
        imagen.SetImageBitmap(imageBitmap);
    }

    private Bitmap GetImageBitmapFromUrl(string url)
    {
        Bitmap imageBitmap = null;

        using (var webClient = new WebClient())
        {
            var imageBytes = webClient.DownloadData(url);
            if (imageBytes != null && imageBytes.Length > 0)
            {

                SavePicture("ImageName.jpg", imageBytes, "imagesFolder");
                imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
            }
        }

        return imageBitmap;
    }

下载图片并将其保存在本地存储中。

 private void SavePicture(string name, byte[] data, string location = "temp")
    {
        
        var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        documentsPath = System.IO.Path.Combine(documentsPath, "Orders", location);
        Directory.CreateDirectory(documentsPath);

        string filePath = System.IO.Path.Combine(documentsPath, name);      
        using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
        {             
            int length = data.Length;
            fs.Write(data, 0, length);
        }
    }

您需要在 AndroidMainfeast.xml 中添加权限 WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE,然后您还需要在 Android 6.0.

中添加运行时权限检查
  private void checkpermission()
    {
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the writeexternalstorage.
        }
        else
        {
            // writeexternalstorage permission is not granted. If necessary display rationale & request.
        }
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the ReadExternalStorage.
        }
        else
        {
            // ReadExternalStorage permission is not granted. If necessary display rationale & request.
        }
    }