2015-10-17 80 views
0

我在我的應用程序中顯示圖像,我想在用戶點擊每個圖像後添加下載按鈕,圖像將自動保存到文件夾。可能嗎?直接從Android活動下載圖像

+0

均來自互聯網或您的應用程序中的圖像? – geokavel

+0

這些圖像來自哪裏?它來自服務器還是您的應用程序? –

回答

0

您可以使用Picasso庫來顯示圖像。在您的build.gradle依賴,加入這個下面的代碼:

compile 'com.squareup.picasso:picasso:2.4.0' 

現在用這個來顯示圖像,您可以將按鈕的onClick()方法中添加以下代碼。

File file = new File(imagePath); 
if(file.exists()) { 
    Picasso.with(context).load(file).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView); 
} 
else { 
    Picasso.with(context).load(imageUrl).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView, new PicassoCallBack(yourImageView,imagePath)); 
} 

的picassoCallBack類將是這樣的:

public class PicassoCallBack extends Callback.EmptyCallback { 
    ImageView imageView; 
    String filename; 
    public PicassoCallBack(ImageView imageView, String filename) { 
     this.imageView = imageView; 
     this.filename = filename; 
    } 
    @Override public void onSuccess() { 
     // Log.e("picasso", "success"); 
     Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); 
     try { 
      ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos1); 
      // FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE); 
      File file = new File(filename); 
      FileOutputStream outStream = new FileOutputStream(file); 
      outStream.write(baos1.toByteArray()); 
      outStream.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    @Override 
    public void onError() { 
     Log.e("picasso", "error"); 
    } 
} 

希望它會做你的工作。

+0

這會允許用戶下載圖像嗎? – geokavel

+0

不,你應該自己下載,如果你需要,那麼我也可以提供該代碼。但是,你不是已經有一個代碼fot httpGet嗎? –

+0

他的問題是關於下載不顯示它們的圖像。 – geokavel

0

如果你已經保存在您的應用程序文件,將它複製到這個公用文件夾 File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

然後使用該技術提供here掃描圖片中的畫廊。現在當用戶打開圖庫時,他們會看到圖片。

0
private static void persistImage(Bitmap bitmap, String name) { 
    File filesDir = getAppContext().getFilesDir(); 
    File imageFile = new File(filesDir, name + ".jpg"); 

    OutputStream os; 
    try { 
     os = new FileOutputStream(imageFile); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
     os.flush(); 
     os.close(); 
    } catch (Exception e) { 
     Log.e(getClass().getSimpleName(), "Error writing bitmap", e); 
    } 
} 
0

可以使用滑翔下載圖像,我認爲這是更好然後畢加索因爲它擴展爲picasso.and更多信息,請參閱https://github.com/bumptech/glide。 這個,你只需要包括
compile 'com.github.bumptech.glide:glide:3.6.1'
依賴,然後簡單地添加此行代碼

Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);` 


其中http://goo.gl/gEgYUd是URL使用這個你沒有保持高速緩存後pass.and。

享受您的代碼:)