簡體   English   中英

從加載了畢加索的 ImageView 中獲取位圖

[英]Get Bitmap from ImageView loaded with Picasso

我有一種加載圖像的方法,如果圖像尚未加載,則它會在服務器上查找它。 然后它將它存儲在應用程序文件系統中。 如果它在文件系統中,它會加載該圖像,因為這比從服務器拉取圖像要快得多。 如果您之前在未關閉應用程序的情況下加載了圖像,它將存儲在靜態字典中,以便可以在不使用更多內存的情況下重新加載,以避免內存不足錯誤。

這一切都很好,直到我開始使用畢加索圖像加載庫。 現在我正在將圖像加載到 ImageView 中,但我不知道如何獲取返回的位圖,以便我可以將其存儲在文件或靜態字典中。 這讓事情變得更加困難。 因為這意味着它每次都嘗試從服務器加載圖像,這是我不想發生的事情。 有沒有辦法在將 Bitmap 加載到 ImageView 后獲取它? 下面是我的代碼:

public Drawable loadImageFromWebOperations(String url,
        final String imagePath, ImageView theView, Picasso picasso) {
    try {
        if (Global.couponBitmaps.get(imagePath) != null) {
            scaledHeight = Global.couponBitmaps.get(imagePath).getHeight();
            return new BitmapDrawable(getResources(),
                    Global.couponBitmaps.get(imagePath));
        }
        File f = new File(getBaseContext().getFilesDir().getPath()
                .toString()
                + "/" + imagePath + ".png");

        if (f.exists()) {
            picasso.load(f).into(theView);

下面這一行是我嘗試檢索位圖時它拋出了一個空指針異常,我認為這是因為畢加索需要一段時間才能將圖像添加到 ImageView

            Bitmap bitmap = ((BitmapDrawable)theView.getDrawable()).getBitmap();
            Global.couponBitmaps.put(imagePath, bitmap);
            return null;
        } else {
            picasso.load(url).into(theView);
            return null;
        }
    } catch (OutOfMemoryError e) {
        Log.d("Error", "Out of Memory Exception");
        e.printStackTrace();
        return getResources().getDrawable(R.drawable.default1);
    } catch (NullPointerException e) {
        Log.d("Error", "Null Pointer Exception");
        e.printStackTrace();
        return getResources().getDrawable(R.drawable.default1);
    }
}

任何幫助將不勝感激,謝謝!

使用 Picasso,您不需要實現自己的靜態字典,因為它會自動為您完成。 @intrepidkarthi 是正確的,因為畢加索第一次加載圖像時會自動緩存圖像,因此它不會不斷調用服務器來獲取相同的圖像。

話雖如此,我發現自己處於類似的情況:我需要訪問下載的位圖,以便將其存儲在我的應用程序中的其他位置。 為此,我稍微調整了@Gilad Haimov 的回答:

Java,使用舊版本的畢加索:

Picasso.with(this)
    .load(url)
    .into(new Target() {

        @Override
        public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from) {
            /* Save the bitmap or do something with it here */

            // Set it in the ImageView
            theView.setImageBitmap(bitmap); 
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {}

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {}
});

Kotlin,帶有 Picasso 2.71828 版本:

Picasso.get()
        .load(url)
        .into(object : Target {

            override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) {
                /* Save the bitmap or do something with it here */

                // Set it in the ImageView
                theView.setImageBitmap(bitmap)
            }

            override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}

            override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}

        })

這使您可以在仍然異步加載它的同時訪問加載的位圖。 您只需要記住在 ImageView 中設置它,因為它不再自動為您完成。

附帶說明一下,如果您想知道圖像的來源,可以使用相同的方法訪問該信息。 上述方法的第二個參數Picasso.LoadedFrom from是一個枚舉,它讓您知道位圖是從哪個源加載的(三個源是DISKMEMORYNETWORK 。( Source )。Square Inc. 還提供了一個使用此處解釋的調試指示器查看位圖加載位置的可視化方式。

希望這可以幫助 !

Picasso 讓您可以直接控制下載的圖像。 要將下載的圖像保存到文件中,請執行以下操作:

Picasso.with(this)
    .load(currentUrl)
    .into(saveFileTarget);

在哪里:

saveFileTarget = new Target() {
    @Override
    public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + FILEPATH);
                try {
                    file.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(CompressFormat.JPEG, 75, ostream);
                    ostream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

既然您正在使用畢加索,您不妨充分利用它。 它包括一個強大的緩存機制。

在您的Picasso實例上使用picasso.setDebugging(true)來查看發生了什么類型的緩存(圖像是從磁盤、內存或網絡加載的)。 請參閱: http : //square.github.io/picasso/ (調試指標)

Picasso 的默認實例配置為( http://square.github.io/picasso/javadoc/com/squareup/picasso/Picasso.html#with-android.content.Context-

可用應用程序 RAM 的 15% 的 LRU 內存緩存

2% 存儲空間的磁盤緩存,最高 50MB 但不低於 5MB。 (注意:這僅在 API 14+ 上可用,或者如果您使用的是在所有 API 級別(如 OkHttp)上提供磁盤緩存的獨立庫)

您還可以使用Picasso.Builder指定您的Cache實例Picasso.Builder定義您的實例,並且您可以指定您的Downloader以進行更精細的控制。 (如果您在應用程序中包含OkHttp ,則會自動使用 Picasso 中的OkDownloader實現。)

在這個例子中,我用來設置折疊工具欄的背景。

public class MainActivity extends AppCompatActivity {

 CollapsingToolbarLayout colapsingToolbar;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

  colapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.colapsingToolbar);
  ImageView imageView = new ImageView(this);
  String url ="www.yourimageurl.com"


  Picasso.with(this)
         .load(url)
         .resize(80, 80)
         .centerCrop()
         .into(image);

  colapsingToolbar.setBackground(imageView.getDrawable());

}

我希望它對你有幫助。

用這個

Picasso.with(context)
.load(url)
.into(imageView new Callback() {
    @Override
    public void onSuccess() {
        //use your bitmap or something
    }

    @Override
    public void onError() {

    }
});

希望對你有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM