在我的活动中,我想要修改一个图像来添加一个文本。
图像被选择在galery或与相机一起拍摄,然后存储在一个文件中,在以前的活动中。然后,该文件的uri将通过附加文件传递。
现在,我尝试在图像的顶部添加一个字符串,如下所示:
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
}预期的行为将是显示图像与“一些文本在上面”。但是没有显示任何东西,但是应用程序没有崩溃。
调试时,我遇到一个出现在
位图位图=ImageDecoder.decodeBitmap(源);
和
画布画布=新画布(位图);
以下是错误:
/storage/emulated/0/Android/data/com.emergence.pantherapp/files/Pictures/JPEG_20200829_181926_7510981182141824841.jpg : java.io.FileNotFoundException:无内容提供者:
我怀疑这是我第一次使用"ImageDecoder“。更确切地说,我无法让"decodeBitmap“方法在onCreate,Android告诉我,它不可能在”主线“,我一点也不熟悉线程。将它移动到一个专用函数中,修复了这个问题,但也许我应该做一些其他的事情,这是问题的根源。
我的问题:是否使用正确的工具修改文件并在其上添加文本?如果是,我做错了什么?如果不是,我应该研究哪些库/工具来完成这项任务?
谢谢,
编辑:附加答案元素
正如@blackapps和@rmunge都指出的那样,我得到的不是一个合法的URI,而是一个文件路径。解决问题的简单方法是使用以下代码从路径中获取URI:
Uri realuri = Uri.fromFile(new File("insert path here")));此外,要编辑位图,它必须是可变的,例如覆盖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);
}发布于 2020-08-29 17:44:07
看来你的URI是错的。它必须从file:///开始
https://stackoverflow.com/questions/63649635
复制相似问题