From 4b11ca0a1febb98822c9bf255e12ec88da544c5c Mon Sep 17 00:00:00 2001 From: ian-wd <54297307+ian-wd@users.noreply.github.com> Date: Wed, 9 Oct 2024 19:31:30 +0800 Subject: [PATCH] feat: support content URI when loading background image (#79) --- .../rnsketchcanvas/SketchCanvas.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/android/src/main/java/com/terrylinla/rnsketchcanvas/SketchCanvas.java b/android/src/main/java/com/terrylinla/rnsketchcanvas/SketchCanvas.java index e8edd9b6..497d9629 100644 --- a/android/src/main/java/com/terrylinla/rnsketchcanvas/SketchCanvas.java +++ b/android/src/main/java/com/terrylinla/rnsketchcanvas/SketchCanvas.java @@ -1,5 +1,6 @@ package com.terrylinla.rnsketchcanvas; +import android.database.Cursor; import android.graphics.Typeface; import android.graphics.Bitmap; import android.graphics.BitmapFactory; @@ -11,7 +12,9 @@ import android.graphics.Rect; import android.graphics.Matrix; import android.media.ExifInterface; +import android.net.Uri; import android.os.Environment; +import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import android.view.View; @@ -64,6 +67,30 @@ public SketchCanvas(ThemedReactContext context) { mContext = context; } + private Uri getFileUri(String filepath) { + Uri uri = Uri.parse(filepath); + if (uri.getScheme() == null) { + uri = Uri.parse("file://" + filepath); + } + return uri; + } + + private String getOriginalFilepath(String filepath) { + Uri uri = getFileUri(filepath); + String originalFilepath = filepath; + if (uri.getScheme().equals("content")) { + try { + Cursor cursor = mContext.getContentResolver().query(uri, null, null, null, null); + if (cursor.moveToFirst()) { + originalFilepath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); + } + cursor.close(); + } catch (IllegalArgumentException ignored) { + } + } + return originalFilepath; + } + public boolean openImageFile(String filename, String directory, String mode) { if (filename != null) { int res = mContext.getResources().getIdentifier( @@ -71,7 +98,10 @@ public boolean openImageFile(String filename, String directory, String mode) { "drawable", mContext.getPackageName()); BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); - File file = new File(filename, directory == null ? "" : directory); + + String originalFilepath = getOriginalFilepath(filename); + File file = new File(originalFilepath, directory == null ? "" : directory); + Bitmap bitmap = res == 0 ? BitmapFactory.decodeFile(file.toString(), bitmapOptions) : BitmapFactory.decodeResource(mContext.getResources(), res);