20

I need to create .jpeg/.png file on my Android application programmatically. I have simple image (black background), and it need to write some text on it programmatically. How can I do it? Is it possible?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1023177
  • 641
  • 3
  • 10
  • 18
  • duplicate of http://stackoverflow.com/questions/8025728/how-to-create-simple-image-programatically – Suragch May 10 '15 at 04:18

3 Answers3

9

It's definately possible.

To write text on an image you have to load the image in to a Bitmap object. Then draw on that bitmap with the Canvas and Paint functions. When you're done drawing you simply output the Bitmap to a file.

If you're just using a black background, it's probably better for you to simply create a blank bitmap on a canvas, fill it black, draw text and then dump to a Bitmap.

I used this tutorial to learn the basics of the canvas and paint.

This is the code that you'll be looking for to turn the canvas in to an image file:

OutputStream os = null; 
try { 
    File file = new File(dir, "image" + System.currentTimeMillis() + ".png");
    os = new FileOutputStream(file); 
    finalBMP.compress(CompressFormat.PNG, 100, os);
    finalBMP.recycle(); // this is very important. make sure you always recycle your bitmap when you're done with it.
    screenGrabFilePath = file.getPath();
} catch(IOException e) { 
    finalBMP.recycle(); // this is very important. make sure you always recycle your bitmap when you're done with it.
    Log.e("combineImages", "problem combining images", e); 
}
Rev Tyler
  • 601
  • 7
  • 17
6

Using Graphics2d you can create a PNG image as well:

public class Imagetest {

    public static void main(String[] args) throws IOException {
        File path = new File("image/base/path");
        BufferedImage img = new BufferedImage(100, 100,
                BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = img.createGraphics();

        g2d.setColor(Color.YELLOW);
        g2d.drawLine(0, 0, 50, 50);

        g2d.setColor(Color.BLACK);
        g2d.drawLine(50, 50, 0, 100);

        g2d.setColor(Color.RED);
        g2d.drawLine(50, 50, 100, 0);

        g2d.setColor(Color.GREEN);
        g2d.drawLine(50, 50, 100, 100);

        ImageIO.write(img, "PNG", new File(path, "1.png"));
    }
}
Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
Simmant
  • 1,477
  • 25
  • 39
6

Yes, see here

Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);

You can also use awt's Graphics2D with this compatibility project

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140