How can I pass a Bitmap object from one activity to another

前端 未结 10 925
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 03:39

In my activity, I create a Bitmap object and then I need to launch another Activity, How can I pass this Bitmap object from the sub-ac

10条回答
  •  长情又很酷
    2020-11-22 04:06

    Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

    To store bitmap in a file myImage in internal storage:

    public String createImageFromBitmap(Bitmap bitmap) {
        String fileName = "myImage";//no .png or .jpg needed
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
            fo.write(bytes.toByteArray());
            // remember close file output
            fo.close();
        } catch (Exception e) {
            e.printStackTrace();
            fileName = null;
        }
        return fileName;
    }
    

    Then in the next activity you can decode this file myImage to a bitmap using following code:

    //here context can be anything like getActivity() for fragment, this or MainActivity.this
    Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
    

    Note A lot of checking for null and scaling bitmap's is ommited.

提交回复
热议问题