Android Convert Text to Image and Save To SDCard

By | August 9, 2014

Since a long time i was looking for something how to convert edittext text to a bitmap , after a lot of search on internet i didn’t find any appropriate answer for it and then i put some effort and came with solution ,i am not using any external library for this , i am using graphic library which is provide in android SDK .


Project Detail

Project Name Stringtoimage
Package com.pavan.stringtoimage
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

XML Layout

Create a XML Layout and add edittext and Button to it .

file : activity_main.xml

<LinearLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:orientation=”vertical”
    android:padding=”10dp”
    tools:context=”.MainActivity” >

    <EditText
        android:id=”@+id/str_id”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content”
        android:layout_marginTop=”10dp”
        android:hint=”Enter Your Text Here …..”
        android:inputType=”textMultiLine”
        android:lines=”10″ >

        <requestFocus />
    </EditText>

    <Button
        android:id=”@+id/btn_id”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content”
        android:text=”Convert To Imaget” />

</LinearLayout>

Converting Text To Image

I have Created a Class converter the purpose of this class is to convert text to image for which i defined two methods.
textAsBitmap()  converting text to image and return’s bitmap .
addBorder()  add border to bitmap and return’s it .

Coverting Text to Image Logic

1.  Create Textpaint object and set the property like color , textsize,stroke,typeface,alignment
2.  Create a Static Layout for a text with the above defined textpaint object .

What is StaticLayout ?
Static Layout is a Layout for text , which is used to control text layout ,once the text is laid out it cannot be edited .

3. Create a Bitmap of the appropriate size, Here i am manually giving width as 435 and height is based on multiplication of number of lines in a text to character height of each line.

height :
int linecount = staticLayout.getLineCount();
int height = (int) (baseline + paint.descent() + 3) * linecount + 10;

4. Create a Canvas for the Bitmap.
5. Then draw your staticlayout to the canvas.

file : Converter.java

package com.pavan.stringtoimage;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.StaticLayout;
import android.text.TextPaint;

public class Converter {

    // Convert Text to image Method
    // pass the paramter : text , size , stroke ,color,typeface
    public Bitmap textAsBitmap(String text, float textSize, float stroke,
            int color, Typeface typeface) {

        TextPaint paint = new TextPaint();
        paint.setColor(color);
        paint.setTextSize(textSize);
        paint.setStrokeWidth(stroke);
        paint.setTypeface(typeface);

        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.LEFT);

        float baseline = (int) (-paint.ascent() + 3f); // ascent() is negative

        StaticLayout staticLayout = new StaticLayout(text, 0, text.length(),
                paint, 435, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f,
                1.0f, false);

        int linecount = staticLayout.getLineCount();

        int height = (int) (baseline + paint.descent() + 3) * linecount + 10;

        Bitmap image = Bitmap
                .createBitmap(435, height, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(image);
        canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);

        staticLayout.draw(canvas);

        return image;

    }
  
    // Adding Border to bitmap
    public Bitmap addBorder(Bitmap bmp, int borderSize, int borderColor) {
        Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize
                * 2, bmp.getHeight() + borderSize * 2, bmp.getConfig());
        Canvas canvas = new Canvas(bmpWithBorder);
        canvas.drawColor(borderColor);
        canvas.drawBitmap(bmp, borderSize, borderSize, null);
        return bmpWithBorder;
    }

}

Saving Image To SDCard

Use java’s  BufferedOutputStream  class and pass the fileoutstream object by specifying your path and Write a compressed version of the bitmap to the BufferedOutputStream object .

file : SaveImage.java

package com.pavan.stringtoimage;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
import android.util.Log;

public class SaveImage {

    public boolean storeImage(Bitmap imageData, String filename) {
        String iconsStoragePath = Environment.getExternalStorageDirectory()
                + “/myImages”;

        File sdIconStorageDir = new File(iconsStoragePath);
        sdIconStorageDir.mkdirs();

        try {
            String filePath = sdIconStorageDir.toString() + “/” + filename
                    + “.png”;
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);

            BufferedOutputStream bos = new BufferedOutputStream(
                    fileOutputStream);

            // compress image according to your format
            imageData.compress(CompressFormat.PNG, 100, bos);

            bos.flush();
            bos.close();

        } catch (FileNotFoundException e) {
            Log.w(“TAG”, “Error saving image file: ” + e.getMessage());
            return false;
        } catch (IOException e) {
            Log.w(“TAG”, “Error saving image file: ” + e.getMessage());
            return false;
        }

        return true;
    }

}

MainActivity

Create MainActivity class which extends activity class and set the content of this class with the above defined xml layout , here on click of button get the text of edittext and convert to image by calling appropriate methods which is very self explanatory .

file : MainActivity.java

package com.pavan.stringtoimage;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText str_et;
    Button mybtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        str_et = (EditText) findViewById(R.id.str_id);
        mybtn = (Button) findViewById(R.id.btn_id);

        mybtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String data = str_et.getText().toString();

                // Convert Text to Image
                Converter convert = new Converter();

                // text , size , stroke ,color,typeface
                Bitmap bmp = convert.textAsBitmap(data, 30, 5, Color.RED,
                        Typeface.MONOSPACE);
                Bitmap image = convert.addBorder(bmp, 2, Color.BLACK);

                // file name appending with system date
                Calendar c = Calendar.getInstance();
                SimpleDateFormat f = new SimpleDateFormat(“dd-MM-yyyy-HH-mm-ss”);
                String filename = “ScreenShot_” + f.format(c.getTime());

                // saving image to sdcard
                SaveImage saveimg = new SaveImage();
                // pass bit and filename
                saveimg.storeImage(image, filename);

                Toast.makeText(getApplicationContext(),
                        “Saved As :n” + filename, Toast.LENGTH_SHORT).show();

            }
        });

    }

}

Android Manifest 

Add the External Writing Permission to the manifest file .
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

file : AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.pavan.stringtoimage”
    android:versionCode=”1″
    android:versionName=”1.0″ >

    <uses-sdk
        android:minSdkVersion=”8″
        android:targetSdkVersion=”17″ />

    <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

    <application
        android:allowBackup=”true”
        android:icon=”@drawable/ic_launcher”
        android:label=”@string/app_name”
        android:theme=”@style/AppTheme” >
        <activity
            android:name=”com.pavan.stringtoimage.MainActivity”
            android:label=”@string/app_name” >
            <intent-filter>
                <action android:name=”android.intent.action.MAIN” />

                <category android:name=”android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>
    </application>

</manifest>

OUTPUT :

Bitmap Image

Also Don’t Miss : Android Extract Image From PDF and Save

  • super very nice tutorials………………….

  • pls u will add phonegap tutorialsssssssssss

  • Very nice. How to read data from image ???? Do u have any idea please tell me !!!!!!

  • @M Kumar

    Sure will post articles on phone gap

  • @vemanna
    using OCR technology it's possible to read data from image

  • nice Logic

  • program runs fine but i am unable to find the saved image.Actually image is not saving in my sdcard. i already gives permission
    Please help me sir

  • Can we convert a form which consist of text and image into single image.