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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With