简体   繁体   English

Android:如何将位图写入内部存储

[英]Android: How to write a Bitmap to internal storage

I am making an app that gets images from a URL. 我正在制作一个从URL获取图像的应用程序。 I want to be able to store these images on the phone so that if the url is the same as before, the user won't have to wait for the image to load but instead the app will pull it up (as it has already been received once). 我希望能够将这些图像存储在手机上,以便如果url与以前相同,则用户不必等待图像加载,而是由应用程序将其拉起(因为它已经收到一次)。

Here is my code right now: 现在是我的代码:

            URL url2 = new URL("http://ddragon.leagueoflegends.com/cdn/5.9.1/img/champion/" + champ + ".png");
            InputStream is = new BufferedInputStream(url2.openStream());
            //Save is to file
            FileOutputStream fos = null;
            try {
                fos = context.openFileOutput("temp_file", Context.MODE_PRIVATE);
                int b;
                while( (b = is.read()) != -1){
                    fos.write(b);
                }
                fos.close();
            } catch (FileNotFoundException asdf) {
                asdf.printStackTrace();
            }
            bd = BitmapFactory.decodeStream(is);

However, there is no fos.write() for a Bitmap. 但是,位图没有fos.write()。 Also, I'm not sure how to excess the file either. 另外,我也不知道如何删除文件。

Any help would be great :) 任何帮助将是巨大的:)

The Bitmap class has a compress() method for writing to an OutputStream Bitmap类具有用于写入OutputStreamcompress()方法。

bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

This will compress the bitmap using PNG format, which is lossless, so you won't sacrifice image quality by doing the compression. 这将使用无损的PNG格式压缩位图,因此您不会通过压缩来牺牲图像质量。

To access the file after it is written, use the decodeFile() method of BitmapFactory 要在写入文件后访问文件,请使用BitmapFactorydecodeFile()方法

Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM