下载图像并保存 [英] Download images and save it

查看:78
本文介绍了下载图像并保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个学校的android项目. 我需要有一个下载按钮来下载图片(当我们上课时) 然后在另一个活动中显示它(即使在离线模式下也退出后)

I'm working on a school android project. I need to have a download button which downloads a picture(when we have class) And after display it in another activity(even in offline mode, and after quiting)

我尝试过毕加索,但是我无法保存它并在离线模式下使用它.

I've tried picasso, but I can't get it to save and use it in offline mode.

推荐答案

要支持脱机模式,您需要将映像保存在磁盘上,因为清除缓存时,映像也会被清除.

For you to support offline mode, You need to Save the image on your disk because when your cache is cleared, The image is cleared as well.

您可以轻松地使用Glide解决此问题,还可以将其存储在设备上并进行检索

You can easily use Glide to Solve this, also storing on device and retrieving

您可以在此处 http:/上了解有关Glide的更多信息. /inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/zh_CN

/** Download the image using Glide **/

Bitmap theBitmap = null;
theBitmap = Glide.
    with(YourActivity.this).
    load("Url of your image").
    asBitmap().
    into(-1, -1).
    get();

   saveToInternalStorage(theBitmap, getApplicationContext(), "your preferred image name");

/** Save it on your device **/

public String saveToInternalStorage(Bitmap bitmapImage, Context context, String name){


        ContextWrapper cw = new ContextWrapper(context);
        // path to /data/data/yourapp/app_data/imageDir

        String name_="foldername"; //Folder name in device android/data/
        File directory = cw.getDir(name_, Context.MODE_PRIVATE);

        // Create imageDir
        File mypath=new File(directory,name);

        FileOutputStream fos = null;
        try {

            fos = new FileOutputStream(mypath);

            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("absolutepath ", directory.getAbsolutePath());
        return directory.getAbsolutePath();
    }

/** Method to retrieve image from your device **/

public Bitmap loadImageFromStorage(String path, String name)
    {
        Bitmap b;
        String name_="foldername";
        try {
            File f=new File(path, name_);
            b = BitmapFactory.decodeStream(new FileInputStream(f));
            return b;
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        return null;
    }

/** Retrieve your image from device and set to imageview **/
//Provide your image path and name of the image your previously used.

Bitmap b= loadImageFromStorage(String path, String name)
ImageView img=(ImageView)findViewById(R.id.your_image_id);
img.setImageBitmap(b);

这篇关于下载图像并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆