直接从Android活动下载图像

问题描述 投票:0回答:5

我在我的应用程序中显示图像,我想在每个图像后添加下载按钮,当用户点击它时,图像将自动保存到文件夹。可能吗?

android download
5个回答
0
投票

如果您已将文件保存在应用程序中,请将其复制到此公用文件夹File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

然后使用here提供的技术将图片扫描到图库中。现在,当用户打开图库时,他们将看到图片。


0
投票

之前我尝试过Universal Image LoaderPicasso。你看到你需要和女巫对你来说已经足够了。也有更好的决定阅读this onethis one。它可能会帮助你:

enter image description here


0
投票

您可以使用Glide下载图像,我认为它比毕加索更好,因为它扩展了毕加索。有关更多信息,请参阅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。使用它之后,您不必维护缓存。

享受你的代码:)


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库来显示图像。在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");
    }
}

希望它能完成你的工作。

© www.soinside.com 2019 - 2024. All rights reserved.