liotims
liotims

Reputation: 444

Get Bitmap from an ImageView in Monodroid project

Is it possible to retrieve the bitmap of an imageView ?

I tried this but I'm getting NullPointerException and the edited code don't work in monodroid

Upvotes: 1

Views: 1482

Answers (3)

liotims
liotims

Reputation: 444

Thanks for your answer. Finally I did it like that :

var imageView = FindViewById<ImageView>(Resource.Id.image);
Bitmap bmp = ((BitmapDrawable)imageView.Drawable).Bitmap;

ps: I had a NullPointerException because the imageView was in another view.

Upvotes: 2

Kosh
Kosh

Reputation: 6334

here is a working example i'm using it.

            view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap save = view.getDrawingCache();

where view is ImageView and if you trying to save it. well here is my saving method to get the view from my imageview and save it as .PNG

    void Save() {
    if (null != view.getDrawable()) {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        save = view.getDrawingCache();
        final File myDir = new File(folder);
        myDir.mkdirs();
        final Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        final String fname = "StyleMe-" + n + ".png";
          file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            final FileOutputStream out = new FileOutputStream(file);
            save.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://"
                            + Environment.getExternalStorageDirectory())));
            Toast.makeText(getApplication(), "Image Saved",
                    Toast.LENGTH_SHORT).show();
        } catch (final Exception e) {
            Toast.makeText(getApplication(),
                    "Something Went Wrong check if you have Enough Memory",
                    Toast.LENGTH_LONG).show();
        }
    } else {
        final Toast tst = Toast.makeText(getApplication(),
                "Please Select An Image First", Toast.LENGTH_LONG);
        tst.setGravity(Gravity.CENTER, 0, 0);
        tst.show();
    }
    view.setDrawingCacheEnabled(false);
}

and here is my variables.

        String folder = "/sdcard/Pictures/StyleMe";
        static File file;

Upvotes: 1

Mike Stonis
Mike Stonis

Reputation: 2188

You should be able to get access to the assigned image via the Drawable property. Make sure to check for null before accessing it.

Upvotes: 1

Related Questions