Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

String text = "This 
is 
multiline";

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...