在Java和Android上是否可以通过编程创建图像?

20

我需要在我的Android应用程序中以编程方式创建.jpeg/.png文件。 我有一个简单的图像(黑色背景),需要以编程方式在其上写入一些文本。 我该如何实现它?这可能吗?


如何编程创建简单图像 - Suragch
3个回答

9
“这是完全可能的。
要在图像上写入文本,您需要将图像加载到Bitmap对象中。然后使用Canvas和Paint函数在该位图上进行绘制。完成绘制后,只需将Bitmap输出到文件即可。
如果您只是使用黑色背景,则最好创建一个空白位图,在画布上填充黑色,绘制文本,然后转储到Bitmap。
我使用了这个教程来学习canvas和paint的基础知识。
这是将canvas转换为图像文件所需的代码:”
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); 
}

如何用JavaScript实现相同的功能?有没有任何库或者其他工具可以帮助我们做到这一点? - Chetan

6
是的,请点击这里
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);

您还可以使用awt的Graphics2D与此兼容性项目一起使用。


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"));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接