我在我的应用程序中显示图像,我想在每个图像后添加下载按钮,当用户点击它时,图像将自动保存到文件夹。有可能吗?
答案 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");
}
}
希望它能完成你的工作。
答案 1 :(得分:0)
如果您已将文件保存在应用程序中,请将其复制到此公用文件夹
File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
然后使用提供的here技术将图片扫描到图库中。现在,当用户打开图库时,他们会看到图片。
答案 2 :(得分: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);
}
}
答案 3 :(得分:0)
您可以使用 Glide 下载图片,我认为它比 picasso 更好,因为它扩展了picasso。有关详细信息,请参阅https://github.com/bumptech/glide。
为此,您只需将<{1}}
加入依赖关系,然后只需添加此代码行
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);`
其中http://goo.gl/gEgYUd
是要传递的URL。使用此功能后,您无需维护缓存。
享受您的代码:)
答案 4 :(得分:0)
之前我尝过Universal Image Loader和Picasso。 你看到你需要和女巫对你来说已经足够了。 还有更好的决策阅读this one和this one。 它可以帮到你: