简体   繁体   中英

How to save image from drawable as png in android?

Problem:

I can't save image from drawable as png in android.

Code:

 Bitmap b = BitmapFactory.decodeResource(getResources(), 
 eventsList.get(position).getEvent_image());

            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/png");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),
                    b, "imagePath", null);
            if (!SampleUtil.isNullOrEmpty(path)) {
                /*Uri imageUri = Uri.parse(path);*/
                selectedImage = path;
            }

try this

step 1. get your bitmap in to drawable obje like this

Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);

step 2 save in your storage like this

 String extStorageDirectory =  Environment.getExternalStorageDirectory().toString();
    File file = new File(extStorageDirectory, "launcher.PNG");
    try {
        FileOutputStream outStream = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        outStream.flush();
        outStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Don't forget to add android.permission.WRITE_EXTERNAL_STORAGE permission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM