使用 ImageDecoder 从 URI 加载位图并添加文本

Loading a bitmap with ImageDecoder from URI and adding text

在我的 activity 中,我想修改一张图片以在其上添加文字。

图像是在图库中选择的或用相机拍摄的,然后存储在上一个activity的文件中。然后该文件的 uri 通过 extras 传递。

现在我尝试在图像顶部添加一个字符串,如下所示:

try {
        modifyThePic(imageUri);
    } catch (IOException e) {
        e.printStackTrace();
    }

这里是函数体:

public void modifyThePic(Uri imageUri) throws IOException {

    ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), imageUri);
    Bitmap bitmap = ImageDecoder.decodeBitmap(source);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(10);
    canvas.drawText("Some Text here", 0, 0, paint);

    image.setImageBitmap(bitmap); //image is the imageView to control the result

}

预期的行为是显示上面带有“此处有一些文本”的图像。但是没有显示任何内容,但是应用程序没有崩溃。

调试时,我遇到

之间出现的错误

Bitmap bitmap = ImageDecoder.decodeBitmap(source);

Canvas canvas = new Canvas(bitmap);

这里是错误:

java.io.FileNotFoundException:没有内容提供者:/storage/emulated/0/Android/data/com.emergence.pantherapp/files/Pictures/JPEG_20200829_181926_7510981182141824841.jpg

我怀疑我用错了“ImageDecoder”,因为这是我第一次使用它。更准确地说,我无法让 onCreate 中的“decodeBitmap”方法,Android Studio 告诉我它不能在“主线程”中,我对线程一点也不熟悉。将它移动到专用函数中可以解决此问题,但也许我应该做其他事情,这是问题的根源。

我的问题: 我是否使用了正确的工具来修改文件并在其中添加文本? 如果是,我做错了什么? 如果不是,我应该研究什么 library/tools 来完成这项任务?

谢谢,

编辑:附加答案元素

正如@blackapps 和@rmunge 所指出的,我得到的不是合法的 URI,而是文件路径。解决我的问题的简单方法是使用以下代码从路径获取 URI:

Uri realuri = Uri.fromFile(new File("insert path here")));

另外要编辑位图,必须使其可变,例如

从 URI 中提取位图并在其上添加文本的最后一个函数是:

public void modifyThePic(Uri imageUri) throws IOException {

    ContentResolver cr = this.getContentResolver();
    InputStream input = cr.openInputStream(imageUri);
    Bitmap bitmap = BitmapFactory.decodeStream(input).copy(Bitmap.Config.ARGB_8888,true);

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(300);

    int xPos = (canvas.getWidth() / 2); //just some operations to center the text
    int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;

    canvas.drawText("SOME TEXT TO TRY IT OUT", xPos, yPos, paint);

    image.setImageBitmap(bitmap);

}

您的 URI 似乎有误。它必须以 file:///

开头