How to save image using return Uri?

657 views Asked by At

I am using an image background remover library from GitHub. My image is not being saved in storage after done with removing background.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CutOut.CUTOUT_ACTIVITY_REQUEST_CODE) {
        switch (resultCode) {
            case Activity.RESULT_OK:
                Uri imageUri = CutOut.getUri(data);
                // Save the image using the returned Uri here
                //what code to add here so i can save my image
                how to save image using Retun Uri
                Intent intent1=new Intent(BackgroundRemover.this,MainActivity.class);
                startActivity(intent1);
                break;
            case CutOut.CUTOUT_ACTIVITY_RESULT_ERROR_CODE:
                Exception ex = CutOut.getError(data);
                break;
            default:
                System.out.print("User cancelled the CutOut screen");
                Intent intent2=new Intent(BackgroundRemover.this,AdvanceFeatures.class);
                startActivity(intent2);
        }
    }
}

How to save image using return Uri?

2

There are 2 answers

0
Vivek Aghera On

You have to get the byte array from URI and convert the byte array to a file using output and input stream.

Get Bytearray from URI

result?.data?.data?.let {
                val byteArray = contentResolver.openInputStream(it)?.readBytes() }

Get the file information from URI

    /*
 * Get the file's content URI from the incoming Intent,
 * then query the server app to get the file's display name
 * and size.
 */
returnIntent.data?.let { returnUri ->
    contentResolver.query(returnUri, null, null, null, null)
}?.use { cursor ->
    /*
     * Get the column indexes of the data in the Cursor,
     * move to the first row in the Cursor, get the data,
     * and display it.
     */
    val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
    cursor.moveToFirst()
    val fileName = cursor.getString(nameIndex)
    val fileSize = cursor.getLong(sizeIndex).toString()
}

Write file from byte array

if (!file.exists()) {
    file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(byteArray);
fos.close();
8
EL Amine Bechorfa On

A practical way to save an image by URI is by writing the code below :

1 - Get the Uri of the image using CutOut.getUri(data).

2- MediaStore.Images.Media.getBitmap to get a Bitmap object

3- getContentResolver().openOutputStream(imageUri) to get an OutputStream object to write the image data to the Uri.

4 - bitmap.compress to compress the image data and write it to the OutputStream.

5 - case Activity.RESULT_OK: (block of your) onActivityResult method.

    Uri imageUri = CutOut.getUri(data);
try {
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    String displayName = "my_image.png"; // Set the name of the image file here
    OutputStream fos = getContentResolver().openOutputStream(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/" + displayName));
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}