how do you pass images (bitmaps) between android activities using bundles?

后端 未结 9 1198
自闭症患者
自闭症患者 2020-11-22 09:56

Suppose I have an activity to select an image from the gallery, and retrieve it as a BitMap, just like the example: here

Now, I want to pass this BitMap to be used i

9条回答
  •  萌比男神i
    2020-11-22 10:36

    As suggested by @EboMike I saved the bitmap in a file named myImage in the internal storage of my application not accessible my other apps. Here's the code of that part:

    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:

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

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

提交回复
热议问题