问题描述
我需要以编程方式在我的Android应用程序上创建.jpeg / .png文件。我有简单的图像(黑色背景),它需要以编程方式在其上写一些文字。我该怎么做?可能吗?
I need to create .jpeg/.png file on my Android application programmatically. I have simple image (black background), and it need to write some text on it programmatically. How can I do it? Is it possible?
推荐答案
这绝对是可能的。
在图像上写文字您必须将图像加载到Bitmap对象。然后使用Canvas和Paint函数在该位图上绘制。当你完成绘图时,你只需将位图输出到一个文件。
To write text on an image you have to load the image in to a Bitmap object. Then draw on that bitmap with the Canvas and Paint functions. When you're done drawing you simply output the Bitmap to a file.
如果你只是使用黑色背景,你可能最好只创建一个空白画布上的位图,填充黑色,绘制文本然后转储到位图。
If you're just using a black background, it's probably better for you to simply create a blank bitmap on a canvas, fill it black, draw text and then dump to a Bitmap.
这是您要将画布转换为图像文件的代码:
This is the code that you'll be looking for to turn the canvas in to an image file:
OutputStream os = null;
try {
File file = new File(dir, "image" + System.currentTimeMillis() + ".png");
os = new FileOutputStream(file);
finalBMP.compress(CompressFormat.PNG, 100, os);
finalBMP.recycle(); // this is very important. make sure you always recycle your bitmap when you're done with it.
screenGrabFilePath = file.getPath();
} catch(IOException e) {
finalBMP.recycle(); // this is very important. make sure you always recycle your bitmap when you're done with it.
Log.e("combineImages", "problem combining images", e);
}
这篇关于是否可以在Java,Android上以编程方式创建图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!