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

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...