2017-04-12 170 views
0

我已經存儲在服務器上的圖像,現在我想從android代碼下載該圖像。我正在使用picasso庫從服務器加載圖像。如何在android中使用picasso庫保存圖片?

但我不知道如何下載並將其保存在我的SDCard中(僅限使用Picasso庫或其他庫)。 所以,任何人都會向我推薦任何工作代碼!

我使用這個代碼

Picasso.with(this).load("server url").fetch(new Callback() { 
     @Override 
     public void onSuccess() { 

     } 

     @Override 
     public void onError() { 

     } 
    }); 
+0

如果你想將它保存到特定的文件夾,然後使用_Target_回調用於picasso這將返回位圖,您可以將該位圖保存到特定文件夾 – Piyush

+0

我也使用回調,但我不知道從哪裏我可以得到ima GE。 – Mehul

+1

在_onBitmapLoaded_方法中,您可以獲取位圖,這將是您的圖像。 – Piyush

回答

0
//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) { 

      } 

使用上面的代碼保存的位圖外部存儲..Please確保您的動態權限和清單文件已經建立properly.Please按照此討論Saving image from url using Picasso?

+0

是的,下一次給你找到解決方案的網址。 [http://stackoverflow.com/a/32799659/3763848](http://stackoverflow.com/a/32799659/3763848) –

+0

@VassilisPallas我已經做到了 –

+0

你可以用畢加索做得更好嗎?奇怪的是,畢加索首先將jpg文件轉換爲位圖。或者一個PNG文件。很奇怪。它應該只傳遞文件的字節。或者更好地保存接收到的字節直接爲您提供文件。可以做到嗎? – greenapps

相關問題