Load Image With Picasso to a bitmap first

2019-07-02 00:30发布

问题:

I'm using Picasso. And i want to add the image to bitmap first and then add it to an imageview. I'm using the following line of code that adds an image from gallery with uri and show it on image view. I want to save it on a bitmap first. what should i do:

Picasso.with(this).load(uriadress).into(imageView);

but i want to save it on a bitmap first.

回答1:

Picasso holds Target instance with weak reference.
So it is better to hold Target as instance field.
see: https://stackoverflow.com/a/29274669/5183999

private Target mTarget;

void loadImage(Context context, String url) {

    final ImageView imageView = (ImageView) findViewById(R.id.image);

    mTarget = new Target() {
        @Override
        public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
            //Do something
            ...

            imageView.setImageBitmap(bitmap);
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };

    Picasso.with(context)
            .load(url)
            .into(mTarget);
}


回答2:

You can do like this

private Target image;
image = 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 outstream = new FileOutputStream(file);
                        bitmap.compress(CompressFormat.JPEG, 75, outstream);
                        outstream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
Picasso.with(this)
        .load(currentUrl)
        .into(image);