从 url/http 下载并打开图片 [Android Xamarin App]
Posted
技术标签:
【中文标题】从 url/http 下载并打开图片 [Android Xamarin App]【英文标题】:Download and open picture from url/http [Android Xamarin App] 【发布时间】:2021-03-31 15:23:28 【问题描述】:你好,你们中的任何人都可以发送一个工作代码来从 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下载图片并显示在imageview中,你可以看this thread,如果你想为你的应用创建新文件夹,请看:create files on Android with Xamarin,但你需要添加关于WRITE_EXTERNAL_STORAGE
的权限,请看:Permissions In Xamarin.Android
【参考方案1】:
从 url 加载图片并在 imageview 中显示。
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_STORAGE
和READ_EXTERNAL_STORAGE
,然后您还需要在Android 6.0中进行Runtime Permission Checks。
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.
【讨论】:
非常感谢!以上是关于从 url/http 下载并打开图片 [Android Xamarin App]的主要内容,如果未能解决你的问题,请参考以下文章