0

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Fawad
  • 21
  • 4
  • 1
    `my image is not being saved in storage after done with removing background` What kind of image? Where does it suddenly come from? What does it have to do with removing a backgroud? A background of what? – blackapps Mar 06 '23 at 09:36
  • You can create a file object from your uri and save it in storage. File temp = new File(uri), save and read this file again, after you only need to knowledge working with storage in android. – Reyhane Farshbaf Mar 06 '23 at 10:17
  • Please do not repost your problem within three hours. And certainly not without even answering questions. – blackapps Mar 06 '23 at 12:45

2 Answers2

1

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();
}
  • thanks so much for your answer means a lot but just elaborate a little where i have to use displayName??? – Fawad Mar 06 '23 at 13:16
  • and what about onActivityResult method idk kindly help me – Fawad Mar 06 '23 at 13:17
  • this did not give me any error but still image is not saved – Fawad Mar 06 '23 at 13:30
  • `DisplayName` variable is storing just the name of the file as a String, you can use it to make an URI to specify where to save the image. check the code i updated it ;) – EL Amine Bechorfa Mar 06 '23 at 14:42
  • `CutOut` library saves the image file in the application's cache directory, You can use `getCacheDir()` method to get the path to the cache directory. You can also specify a custom directory to save the file. For example, you can save the file in the external storage directory by using `getExternalFilesDir()` method. You can find more details on the official documentation – EL Amine Bechorfa Mar 06 '23 at 14:46
  • Thank you so much its working now..... keep on helping new programmers – Fawad Mar 06 '23 at 16:03
  • only 1 confusion yes its saving image now but with blackish background in folder its showing white but when i oepn that image saved afyer removing background showing black background ??? – Fawad Mar 06 '23 at 16:09
  • Maybe you have a PNG image without a background so thats why you have different colors it depends with which program your reading the picture, it is not a problem – EL Amine Bechorfa Mar 06 '23 at 16:22
0

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();