Android从内部文件返回位图

时间:2013-09-23 15:24:27

标签: android

您好我已经从URL下载了一个图像并将其作为位图写入文件。我试图从文件中检索位图并显示它。有谁知道如何做到这一点?继续我所尝试的并不是错误,但它没有显示图像。

Global.java

public static void saveBitmapToFile(Context activityContext, Bitmap bitmap, String FileName){

    try{
        File file = new File(FileName);
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();}
    catch (Exception e) {
        e.printStackTrace();
        Log.i(null, "Save file error!");

        }

    }

    public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
        Bitmap bitmap = BitmapFactory.decodeFile(FileName);
        return bitmap;

    }

GetBitmap.java

 public void downloadUserPhoto(){



            String userPhotoUrl = "http://static.bbci.co.uk/h4discoveryzone/ic/newsimg/media/images/229/129/68805000/jpg/_68805145_pahs2.jpg"

            userPhoto = Global.createBitmapFromUrl(this, userPhotoUrl); 
            Global.saveBitmapToFile(this, userPhoto, "user_photo");
}                       

 public void getUserPhoto(){
         loadingText.setText("Getting User Pictures..."); 
          Bitmap setUserPhoto = Global.returnBitmapFromFile(this, "user_photo");
         logo.setImageBitmap(setUserPhoto);


         }

1 个答案:

答案 0 :(得分:1)

尝试使用FileInputStream

打开它
public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){
    FileInputStream in = new FileInputStream(FileName);
        BufferedInputStream buf = new BufferedInputStream(in);
        byte[] bitMapA= new byte[buf.available()];
        buf.read(bitMapA);
        buf.close();
        in.close();
        Bitmap bitmap = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
    return bitmap;

}

其他方式是使用openFileInput

public static Bitmap returnBitmapFromFile(Context activityContext, String FileName){

  FileInputStream fis;      

    try {
        fis = openFileInput(FileName);
        Bitmap bitmap = BitmapFactory.decodeStream(fis);
        fis.close();
                    return bitmap;
    } catch (FileNotFoundException e) {
                    e.printStackTrace();
                     return null;
    } catch (IOException e) {
        e.printStackTrace();
                    return null;
    }
}