Skip to content Skip to sidebar Skip to footer

How To Convert Views To Bitmap And Save As Image?

I am trying to convert views to bitmap and save as image! I found some method to do that but it doesn't work in Android 10 or higher version! Here is my XML code:-

Solution 1:

Use this method. It will save bitmap to Pictures folder (MediaStore API)

Also learn more about Scoped storage

publicstatic Uri savePng(Context context, Bitmap bitmap, @NonNull String name)throws IOException {
        Uri uri;
        OutputStream fileOutputStream;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolverresolver= context.getContentResolver();
            ContentValuescontentValues=newContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name + ".png");
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            fileOutputStream = resolver.openOutputStream(Objects.requireNonNull(uri));
        } else {
            StringimagePath= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
            Fileimage=newFile(imagePath, name + ".png");
            fileOutputStream = newFileOutputStream(image);
            uri = getUriFromPath(context, imagePath);
        }
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.close();
        return uri;
    }


    privatestatic Uri getUriFromPath(Context context, String imagePath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            return FileProvider.getUriForFile(context, "com.noobprogroammer.sampleproject.fileProvider", newFile(imagePath));
        return Uri.fromFile(newFile(imagePath));
    }


    protectedvoidopenImage(Uri uri) {
        try {
            Intentintent=newIntent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "image/*");
            startActivity(intent);
        }catch (Exception e){
            Toast.makeText(this, "Error opening image", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

Post a Comment for "How To Convert Views To Bitmap And Save As Image?"