How to save an image to Internal Storage and then show it on another activity?

astahirastahir USMember ✭✭

Hi all,

I have two activities on which I need to show the same image. On the first screen, I download it from a web URL and show it but I don't want to do the same on second screen. I want to save it to Internal Storage when it gets downloaded on the first screen and then simply retrieve it from there to show on second activity. How can I do that?

Here is my code that I am using on first activity:

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        this.SetContentView (Resource.Layout.Main);

        String uriString = this.GetUriString();
        WebClient web = new WebClient ();
        web.DownloadDataCompleted += new DownloadDataCompletedEventHandler(web_DownloadDataCompleted);
        web.DownloadDataAsync (new Uri(uriString));
    }

    void web_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            RunOnUiThread(() =>
                Toast.MakeText(this, e.Error.Message, ToastLength.Short).Show());
        }
        else
        {
            Bitmap bm = BitmapFactory.DecodeByteArray(e.Result, 0, e.Result.Length);

            // THIS IS WHERE I NEED TO SAVE THE IMAGE IN INTERNAL STORAGE //

            RunOnUiThread(() =>
                {
                    ProgressBar pb = this.FindViewById<ProgressBar> (Resource.Id.custLogoProgressBar);
                    pb.Visibility = ViewStates.Gone;

                    ImageView imgCustLogo = FindViewById<ImageView>(Resource.Id.imgCustLogo);
                    imgCustLogo.SetImageBitmap(bm);
                });
        }
    }

Best Answer

Answers

  • astahirastahir USMember ✭✭

    Guys, I'm still waiting for some help...

  • CheesebaronCheesebaron DKInsider, University mod

    What is it that you do not understand? What have you tried?

    Hint: Look at Bitmap.Compress() and the usual System.IO stuff. There should be samples in the docs that describe file manipulation.

  • astahirastahir USMember ✭✭

    @Cheesebaron‌ - here is what I did inspired by this:

                Bitmap bm = BitmapFactory.DecodeByteArray(e.Result, 0, e.Result.Length);
    
                ContextWrapper cw = new ContextWrapper(this.ApplicationContext);
                File directory = cw.GetDir("imgDir", FileCreationMode.Private);
                File myPath = new File(directory, "test.png");
    
                FileOutputStream fos = null;
                try 
                {
                    fos = new FileOutputStream(myPath);
                    bm.Compress(Bitmap.CompressFormat.Png, 100, fos);
                    fos.Close();
                }
                catch (Exception ex) 
                {
                    System.Console.Write(ex.Message);
                }
    

    However, the code does not compile and I get an exception where I call bm.Compress(). It says:

    Error CS1503: Argument 3: cannot convert from 'Java.IO.FileOutputStream' to 'System.IO.Stream'

  • astahirastahir USMember ✭✭

    I would appreciate some help guys...

  • astahirastahir USMember ✭✭

    @TomOpgenorth‌ - thanks Tom for coming to my rescue, got it working.

  • MelaniMelani IDMember

    How the code about the picture not from downloaded picture? It same or not?

  • astahirastahir USMember ✭✭

    @Melani - I don't fully understand what you are saying. If you're asking whether the code written by Tom will work for an image not downloaded from somewhere then the answer is 'Yes'. It is because it has nothing to do with downloading, the code simply saves a Bitmap at a given location.

  • MelaniMelani IDMember
    edited May 2016

    I am so sorry with my english. I mean how is the code if the picture from gallery in Android? Is it the code same or not? Anyway the picture in gallery has not downloaded but take it with camera. Do you understand what i'm trying to say?

  • astahirastahir USMember ✭✭

    @Melani - It doesn't matter where the image is coming from. The idea here is that you already have a Bitmap object from anywhere (web, gallery, camera, etc.) and then you can use the code in above posts to save that image to a particular location on your device. If you want, you can later access it from the location where you saved it.

  • Any one help me to store this image(imageView) in internal storage ....!
    protected override void OnCreate(Bundle bundle)
    {
    base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            button = FindViewById<Button>(Resource.Id.myButton);
            button.Click += delegate {
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(
                    Intent.CreateChooser(imageIntent, "Select photo"), 0);
    
            };
    
        }
    

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
    base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
    
                var imageView =
                    FindViewById<ImageView>(Resource.Id.myImageView);
                imageView.SetImageURI(data.Data);
    
            }
        }
    
  • guys help me to solve this
    am waiting for your replay...!

  • SamirgcSamirgc USMember ✭✭

    Please follow along to get the solution for xamarin forms :smile:

  • marcuskongmarcuskong USMember

    @hariharanArumugam You can save it like this. I am using basic saving button and im doing the same thing, sorry for the late reply :smile:

    private void BtnSave_Click(object sender, EventArgs e)
    {

            if (txtCode.Text == "")
            {
                Toast.MakeText(this, "Item Code can't be empty...", ToastLength.Short).Show();
                txtCode.RequestFocus();
                return;
            }
            else if (txtDescription.Text == "")
            {
                Toast.MakeText(this, "Item Category can't be empty...", ToastLength.Short).Show();
                txtDescription.RequestFocus();
                return;
            }
            else if (txtDescription2.Text == "")
            {
                Toast.MakeText(this, "Item Description can't be empty...", ToastLength.Short).Show();
                txtDescription2.RequestFocus();
                return;
            }
            else if (txtPrice.Text == "")
            {
                Toast.MakeText(this, "Item Price can't be empty...", ToastLength.Short).Show();
                txtPrice.RequestFocus();
                return;
            }
            else
            {
                ItemMaster _itemMaster = new ItemMaster();
                _itemMaster = _ItemMasterDAL.GetItemByCode(txtCode.Text);
    
                if (_itemMaster != null)
                {
                    Toast.MakeText(this, "Code already exists, try another!", ToastLength.Short).Show();
                    txtCode.RequestFocus();
                    return;
                }
                else
                {
                    ItemMaster _ItemMaster = new ItemMaster();
    
                    _ItemMaster.Description = itemcategory[value].Description;
                    _ItemMaster.Code = txtCode.Text;
                    _ItemMaster.Description2 = txtDescription2.Text;
                    _ItemMaster.Price = txtPrice.Text;
    

    //save the image you get from the gallery
    _ItemMaster.FileName = ImageByte;

                    _ItemMaster.Status = GlobalVariables.StatusActive;
                    _ItemMaster.UpdatedUser = GlobalVariables.UserName;
                    _ItemMaster.UpdatedDateTime = LocalDateTime.GetDeviceDateTime(DateTime.Now);
    
                    _ItemMasterDAL.Insert(_ItemMaster);
    
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.SetTitle("Information");
                    alert.SetMessage("Item Create Successful..");
                    alert.SetPositiveButton("OK", (senderAlert, args) =>
                    {
                        StartActivity(typeof(Itemmaster));
                        Finish();
                    });
    
                    Dialog dialog = alert.Create();
                    dialog.Show();
                }
            }
        }
    
Sign In or Register to comment.