Skip to content
Advertisement

Generate a image with custom text in Android

I’m trying to make an app for create custom cards. I’d like to add some text over a custom background (a jpg image).

What is the best way of doing it? I’d need to show the user a preview of the card before send it to the server.

Thanks

Advertisement

Answer

Use below code to achieve your requirement

    Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage); // the original file yourimage.jpg i added in resources
    Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);

    String yourText = "My custom Text adding to Image";

    Canvas cs = new Canvas(dest);
    Paint tPaint = new Paint();
    tPaint.setTextSize(35);
    tPaint.setColor(Color.BLUE);
    tPaint.setStyle(Style.FILL);
    cs.drawBitmap(src, 0f, 0f, null);
    float height = tPaint.measureText("yY");
    float width = tPaint.measureText(yourText);
    float x_coord = (src.getWidth() - width)/2;
    cs.drawText(yourText, x_coord, height+15f, tPaint); // 15f is to put space between top edge and the text, if you want to change it, you can
    try {
        dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/ImageAfterAddingText.jpg")));
        // dest is Bitmap, if you want to preview the final image, you can display it on screen also before saving
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

You have to use below permission in manifest file.

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

For my device the path is /sdcard to access external SD card, it may vary for other devices. Some devices may have /mnt/sdcard may be it is for internal sd cards. Just check it while before using this code.

Actually I wrote the above code for some other question, which required time stamp on photo after captured from camera. I gave you the same solution with a little modifications for your specific requirement.

I hope you can understand this. If you have any doubts regarding code feel free to ask.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement