Skip to content

Commit

Permalink
feat: support content URI when loading background image (terrylinla#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
ian-wd authored Oct 9, 2024
1 parent 993fee1 commit 4b11ca0
Showing 1 changed file with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.terrylinla.rnsketchcanvas;

import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
Expand All @@ -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;
Expand Down Expand Up @@ -64,14 +67,41 @@ 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(
filename.lastIndexOf('.') == -1 ? filename : filename.substring(0, filename.lastIndexOf('.')),
"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);
Expand Down

0 comments on commit 4b11ca0

Please sign in to comment.