如何从imageview获取drawable并转换为位图?

时间:2017-09-06 17:13:09

标签: android bitmap picasso

我已经创建了从facebook加载图片的应用程序。我用毕加索。毕加索将图像结果设置为我的Imageview。我想将该图像转换为位图。

以下是我从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。

我需要你的帮助。 谢谢

5 个答案:

答案 0 :(得分:1)

将图像加载到ImageView中是否有效?可能发生的是你在Picasso加载图像之前调用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() {

      }
});

答案 1 :(得分:1)

您应该使用Picasso API来完成您要执行的操作。

一种选择是提供一个Target监听器来执行Bitmap操作,然后在ImageView上进行设置:

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执行调整大小操作,不要自己进行任何Bitmap操作,如下所示:

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

答案 2 :(得分:0)

    if (isset($_SESSION["cart_item"])) {
       // make sure the cart_item key exists before adding anything to it.
       $_SESSION['cart_item'] = array();
       $_SESSION["cart_item"][] = $array;
    } 
    else {
       $_SESSION["cart_item"][] =  $array;
    } 

答案 3 :(得分:0)

这应该在AsyncTask中:

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

答案 4 :(得分:0)

您可以通过以下代码

来完成
 ImageView img;
 img.setDrawingCacheEnabled(true);
 Bitmap scaledBitmap = img.getDrawingCache();
相关问题