Get path of image without inserting it to the gallery

Hello,

FIrst, I have to apologize for posting this here instead of the Android Development board - I have renewed my subscription but for whatever reason it’s not updated here on the board - can you please check what’s going on? (please move this in the Android Development board)

Secondly, I have this issue of trying to send a picture in a MultiPart request. Everything works well, but in order to get the URI to create the file that is to be sent based on the Bitmap, I am doing this:

    //prepare the picture as multipart
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
    String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), document, "Document", "Scanned Document");
    Uri documentUri = Uri.parse(path);
    File file = FileUtils.getFile(context, documentUri);

    //add the document to the request
    RequestBody requestDocument = RequestBody.create(MediaType.parse(context.getContentResolver().getType(documentUri)), file);
    MultipartBody.Part documentPart = MultipartBody.Part.createFormData(context.getString(R.string.send_document_multipart_body_file_name), file.getName(), requestDocument);

The problem is that while this works, it also adds the picture to the phone’s gallery, even after I delete the file in my backend response with file.delete().

I need a way to get the bitmap’s URI without adding it to the MediaStore, like I am doing now. Can you please tell me if there is such a way?

Thank you!

Because I manually have to sync the membership rosters, you have to re-request access if your Warescription lapses. I have re-granted your posting privileges to this category. And thanks for renewing! :grin:

File file = FileUtils.getFile(context, documentUri);

I suspect that this is broken, particularly on Android Q and higher.

I need a way to get the bitmap’s URI

No, you don’t. You are throwing away the Uri after (incorrectly) attempting to convert it to a File. Your only other use of it is for getType(), and you already know the MIME type. So, you just need a File, such as:

//prepare the picture as multipart
    File file = new File(context.getCacheDir(), "awesome.jpg");
    FileOutputStream fos = new FileOutputStream(file);
    document.compress(Bitmap.CompressFormat.JPEG, 90, fos);
    fos.flush();
    fos.getFD().sync();
    fos.close();

    //add the document to the request
    RequestBody requestDocument = RequestBody.create(MediaType.parse("image/jpeg"), file);
    MultipartBody.Part documentPart = MultipartBody.Part.createFormData(context.getString(R.string.send_document_multipart_body_file_name), file.getName(), requestDocument);

It works, thank you! I haven’t worked with files that much and whenever I see File and FileOutputStream it reminds me of “low level Java SE” programming to which I’m allergic. :grinning: