1

The question is in the title. For example how can I save g in a file in the following snippet ?

public void paints(Graphics g, Image background, Image watermark, int width, int height) {

g.drawImage(background, 0, 0);
g.drawImage(watermark, 0, 0);
g.setColor(0xFF0000);

// Upper left corner
g.fillRect(0, 0, 10, 10);

// Lower right corner
g.setColor(0x00FF00);
g.fillRect(width - 10, height - 10, 10, 10);

g.setColor(0xFF0000);
Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
g.setFont(f);
// Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
g.drawString("HelloWorld", 
        (int) (848 ),
        (int) (610)
        );

// NOW how can I save g in a file ?

}

The reaseon why I don't want to take a screenshot is because I want to keep the full resolution of g (eg : 2000 x 1500).

I would be so grateful to anyone that can tell me how to do that with Codename one. If not possible then it is already good to know it!

Cheers,

HelloWorld
  • 2,275
  • 18
  • 29

2 Answers2

2

What you could do is to create an Image as buffer, get the graphics object from the image an do all your drawings operations on it. Then draw the whole image to the display and save it as a file:

int height = 2000;
int width = 1500;
float saveQuality = 0.7f;

// Create image as buffer
Image imageBuffer = Image.createImage(width, height, 0xffffff);
// Create graphics out of image object
Graphics imageGraphics  = imageBuffer.getGraphics();

// Do your drawing operations on the graphics from the image
imageGraphics.drawWhaterver(...);

// Draw the complete image on your Graphics object g (the screen I guess) 
g.drawImage(imageBuffer, w, h);

// Save the image with the ImageIO class
OutputStream os = Storage.getInstance().createOutputStream("storagefilename.png");
ImageIO.getImageIO().save(imageBuffer, os, ImageIO.FORMAT_PNG, saveQuality);

Note, that I have not tested it, but it should work like that.

Gabriel Haas
  • 117
  • 6
  • Thanks this is working as expected!!! The output image file has the same dimensions as the original image! But why is it that the method I used did not work ? The only difference with yours is that you use an intermediate image as buffer whereas I directly drew on the Graphics object g. Thanks in advance if you or maybe @Shai can add some explanations. – HelloWorld Jun 12 '16 at 14:36
1

Graphics is just a proxy to a surface, it has no knowledge or access to the underlying surface to which it is drawing and the reason for that is quite simple. It can draw to a hardware accelerated "surface" where there is physically no underlying image.

This is the case both on iOS and Android where the "screen" is natively drawn and has no buffer.

Shai Almog
  • 51,749
  • 5
  • 35
  • 65
  • Thanks @Shai, so if there is no buffer it will not be possible to save the Graphics in a file. Consequently screenshot is my only way to go! – HelloWorld Jun 10 '16 at 04:58