【问题标题】:Read and write bitmap to android fails读写位图到android失败
【发布时间】:2017-12-04 11:19:32
【问题描述】:

我正在尝试按照其他主题的建议来编写和读取位图,问题是当我尝试在保存图像的路径上读取时,我永远不会得到位图:

所以我有这个来写位图:

private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath=new File(directory,"captured");

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return directory.getAbsolutePath();
    }

}

我将返回的路径传递给另一个活动,然后将其作为参数传递以获取位图,如下所示:

 private void loadImageFromStorage(String path)
    {

        try {
            File f=new File(path, "captured.jpg");
            Log.d("filehe",f.toString());
            b = BitmapFactory.decodeStream(new FileInputStream(f));
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

    }

我觉得我在这里做错了什么,但不知道是什么,b variavel 没有价值:/。

有什么帮助吗?

谢谢

【问题讨论】:

    标签: java android file bitmap android-file


    【解决方案1】:

    所以我有这个来写位图:

    您保存的文件名为captured

    我将返回的路径传递给另一个活动,然后我将其作为参数传递以获取这样的位图

    在这里,您正在尝试加载captured.jpg,而不是captured

    您可以通过让第一个方法返回第二个方法使用的File 来避免此类问题。

    还有:

    • 使用具有内存缓存的图像加载库(例如 Picasso、Glide),这样您就不会浪费用户时间从磁盘重新加载相同的位图

    • 从第一种方法中去掉ContextWrapper,因为你不需要它

    【讨论】:

    • 我正在使用毕加索,我只需要将位图传递给其他活动,我该如何使用它呢?
    • @afcosta007:“我正在使用毕加索”——您没有在第二种方法中使用它。 “我怎么能用它来达到这个目的?”——你使用了一些东西来加载 Picasso 的图像,例如 URL 或Uri。将其传递给第二个活动,并让它也使用毕加索。 Picasso will then use the cached bitmap where possible.
    • 那么你说的是我可以使用毕加索从第一种方法的给定路径加载位图吗?
    • @afcosta007:您没有在第一种方法中加载任何内容。 Picasso 可以加载本地图片,因此您可以在第二种方法中使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多