如何解决从 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 加载图片并在 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,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,length);
}
}
您需要在WRITE_EXTERNAL_STORAGE
中添加权限READ_EXTERNAL_STORAGE
和AndroidMainfeast.xml
,然后在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.
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。