在我的应用程序中,我正在使用 picasso 下载图像并将该图像转换为字节数组。我在此方法下方调用以下载图像并将其转换为字节数组。
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;
}
我的问题是我收到这样的错误。
日志
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
谁能帮我解决这个问题。
您不需要ImageView
仅仅用于下载图像并获取其字节数组。使用 Picasso,您可以注册在下载完成时调用的回调。
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) {
}
}
使用此回调,您可以异步下载图像:
Picasso.with(context).load(url).into(target);
同样要将位图转换为字节数组,您可以先压缩位图,然后将其保存到输出流中:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
如果不想压缩,可以使用Bitmap.copyPixelsToBuffer
方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句