2017-10-15 83 views
0

在我的應用程序中,我使用picasso下載圖像並將該圖像轉換爲字節數組。我在下方調用此方法下載並將圖像轉換爲字節數組。Android - 位圖空對象引用

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 

誰能幫我解決這個問題。

+0

可能重複[什麼是NullPointerException,以及如何解決它?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix -it) – user1506104

+0

畢加索操作是異步的。當您嘗試在下一行中檢索圖像時,圖像將不會被加載到「ImageView」中。 –

+0

@MikeM。請任何代碼片段。 –

回答

1

您不需要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方法。

+0

@Frogatto非常感謝你,它的工作很好。 –

+0

@Rajkumar我很高興能爲您提供幫助。如果您的問題已解決,請考慮我的答案[_accepting_](https://stackoverflow.com/help/someone-answers)。不僅是這篇文章,你的所有文章。請接受你的問題的最佳答案。這就是Stack Overflow用戶應該這樣做的。 –