[英]Android - Bitmap Null object reference
在我的應用程序中,我正在使用 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
方法。
謝謝@frogatto,我在這里給出詳細的例子,
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
.....
callingMethod();
}
//any method where you need byte array from image url
private void callingMethod() {
Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// Bitmap is loaded, use image here
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image_arr = stream.toByteArray();
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.get().load(imageURL).into(target);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.