Search code examples
androiddelphiurifiremonkeydelphi-10.3-rio

How to load a file into a stream on Android knowing its Jnet_Uri?


I'm writing an Android FMX app in Delphi 10.3 Rio. There I'm selecting photos from the gallery (via TJIntent.JavaClass.ACTION_OPEN_DOCUMENT) and getting back Jnet_Uri entries. I can use those to read image EXIF (with TJExifInterface). Now I also need to load these images into a stream for further processing. How do I do this?

When I try to convert Jnet_Uri to a path with uri.getPath, it comes out like /document/image:26591. uri.toString gives me content://com.android.providers.media.documents/document/image%3A26674. TMemoryStream.LoadFromFile fails to load from both of these paths:

Cannot open file "/document/image:26724". No such file or directory
Cannot open file "/content:/com.android.providers.media.documents/document/image%3A26724". Not a directory

Hence the question, how knowing a Jnet_Uri do I load files contents into a stream?


Solution

  • I was able to read the data via JInputStream:

    var
      uri: Jnet_Uri;
      ms: TMemoryStream;
      jis: JInputStream;
      b: TJavaArray<Byte>;
    begin
      uri := .. some uri, alike "/document/image:26591"
    
      ms := TMemoryStream.Create;
    
      // Need to read via JInputStream, since Uri is not a file
      jis := TAndroidHelper.Context.getContentResolver.openInputStream(uri);
      b := TJavaArray<Byte>.Create(jis.available);
      jis.read(b);
      ms.Write(b.Data^, b.Length);
      jis.close;
    
       .. do something with Stream now