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

标签 java android bitmap save storage

我正在制作一个从 URL 获取图像的应用程序。我希望能够将这些图像存储在手机上,这样如果 url 与以前相同,用户将不必等待图像加载,而是应用程序将其拉起(因为它已经收到一次)。

这是我现在的代码:

            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);

但是,位图没有 fos.write()。另外,我也不确定如何超出文件。

任何帮助都会很棒 :)

最佳答案

Bitmap 类有一个compress() 方法用于写入OutputStream

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

这将使用无损的 PNG 格式压缩位图,因此您不会因压缩而牺牲图像质量。

写入后要访问文件,使用BitmapFactorydecodeFile()方法

Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);

关于java - Android:如何将位图写入内部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630770/

相关文章:

java - 交易中止

java - 由于空指针异常,应用程序崩溃

JavaFX 调用目标异常

java - 从静态上下文访问非静态方法

Android 人脸检测支持

android - volley如何离线加载图片,volley是自动缓存图片还是需要缓存图片?

android - 如何直接将文件下载到Android Q(Android 10)的下载目录中

c# - BitmapSource 指向本地文件

android - 从位图中绘制圆形区域

android - Android位图OOM(内存不足错误)