Monday, August 12, 2013

How to download image from web in Mono for Android?

Note:The  Image downloaded can be seen only in Mobile Device not in Emulator.

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Java.Net;
using Android.Util;
using Java.IO;
using System.Net;
using System.IO;

namespace AndroidApplication3
{
    [Activity(Label = "AndroidApplication3", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        public static string SD_CARD = "sdCard";
        string filename = "/sdcard/barn.jpg";

         string path = Android.OS.Environment.ExternalStorageDirectory.Name + "/image_name.png";

        //string path = "/sdcard/MyImages/image_name.png";

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            button.Click += delegate
            {
                string imageUrl = "http://t0.gstatic.com/images?q=tbn:ANd9GcS1EVyi66BGmy-b2Nqsyw2lPjsyb3MFUxYillTeiQ4ecnPG7qPVRA";
                byte[] imageBytes;
                HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
                WebResponse imageResponse = imageRequest.GetResponse();
                Stream responseStream = imageResponse.GetResponseStream();
                using (BinaryReader br = new BinaryReader(responseStream))
                {
                    imageBytes = br.ReadBytes(500000);
                    br.Close();
                }
                responseStream.Close();
                imageResponse.Close();
                FileStream fs = new FileStream(path, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                try
                {
                    bw.Write(imageBytes);
                }
                finally
                {
                    fs.Close();
                    bw.Close();
                }
            };
        }
    }
}

No comments:

Post a Comment