Android 保存图像并将其加载到本地存储

Android 保存图像并将其加载到本地存储,android,Android,为了缓存,我尝试将少量图像保存到本地存储 保存部分如下所示: Bitmap bmp = ImagesHelper.loadBitmap(url, 3); //here the image is downloaded from web String fname = item.getItemID() + ".png"; //item is my object if(fname != null){ try { FileOutputStream fos = context.o

为了缓存,我尝试将少量图像保存到本地存储

保存部分如下所示:

Bitmap bmp = ImagesHelper.loadBitmap(url, 3);  //here the image is downloaded from web
String fname = item.getItemID() + ".png";  //item is my object
if(fname != null){
    try {
        FileOutputStream fos = context.openFileOutput(fname, Context.MODE_PRIVATE);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
此方法有效,不会引发异常。 现在不工作的部分是cumming,从本地存储器加载映像:

String fname = item.getItemID() + ".png";  //item is my object
if(file.exists()){
    try {
        Bitmap cacheImg = BitmapFactory.decodeFile(file.getAbsolutePath());
        return cacheImg;
    }
    catch(Exception ex){
        Log.e(Constants.TAG, "Error loading cache image", ex);
    }
}
此代码总是出现异常-文件存在,但无法加载图像


错误在哪里?这是将文件保存/加载到本地存储的正确方法吗?

您在哪里初始化了
文件
?是否也可以发布该初始化代码?file.exists()返回true。错误在位图加载程序中。如果
file.exists()
返回true,并不意味着它指向正确的文件。第二次初始化文件
file
时,它可能在不同的目录中创建了一个新的空文件,对吗?这就是为什么要检查目录是否正确的原因