2017-09-06 121 views
0

我已經創建了應用程序,從Facebook加載圖片。我使用畢加索。畢加索將設置圖像結果到我的Imageview。我想要將該圖像轉換爲位圖。如何從imageview中獲取drawable並將其轉換爲位圖?

這裏是我的代碼來從Facebook獲得的圖像:

URL imageURL = new URL("https://graph.facebook.com/"+id+"/picture?type=large");     
Picasso.with(getBaseContext()).load(imageURL.toString()).into(ImageView); 

這裏是我的代碼來獲取圖像,並轉換爲位圖:(不行)

BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable(); 
Bitmap bitmap = drawable.getBitmap(); 
bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true); 
ImageViewTest.setImageBitmap(bitmap); 

ImageView.getDrawable()總是返回null。

我需要你的幫助。 謝謝

+0

爲什麼不能有畢加索只是給你的位圖,當你找回? – CommonsWare

+0

但我看到它的參數是imageview。你的想法是將imageview轉換爲位圖? –

+0

畢加索可以做多種選擇。請參閱[此答案](https://stackoverflow.com/a/46082179/115145)和[此答案](https://stackoverflow.com/a/46081082/115145)。 – CommonsWare

回答

1

看起來像加載圖像到ImageView工作?可能發生的情況是,在畢加索完成加載圖像之前您正在調用ImageView.getDrawable()。你什麼時候調用getDrawable代碼?嘗試做類似:

Picasso.with(getBaseContext()).load(imageURL.toString()) 
    .into(ImageView, new com.squareup.picasso.Callback() { 
     @Override 
     public void onSuccess() { 
      BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable(); 
      ... 
     } 

     @Override 
     public void onError() { 

     } 
}); 
0
// Your imageview declaration 
ImageView iv; 
// Enable cache of imageview in oncreate 
iv.setDrawingCacheEnabled(true); 
// Get bitmap from iv 
Bitmap bmap = iv.getDrawingCache(); 
0

這應該是一個的AsyncTask裏面:

try { 
    URL url = new URL("http://...."); 
    Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
} catch(IOException e) { 
    System.out.println(e); 
} 
+0

謝謝。它的工作原理,但我們需要使用AsyncTask。 :) –

+0

請接受這個答案,讓其他人可能會得到幫助 –

0

您可以通過下面的代碼做

ImageView img; 
img.setDrawingCacheEnabled(true); 
Bitmap scaledBitmap = img.getDrawingCache(); 
1

您應該使用Picasso API完成你想要做的事情。

一種選擇是提供一個Target監聽器設置它的ImageView這樣前執行Bitmap操作:

Picasso.with(getBaseContext()) 
     .load("https://graph.facebook.com/" + id + "/picture?type=large") 
     .into(new Target() { 
      @Override 
      public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { 
       // Manipulate image and apply to ImageView 
      } 

      @Override 
      public void onBitmapFailed(Drawable errorDrawable) { 

      } 

      @Override 
      public void onPrepareLoad(Drawable placeHolderDrawable) { 

      } 
     }); 

或者更好的是,使用Picasso到perfom調整操作,不要做任何Bitmap操縱自己,就像這樣:

Picasso.with(getBaseContext()) 
     .load("https://graph.facebook.com/" + id + "/picture?type=large") 
     .resize(70, 70) 
     .into(ImageView); 
+0

你可能知道這一個! https://stackoverflow.com/q/46131941/294884 – Fattie

相關問題