Android读写临时文件

3

大家好,我创建了这个方法来完成以下任务:

-获取位图

-创建临时文件

-压缩位图并将其放入临时文件中

-打开临时文件

-读取字节 >>>我的代码在这里出现了问题

-将这些字节保存到SQLite数据库中

-从SQLite数据库中检索字节

-将这些字节再次设置为图像位图

我知道这完全没用,但这是我找到的实现我想要达到的目标的唯一方法:

-压缩位图

-将其保存到SQLite数据库中

以下是代码。程序在in.read(bb)处崩溃:

private void updateBitmapData() {
    File file = null;
    
    FileOutputStream stream = null;

    try {
        file = File.createTempFile("image", null, getBaseContext().getFilesDir());
        stream = new FileOutputStream(file);
        System.out.println(thumbnail.getRowBytes());
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 50, stream);
        
        stream.close();
        
        FileInputStream in=new FileInputStream(file);

        byte[] bb = null;
        in.read(bb); //crash
        in.close();
        System.out.println("despues compression"+bb.length);
        
        DBAdapter db=new DBAdapter(getApplicationContext());
        db.insertData(bb);
        Cursor c=db.getLastImage();
        if(c.moveToFirst()){
            bb=c.getBlob(0);
        }
        c.close();
        db.close();
        im.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
    
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e("NuevaIncidencia", e.getLocalizedMessage());
        im.setImageBitmap(thumbnail);
    }catch (IOException e1) {
        Log.e("NuevaIncidencia", e1.getLocalizedMessage());
        e1.printStackTrace();
        im.setImageBitmap(thumbnail);
    } catch (Exception e2){
        e2.printStackTrace();
        //Log.e("NuevaIncidencia", e2.getLocalizedMessage());
    } 
    
}

我该如何解决这个问题?谢谢。

为什么不尝试在SD卡上保存/检索图像路径呢?这很容易使用。 - Hiren Dabhi
1个回答

1

我猜你遇到了NullPointerException,这似乎是正常的,因为当你调用read时,你的缓冲区是null。

你必须使用预期大小来实例化缓冲区。

尝试以这种方式初始化你的字节数组:

byte[] bb = new byte[file.length()];

希望能帮到你。

Jokahero


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接