2015-10-17 82 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。

享受您的代码:)