In my application I am downloading the image using Picasso and converting that image in to byte array.i am calling below this method to download and convert the image to byte array.
private byte[] convertToByte(String url) {
Picasso.with(list_my_posts.this).load(url).fit().centerCrop().into(img);
Bitmap bitmap=((BitmapDrawable)img.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
byteArray= stream.toByteArray();
Toast.makeText(getApplicationContext(),"Downloaded Successfully",Toast.LENGTH_LONG).show();
return byteArray;
}
My problem is I am getting error like this.
Log
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
Can anyone help me to solve this issue.
You don't need a ImageView
merely for downloading a image and getting its byte array. Using Picasso you can register a callback to be called when download completes.
private Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
Using this callback, you can asynchronously download images:
Picasso.with(context).load(url).into(target);
Also to convert a Bitmap to a byte array, you can first compress the bitmap and then save it into a output stream:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
If you don't want to compress, you can use Bitmap.copyPixelsToBuffer
method.