2017-09-06 82 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

相关问题