Скачать изображение и показать Xamarin - PullRequest
0 голосов
/ 01 марта 2020

Я хотел бы загрузить изображения в Xamarin и показать его, но у меня есть ошибка:

"невозможно ожидать пустоту"

в строке;

var imageBytes = await webClient.DownloadDataAsync(url);

Вот код:

public async void DownloadImages()
{
     var webClient = new WebClient();
     var url = new Uri("myurl.jpg");

     var imageBytes  =  await webClient.DownloadDataAsync(url);

     if (imageBytes != null && imageBytes.Length > 0)
     {
         GridRectangleImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
     }        
}

Ответы [ 2 ]

0 голосов
/ 02 марта 2020

@ Hugokis

Выполните следующие действия, чтобы загрузить изображение и показать Xamarin

Шаг 1: - Создать проект Xamarin.

Шаг 2: - Добавление библиотеки приложений Xamarin Support v7 AppCompat. Добавить ссылку Android .Support.v7. AppCompat с помощью диспетчера пакетов NuGet

шаг 3: - Добавить код в файл app.xaml:

 <?xml version="1.0" encoding="utf-8" ?>  
<resources>  
  <style name="MyTheme" parent="MyTheme.Base">  
  </style>  
  <!--Base theme applied no matter what API-->  
  <style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">  
    <item name="windowNoTitle">true</item>  
    <!--We will be using the toolbar so no need to show ActionBar-->  
    <item name="windowActionBar">false</item>  
    <!--Set theme color from http://www.google.com/design/spec/style/color.html#color-co-->  
    <!--Color Primary is used for default action bar backround-->  
    <item name="colorPrimary">#009688</item>  
    <!--Color Primary Dark is use for status bar-->  
    <item name="colorPrimaryDark">#1976D2</item>  
    <!--ColorAccent is used as the default value for   
    ColorControlActivat1ed which is used to tint widgts-->  
    <item name="colorAccent">#FF4081</item>  
    <item name="colorControlHighlight">#FF4081</item>  
    <!--You can also set ColorControlNormal ColorControlActivated   
      ColorControlHihglight colorSwitchThumbNormal.-->  
  </style>  
</resources> 

шаг 4: - Добавить новую папку в папку ресурсов с именем values-v21. Аналогичным образом добавьте новый XAML-файл в папку values-v21 - style. xml и добавьте следующий код.

Xaml Code:

<?xml version="1.0" encoding="utf-8" ?>  
<resources>  
  <!--  
  Base Application theme for API 21+. this theme   
  replaces MyTheme from res/style.xml on API 21+ devices-->  
  <style name="MyTheme" parent="MyTheme.Base">  
    <item name="android:windowContentTransitions">true</item>  
    <item name="android:windowAllowEnterTransitionOverlap">true</item>  
    <item name="android:windowAllowReturnTransitionOverlap">true</item>  
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>  
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>  
    <item name="android:windowTranslucentStatus">true</item>  
  </style>  
</resources>  

шаг 5: - Запись класса DownloadImageFromUrl

C# Код

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using Android.App;  
using Android.Content;  
using Android.Graphics.Drawables;  
using Android.OS;  
using Android.Runtime;  
using Android.Views;  
using Android.Widget;  
using Java.IO;  
using Java.Net;  
namespace SaveWithProgress  
{  
    public class DownloadImageFromUrl : AsyncTask<string, string, string>  
    {  
        private ProgressDialog pDialog;  
        private ImageView imgView;  
        private Context context;  
        public DownloadImageFromUrl(Context context, ImageView imgView)  
        {  
            this.context = context;  
            this.imgView = imgView;  
        }  
        protected override void OnPreExecute()  
        {  
            pDialog = new ProgressDialog(context);  
            pDialog.SetMessage("Downloading file. Please wait...");  
            pDialog.Indeterminate = false;  
            pDialog.Max = 100;  
            pDialog.SetProgressStyle(ProgressDialogStyle.Horizontal);  
            pDialog.SetCancelable(true);  
            pDialog.Show();  
            base.OnPreExecute();  
        }  
        protected override void OnProgressUpdate(params string[] values)  
        {  
            base.OnProgressUpdate(values);  
            pDialog.SetProgressNumberFormat(values[0]);  
            pDialog.Progress = int.Parse(values[0]);  
        }  
        protected override void OnPostExecute(string result)  
        {  
            string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path;  
            string filePath = System.IO.Path.Combine(strongPath, "download.jpg");  
            pDialog.Dismiss();  
            imgView.SetImageDrawable(Drawable.CreateFromPath(filePath));  
        }  
        protected override string RunInBackground(params string[] @params)  
        {  
            string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path;  
            string filePath = System.IO.Path.Combine(strongPath, "download.jpg");  
            int count;  
            try  
            {  
                URL url = new URL(@params[0]);  
                URLConnection connection = url.OpenConnection();  
                connection.Connect();  
                int LengthOfFile = connection.ContentLength;  
                InputStream input = new BufferedInputStream(url.OpenStream(), LengthOfFile);  
                OutputStream output = new FileOutputStream(filePath);  
                byte[] data = new byte[1024];  
                long total = 0;  
                while ((count = input.Read(data)) != -1 )  
                {  
                    total += count;  
                    PublishProgress(""+(int)((total / 100) / LengthOfFile));  
                    output.Write(data, 0, count);  
                }  
                output.Flush();  
                output.Close();  
                input.Close();  
            }  
            catch (Exception e)  
            {  
            }  
            return null;  
        }  
    }  
}  

шаг 6: - Основное решение Open Layout Проводник-> Имя проекта-> Ресурсы-> Макет-> Main.a xml. Откройте этот основной файл макета и добавьте следующий код.

Код Xaml:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:local="http://schemas.android.com/apk/res-auto"  
    android:orientation="vertical"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent">  
    <android.support.v7.widget.Toolbar  
        android:id="@+id/toolbar"  
        android:fitsSystemWindows="true"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:minHeight="?attr/actionBarSize"  
        android:background="?attr/colorPrimary"  
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"  
        local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />  
    <Button  
        android:text="Download Image"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/btnDownload" />  
    <ImageView  
        android:src="@android:drawable/ic_menu_gallery"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:id="@+id/imageView" />  
</LinearLayout> 

шаг 7: -Основной класс активности C# Код:

using Android.App;  
using Android.Widget;  
using Android.OS;  
using Android.Support.V7.App;  
namespace SaveWithProgress  
{  
    [Activity(Label = "SaveWithProgress", MainLauncher = true , Theme ="@style/MyTheme")]  
    public class MainActivity : AppCompatActivity  
    {  
        protected override void OnCreate(Bundle savedInstanceState)  
        {  
            base.OnCreate(savedInstanceState);  
            // Set our view from the "main" layout resource  
            SetContentView(Resource.Layout.Main);  
            var btnDownload = FindViewById<Button>(Resource.Id.btnDownload);  
            var imageView = FindViewById<ImageView>(Resource.Id.imageView);  
            btnDownload.Click += delegate   
            {  
                DownloadImageFromUrl download = new DownloadImageFromUrl(this, imageView);  
                download.Execute("http://www.qygjxz.com/data/out/244/4304228-wallpaper-phone-hd.jpg");  
            };  
        }  
    }  
}  

шаг 8: - Разрешение от устройства

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
    <uses-permission android:name="android.permission.INTERNET" />  

Надеюсь, приведенный выше код будет вам полезен.

Спасибо.

0 голосов
/ 02 марта 2020

Если вы используете DownloadDataAsyn c: по завершении загрузки возникает событие DownloadDataCompleted. Загруженные данные доступны в свойстве Result. скачанный ресурс:

public async void DownloadImages()
{
    var webClient = new WebClient();
    var url = new Uri("myurl.jpg");

    var imageBytes = await webClient.DownloadDataTaskAsync(url);

    if (imageBytes != null && imageBytes.Length > 0)
    {
        GridRectangleImage.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
    }
}
...