【问题标题】:StreamCorruptedException when reading Bitmap from SD card从 SD 卡读取位图时出现 StreamCorruptedException
【发布时间】:2011-06-24 18:33:30
【问题描述】:

我有一个返回 jpg 的网络服务。我把这个 jpg 读成 byte[],转换成 Bitmap,然后保存到 SD 卡。下次用户来到这个Activity时,它会先搜索SD卡看图片是否存在,然后再点击web服务。

但是,如果文件存在,检查 SD 卡的代码会返回 StreamCorruptedException。

这是我写入 SD 卡的代码:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    String root = Environment.getExternalStorageDirectory().toString();
    new File(root + "/images").mkdirs();
    try {
        File file = new File(root + "/images", Integer.toString(intImageId) + "m.jpg");
        FileOutputStream os = new FileOutputStream(file);
        Bitmap theImageFromByteArray = BitmapFactory.decodeByteArray(image, 0, image.length);
        theImageFromByteArray.compress(Bitmap.CompressFormat.JPEG, 80, os);
        os.flush();
        os.close();
    }
    catch (FileNotFoundException e) {
    }
    catch (IOException e) {
    }
}

这是我检查 SD 卡中现有图像的代码:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
        || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + "/images", Integer.toString(mImageId) + "m.jpg");
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        mImage = (Bitmap)ois.readObject();
        ois.close();
    }
    catch (Exception e) {
    }
}

在 new ObjectInputStream(fis) 期间发生异常

【问题讨论】:

    标签: android sd-card


    【解决方案1】:

    你不能像这样任意 readObject() 。为了让 readObject() 检测到有效的序列化对象,需要使用 writeObject()。

    【讨论】:

    • BitmapFactory.decodeStream(InputStream is, Rect outPadding, BitmapFactory.Options opts) 或其中一个 decodeFile() API 怎么样? doc
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多