Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String text to Bitmap

Tags:

Is it possible to convert string text that is inside an EditText box into a Bitmap? In other words, is there any way to convert string text into a Bitmap that means the text will display as an image?

Below is my Code:

class TextToImage extends Activity {      protected void onCreate(Bundle savedInstanceState) {         //create String object to be converted to image         String sampleText = "SAMPLE TEXT";         String fileName = "Image";          //create a File Object         File newFile = new File("./" + fileName + ".jpeg");          //create the font you wish to use         Font font = new Font("Tahoma", Font.PLAIN, 11);          //create the FontRenderContext object which helps us to measure the text         FontRenderContext frc = new FontRenderContext(null, true, true);     } } 
like image 256
shyam Avatar asked Jan 10 '12 06:01

shyam


2 Answers

You can create a Bitmap of the appropriate size, create a Canvas for the Bitmap, and then draw your text into it. You can use a Paint object to measure the text so you'll know the size needed for the bitmap. You can do something like this (untested):

public Bitmap textAsBitmap(String text, float textSize, int textColor) {     Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);     paint.setTextSize(textSize);     paint.setColor(textColor);     paint.setTextAlign(Paint.Align.LEFT);     float baseline = -paint.ascent(); // ascent() is negative     int width = (int) (paint.measureText(text) + 0.5f); // round     int height = (int) (baseline + paint.descent() + 0.5f);     Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);     Canvas canvas = new Canvas(image);     canvas.drawText(text, 0, baseline, paint);     return image; } 
like image 150
Ted Hopp Avatar answered Sep 23 '22 14:09

Ted Hopp


I've adapted @TedHopp's answer to ensure the image created is always square, which can be useful depending on where the image is to be displayed, such as in a NavigationDrawer icon or suchlike. The text is horizontally centered in the middle of the image.

public static Bitmap textAsBitmap(String text, float textSize, int textColor) {     // adapted from https://stackoverflow.com/a/8799344/1476989     Paint paint = new Paint(ANTI_ALIAS_FLAG);     paint.setTextSize(textSize);     paint.setColor(textColor);     paint.setTextAlign(Paint.Align.LEFT);     float baseline = -paint.ascent(); // ascent() is negative     int width = (int) (paint.measureText(text) + 0.0f); // round     int height = (int) (baseline + paint.descent() + 0.0f);      int trueWidth = width;     if(width>height)height=width; else width=height;     Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);      Canvas canvas = new Canvas(image);     canvas.drawText(text, width/2-trueWidth/2, baseline, paint);     return image; } 
like image 44
Peter Gordon Avatar answered Sep 19 '22 14:09

Peter Gordon