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.
CodePudding user response:
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
CodePudding user response:
You can try this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
public class ImageUtil
{
public static Bitmap convert(String base64Str) throws IllegalArgumentException
{
byte[] decodedBytes = Base64.decode(
base64Str.substring(base64Str.indexOf(",") 1),
Base64.DEFAULT
);
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String convert(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}