【问题标题】:Android - Good way to pass bitmap to an activity fastlyAndroid - 快速将位图传递给活动的好方法
【发布时间】:2015-10-19 21:00:18
【问题描述】:

将位图发送到另一个活动不存储在设备上的最佳方式是什么?
如果我 putExtra(Bitmap),我会遇到缓冲区问题,因为 Bitmap 太大。
现在我用这个但是太慢了:

Intent intent = new Intent(context, ImageScreen.class);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bytes = stream.toByteArray();
    intent.putExtra("image",bytes);
    context.startActivity(intent);

【问题讨论】:

    标签: android android-intent android-activity bitmap


    【解决方案1】:

    你说位图太大了,这种情况下最好的解决办法是把Bitmap写在你app的私有存储中,然后把文件路径发给下一个activity。将位图写入文件并检索文件路径的代码如下

    public String createBitmapFile(Bitmap bitmap) {
        String fileName = "image";
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
            FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (Exception e) {
            fileName = null;
        }
        return fileName;
    }
    

    然后在下一个活动中你可以做类似的事情

    Bitmap bitmap = BitmapFactory.decodeStream(context
                        .openFileInput(fileName));
    

    稍后要删除文件,您可以简单地使用。

    if(activity.deleteFile(imageName))
        Log.i(TAG, "Image deleted");
    

    【讨论】:

    • 我想做什么之后如何删除文件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2012-07-28
    相关资源
    最近更新 更多