Saving image from url using Picasso?

后端 未结 4 2101
庸人自扰
庸人自扰 2020-12-03 06:48

I\'m trying save an image using API Picasso. To do it I\'m trying use Target to save but I can\'t do this work.

How could I do this ?

Trying

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 07:27

    Solved. now works fine!

    I did

    //save image
        public static void imageDownload(Context ctx, String url){
            Picasso.with(ctx)
                    .load("http://blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png")
                    .into(getTarget(url));
        }
    
        //target to save
        private static Target getTarget(final String url){
            Target target = 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() + "/" + url);
                            try {
                                file.createNewFile();
                                FileOutputStream ostream = new FileOutputStream(file);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                                ostream.flush();
                                ostream.close();
                            } catch (IOException e) {
                                Log.e("IOException", e.getLocalizedMessage());
                            }
                        }
                    }).start();
    
                }
    
                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
    
                }
    
                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
    
                }
            };
            return target;
        }
    

提交回复
热议问题