在Android上将文本转换为图像文件


问题内容

我有一个文本文件(.txt)。我想将其转换为图像(.png或.jpg)。例如,在白色背景上的黑色文本。如何以编程方式做到这一点?


问题答案:

此(未经测试的)代码应使您走上正确的道路。

void foo(final String text) throws IOException{
    final Paint textPaint = new Paint() {
        {
            setColor(Color.WHITE);
            setTextAlign(Paint.Align.LEFT);
            setTextSize(20f);
            setAntiAlias(true);
        }
    };
    final Rect bounds = new Rect();
    textPaint.getTextBounds(text, 0, text.length(), bounds);

    final Bitmap bmp = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.RGB_565); //use ARGB_8888 for better quality
    final Canvas canvas = new Canvas(bmp);
    canvas.drawText(text, 0, 20f, textPaint);
    FileOutputStream stream = new FileOutputStream(...); //create your FileOutputStream here
    bmp.compress(CompressFormat.PNG, 85, stream);
    bmp.recycle();
    stream.close();
}