1

我对android很陌生。我想将图像保存到内存中,然后从内存中检索图像并将其加载到图像视图中。我已使用以下代码成功地将图像存储在内部存储器中:

void saveImage() {
    String fileName="image.jpg";
    //File file=new File(fileName);
    try 
    {

       FileOutputStream fOut=openFileOutput(fileName, MODE_PRIVATE);
       bmImg.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

    }
    catch (Exception e) 
    {
       e.printStackTrace();
    }
}

使用此代码图像被保存。但是当我尝试检索图像时,它给了我错误。用于检索图像的代码是:

FileInputStream fin = null;

        ImageView img=new ImageView(this);
        try {
            fin = openFileInput("image.jpg");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] bytes = null;
        try {
            fin.read(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
        img.setImageBitmap(bmp);

但我得到一个空指针异常。

我检查了文件是否存在于路径的内部存储器中:

/data/data/com.test/files/image.jpg

我做错了什么请帮我解决这个问题。我经历了很多堆栈问题。

4

1 回答 1

2

这是因为您的字节数组为空,将其实例化并分配大小。

 byte[] bytes = null;  // you should initialize it with some bytes size like new byte[100]
    try {
        fin.read(bytes);
    } catch (Exception e) {
        e.printStackTrace();
    }

编辑1:我不确定,但你可以做类似的事情

byte[] bytes = new byte[fin.available()]

编辑 2: 这是一个更好的解决方案,因为您正在阅读图像,

FileInputStream fin = null;

    ImageView img=new ImageView(this);
    try {
        fin = openFileInput("image.jpg");
        if(fin !=null && fin.available() > 0) {
            Bitmap bmp=BitmapFactory.decodeStream(fin) 
            img.setImageBitmap(bmp);
         } else {
            //input stream has not much data to convert into  Bitmap
          }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

帮助 - 杰森罗宾逊

于 2013-02-01T06:47:13.820 回答