web-dev-qa-db-fra.com

Obtenir une image attachée à ImageView

Donné

ImageView image = R.findViewById(R.id.imageView);
image.setImageBitmap(someBitmap);

Est-il possible de récupérer le bitmap?

290
lemon
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
780
Arslan

Cela vous donnera une Bitmap parmi ImageView. Bien que ce ne soit pas le même objet bitmap que vous avez défini. C'est un nouveau.

imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();

=== EDIT ===

 imageView.setDrawingCacheEnabled(true);
 imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                   MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
 imageView.layout(0, 0, 
                  imageView.getMeasuredWidth(), imageView.getMeasuredHeight()); 
 imageView.buildDrawingCache(true);
 Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
 imageView.setDrawingCacheEnabled(false);
43
Sarwar Erfan

Écrivez ci-dessous le code

ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView);
Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();
1
Pankaj Talaviya

Ce code est meilleur.

public static  byte[] getByteArrayFromImageView(ImageView imageView)
    {
        BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView.getDrawable());
        Bitmap bitmap;
        if(bitmapDrawable==null){
            imageView.buildDrawingCache();
            bitmap = imageView.getDrawingCache();
            imageView.buildDrawingCache(false);
        }else
        {
            bitmap = bitmapDrawable .getBitmap();
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
    }
0
Ahmad Aghazadeh