我正在制作一个从 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 格式压缩位图,因此您不会因压缩而牺牲图像质量。
写入后要访问文件,使用BitmapFactory
的decodeFile()
方法
Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);
关于java - Android:如何将位图写入内部存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630770/