Error when trying to convert ImageView to string

Advertisements

I have a ImageView that I need to create and get the bitmap of and convert to string, because I need to send the image to charquopy for procesisng. When I attempt to get the Image as a string I get the following error below:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

on this line specifically: imageString = getStringImage(bitmap);

the entire code snipped of that related to my problem:

    mImageView = (ImageView) findViewById(R.id.frame_image);

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

    String imageString = "";
    BitmapDrawable drawable;
    Bitmap bitmap;
    drawable = (BitmapDrawable)mImageView.getDrawable();
    bitmap = drawable.getBitmap();
    imageString = getStringImage(bitmap); // Error occurs in this line
}

the frame image XML:

   <ImageView
        android:id="@+id/frame_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/camera_view"
        android:layout_alignLeft="@id/camera_view"
        android:layout_alignRight="@id/camera_view"
        android:layout_alignTop="@id/camera_view" />

Output:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

I’d like to know why is it returning a null pointer given that Imageview seems to be apparently properly called.

>Solution :

You can draw the imageview on a canvas and create a bitmap out of it like this

ImageView mImageView = (ImageView) findViewById(R.id.frame_image);
Bitmap bitmap = Bitmap.createBitmap(mImageView .getWidth(), mImageView .getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
mImageView.draw(canvas);
ByteArrayOutputStream baos=new  ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
 byte [] b=baos.toByteArray();
 String imageAsString =Base64.encodeToString(b, Base64.DEFAULT);
 //Upload  imageAsString 

Leave a ReplyCancel reply