Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert text to image file on Android

I have a text document (.txt). I want to convert it to an image (.png or .jpg). For example, black text on white background. How can I do that programmatically?

like image 466
Seshu Vinay Avatar asked Dec 05 '22 17:12

Seshu Vinay


1 Answers

I think the proper way for multi-line text is this:

String text = "This \nis \nmultiline";

final Rect bounds = new Rect();
TextPaint textPaint = new TextPaint() {
    {
        setColor(Color.WHITE);
        setTextAlign(Paint.Align.LEFT);
        setTextSize(20f);
        setAntiAlias(true);
    }
};
textPaint.getTextBounds(text, 0, text.length(), bounds);
StaticLayout mTextLayout = new StaticLayout(text, textPaint,
            bounds.width(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int maxWidth = -1;
for (int i = 0; i < mTextLayout.getLineCount(); i++) {
    if (maxWidth < mTextLayout.getLineWidth(i)) {
        maxWidth = (int) mTextLayout.getLineWidth(i);
    }
}
final Bitmap bmp = Bitmap.createBitmap(maxWidth , mTextLayout.getHeight(),
            Bitmap.Config.ARGB_8888);
bmp.eraseColor(Color.BLACK);// just adding black background
final Canvas canvas = new Canvas(bmp);
mTextLayout.draw(canvas);
FileOutputStream stream = new FileOutputStream(...); //create your FileOutputStream here
bmp.compress(CompressFormat.PNG, 85, stream);
bmp.recycle();
stream.close();
like image 83
M-WaJeEh Avatar answered Dec 21 '22 22:12

M-WaJeEh