我需要以编程方式在我的Android应用程序上创建.jpeg / .png文件。我有简单的图像(黑色背景),它需要以编程方式在其上写一些文字。我该怎么做?可能吗?
答案 0 :(得分:9)
这绝对是可能的。
要在图像上写入文本,您必须将图像加载到Bitmap对象中。然后使用Canvas和Paint函数绘制该位图。完成绘图后,只需将位图输出到文件即可。
如果您只是使用黑色背景,那么您最好在画布上创建一个空白位图,将其填充为黑色,绘制文本然后转储到位图。
I used this tutorial to learn the basics of the canvas and paint.
这是您要将画布转换为图像文件的代码:
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);
}
答案 1 :(得分:6)
是的,see here
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
您还可以将awt的Graphics2D与this compatibility project
一起使用答案 2 :(得分:6)
使用Graphics2d
您也可以创建PNG图像:
public class Imagetest {
public static void main(String[] args) throws IOException {
File path = new File("image/base/path");
BufferedImage img = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.YELLOW);
g2d.drawLine(0, 0, 50, 50);
g2d.setColor(Color.BLACK);
g2d.drawLine(50, 50, 0, 100);
g2d.setColor(Color.RED);
g2d.drawLine(50, 50, 100, 0);
g2d.setColor(Color.GREEN);
g2d.drawLine(50, 50, 100, 100);
ImageIO.write(img, "PNG", new File(path, "1.png"));
}
}