Drawing a font on an offscreen image

I'm trying to draw a font on my own offscreen image but I had to implement a few tweaks to get it to work and I would like to know how to do it properly. Here's my code:
  private int[] getPrintMetrics(Font fnt, String txt) {
    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D bg = (Graphics2D)bi.getGraphics();
    FontRenderContext frc = bg.getFontRenderContext();
    TextLayout tl = new TextLayout(txt, fnt, frc);
    int ret[] = new int[2];
    ret[0] = (int)tl.getBounds().getWidth();
    ret[1] = (int)(tl.getBounds().getHeight() * 1.5);
//    ret[0] = (int)tl.getPixelBounds(frc, 0, 0).getWidth();
//    ret[1] = (int)(tl.getPixelBounds(frc, 0, 0).getHeight() * 1.5);
    //BUG! WHY IS HEIGHT TOO SMALL? I HAVE TO ADD 50%
    return ret;
  public void print(Font fnt, int x, int y, String txt, int clr) {
    int size[] = getPrintMetrics(fnt, txt);
    BufferedImage bi = new BufferedImage(size[0], size[1], BufferedImage.TYPE_INT_RGB);
    Graphics2D bg = (Graphics2D)bi.getGraphics();
    FontRenderContext frc = bg.getFontRenderContext();
    TextLayout tl = new TextLayout(txt, fnt, frc);
    //this method draws the outline only
    Shape shape = tl.getOutline(AffineTransform.getTranslateInstance(0, tl.getBounds().getHeight()));
    bg.setColor(new Color(clr));
    bg.draw(shape);
    bg.setColor(new Color(clr));
    bg.setFont(fnt);
    bg.drawString(txt, 0, -1 * tl.getBaselineOffsets()[tl.getBaseline()+2]);   //BUG! HOW DO I KNOW WHICH BASELINE TO USE?
    putPixels(bi.getRGB(0,0,size[0],size[1],null,0,size[0]), x, y, size[0], size[1], 0);
  }putPixels() is my own member that will draw to my own image buffer.
1) Why must I multiply the height by 1.5 in the getPrintMetrics() ?
2) How do I know which baseline to use (I just hacked it).
Thanks.

Why is the height so small?
new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);The graphics context for this BufferedImage is very small.
For more size increase the width and height dimensions.
Try this.
import java.awt.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class GraphicsExercise {
    private JLabel getContent() {
        BufferedImage image = createImage();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setPaint(Color.blue);
        Font font = new Font("dialog", Font.PLAIN, 36);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        String s = "Hello World";
        LineMetrics metrics = font.getLineMetrics(s, frc);
        float height = metrics.getAscent() + metrics.getDescent();
        float width = (float)font.getStringBounds(s, frc).getWidth();
        float x = (image.getWidth() - width)/2f;
        float y = (image.getHeight() + height)/2 - metrics.getDescent();
        g2.drawString(s, x, y);
        g2.dispose();
        return new JLabel(new ImageIcon(image), JLabel.CENTER);
    private BufferedImage createImage() {
        int w = 240;
        int h = 165;
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(w, h, type);
        Graphics2D g2 = image.createGraphics();
        g2.setBackground(UIManager.getColor("Panel.background"));
        g2.clearRect(0,0,w,h);
        g2.dispose();
        return image;
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new GraphicsExercise().getContent());
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
}

Similar Messages

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • PB: PixelGrabber, offscreen Image, Windows 98, ie5

    Hello,
    I've got a problem with a bug that occurs under Windows 98, and ie5.
    This is the code of a little applet that works fine under Windows NT, but not under Windows 98:
    This applet draws 3 colors in a square, and use the grabPixel method for catching the pixels of the image and create another image with those pixels.(the image should be the same)
    The problem is that the grabPixel method changes the colors of the pixels. It occurs only with an offscreen Image (that means an Image created with the createImage(w, h) method). there is no problem with a MemoryImageSource, for example.
    I just notice that the ColorModel of an offscreen Image is not the same as the default ColorModel:
    colorModel: java.awt.image.DirectColorModel = {...}
    red_mask: int = 0xf800 (instead of 0x00ff0000 )
    green_mask: int = 0x7e0 (instead of 0x0000ff00 )
    blue_mask: int = 0x1f (instead of 0x000000ff)
    alpha_mask: int = 0x0 (instead of 0xff000000)
    red_offset: int = 0xb
    green_offset: int = 0x5
    blue_offset: int = 0x0
    alpha_offset: int = 0x0
    red_scale: int = 0x1f
    green_scale: int = 0x3f
    blue_scale: int = 0x1f
    alpha_scale: int = 0x0
    But i don't know how to solve the bug.
    Here is the code :
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    public class AppletFlush extends Applet implements Runnable{
    Thread anim;
    Image memimg;
    boolean bool;
    Image offImage;
    Graphics offGraphics;
         public void init() {
         public void start() {
         anim = new Thread(this);
         anim.start();
    bool = true;
    offImage = this.createImage(100, 100);
    offGraphics = offImage.getGraphics();
         public synchronized void stop() {
         anim = null;
         notify();
         public synchronized void run() {
         while (Thread.currentThread() == anim) {
    int[] pixels = new int[100 * 100];
    int color = 0;
    //set the pixels of a squared image that contains 3 colors (this is my reference image)
    if (bool)
    bool = false;
    for (int i=0; i<100; i++)
    if (i<33)
    color = 0xffff0000;
    else if (i<66)
    color = 0xff00ff00;
    else
    color = 0xff0000ff;
    for (int j=0; j<100; j++)
    pixels[i*100 + j] = color;
    else
    //grab the pixels of the offscreen image(here is the problem)
    PixelGrabber pg = new PixelGrabber(offImage, 0, 0, 100, 100, pixels, 0, 100);
    try
    pg.grabPixels();
    catch (InterruptedException ex)
    System.out.println("erreur pendant gragPixels !!!");
    //create the new image with the pixels
    MemoryImageSource imgsrc = new MemoryImageSource(100, 100, pixels, 0, 100);
    memimg = createImage(imgsrc);
    //draw the image in the offscreen image
    offGraphics.drawImage(memimg, 0, 0, null);
              repaint();
              try {wait(1000);} catch (InterruptedException e) {return;}
         public void paint(Graphics g) {
         // display the offscreen image
         g.drawImage(offImage, 0, 0, this);
    PLEASE HELP !
    YaYa

    try
    public void paint(Graphics g )
    if((_offScreen != null)&&(offScreenImage != null))
    // put your stuff here
    else
    update(g);
    g.dispose();
    g.finalize();
    return;
    public void update(Graphics g)
    if( offScreenImage == null)
    offScreenImage = this.createImage( width, height );
    if( _offScreen == null)
    _offScreen = offScreenImage .getGraphics();
    paint(g);
    }

  • Copy offscreen image to applet

    I drew points to an offscreen Image and tried to copy it to my applet, but the applet is just white.
    my code:
        public void paint (Graphics g)
            Image Drawing = Background;
            Drawing.getGraphics ().setColor (Paint);
            int Index = 0;
            while (Index < points.size ())
                Drawing.getGraphics ().drawLine ((int) Math.round (((Point) poins.get (Index)).getX ()), (int) Math.round (((Point) points.get (Index)).getY ()), (int) Math.round (((Point) points.get (Index)).getX ()), (int) Math.round (((Point) points.get (Index)).getY ()));
                Index = Index + 1;
            g.drawImage (Drawing, 0, 0, this);
        }what am I doing wrong?
    (oh yeah, and is there a better way to draw points, or do I really have to draw 1x1 pixel lines?)

    It is true that turning off graphics acceleration eliminates the problem, but you can't publish an applet that requires every user turn off hardware acceleration on their PC. The problem has to be either fixed in the awt (unlikely since 1.6.10 is at RC) or bypassed in the applet.
    So, if you are reading this because you have a production applet broken by the changes in Java 1.6.10, I am afraid you are going to have to make changes to your paint routine to avoid the applet using any drawImage coordinates that reference areas outside the clip region of the graphics context.

  • Painting in a thread without offscreen image

    I'm trying to develop a good map viewer with java. Now, painting a map can
    be a very long task, and the requirements for a good map viewer should be:
    * the user can see progress, that is, the map is painted incrementally on the
    screen, not offscreen, otherwise the user has to sit and wait looking at
    a gray pane for seconds (a complex map may take 20-30 seconds to paint)
    * the user can stop rendering, or, if the panel is resized, the rendering should
    immediatly restart.
    The second requirement could be achieved by painting in a separate thread
    onto a BufferedImage and then invoke paint back to copy the image onto
    screen, but this approach fails to meet the first requirement... is there any way
    to paint directly on the screen without blocking the swing event thread?
    Moreover, ins't the hardware acceleration lost by using an offscreen image?

    To achieve visibly incremental progress of painting on the panel, probably you can use a JTimer and set the delay to 1000ms. In this frequency you can paint the panel in an incremental fashion. This approach will help you to achieve the other requirement of stopping the progress in the middle. You can provide a button, so that if the user presses the button, then invoke stop() method of timer which eventually stops the progress of the panel. Also if you want, you can restart() the progress from the point where it got stopped previously, by invoking restart() method of timer.
    Obviously, you should have a method which does all your painting and so on. Here JTimer can be helpful only in stopping, restarting and delaying the progress. Finally, make sure that the painting method is handled by JTimer alone.
    Hope this helps.

  • Drawing on top of a gif image.

    I need to be able to have a JPanel that holds a .gif image, have another JPanel over top of it that can be drawn upon. An example of this is placing a map on a table and laying a piece of clear plastic over top of it, then drawing on the plastic the route you want to take. Just as in this example, I want to be able to erase lines on the top image, but I can probably figure that part out OK, I just need the code to layer the drawing panel on top on the image.
    How can this be done?
    Thanks.

    Exactly what problem are you having with getting a layered pane? The Java Tutorial on this site can give you all the basics regarding setting one up.

  • Is it possible to use the drawing dynamic content to erase an image rather than draw over the top?

    I'm trying to create a cover for my magazine  that has a chalk board with writing on. I want the user to be able to erase the writing with their finger but can't figure out how to do it. All i can do is draw a solid colour over the top. What i want is for the finger swipe to erase the .png image instead. wondered if it can be done using a mask but I can only get a mask to reveal solid colour not an image.

    If the images are exactly the same size then make sure the layer with the mask
    is the active layer and in the other documents go to Select>Load Selection and choose
    your document with the layer mask under Source document and under channel choose the layer mask.
    After the selection loads press the layer mask icon at the bottom of the layers panel.
    MTSTUNER

  • Font Problem with Embedded Images when making PDFs

    Hello,
    I am revising a document I didn't create which has embedded images. Although all of the fonts are turned on, when I create a PDF, the fonts in the EPS come out as Courier. When I print to my laser printer, the fonts in the EPS come out correctly. This job will eventually be produced as a PDF, so I need to figure this out. Any ideas?
    Thanks.

    We can't spend the time to retrieve the originals and distill them.
    Yes, I understand that. I like to know why things don't work, even if it takes me a few minutes to test things. You don't have to retrieve any originals. Just unembed one from the ID file. I know it doesn't make sense to Distill all your EPS files when printing to PDF is going to take much less time. But if you can ascertain why it's not working, you'll have a better chance to fix it next time.
    If the fonts weren't included in the original EPSs, why do they print to PDF in Franklin Gothic? This is true even in the one page document I sent you that doesn't have any styles.
    They don't...unless you have that exact Franklin Gothic loaded on your system. They print in Courier here.
    Your EPS file references a specific font name. When you print, your print driver matches up that reference with the Franklin Gothic font you have loaded. For reasons that I don't fully understand, when you Export to PDF Indesign is not able to match up the reference to the font the same way your print driver can.
    Obviously, printing to PDF is a good workaround. And make sure you send your printer a PDF, not a live Indesign file.
    Ken

  • Best software or programme? : I have designs for cards done on a particular app, I need to import somehow typed text (old type writer font) to beside the image? Is something like illustrator or photoshop the best? For card design to then send to printers

    Hello
    I have started designing cards etc
    I have been drawing items on two particular apps on my iPad, but I need to import some old school type writter style text alongside the image.
    What is the best software or programme to do this?
    I don't mind buying some good software
    Basically I would like something in could draw with a stylus on ( or import these images from another app that I can do this on)
    Then add bespoke text beside the image
    Play about with positions, colours sizes etc
    Has anyone tried any of the Wacom products??
    These would all then be sent to printing company to print
    Thanks for your help!

    Hello
    I have started designing cards etc
    I have been drawing items on two particular apps on my iPad, but I need to import some old school type writter style text alongside the image.
    What is the best software or programme to do this?
    I don't mind buying some good software
    Basically I would like something in could draw with a stylus on ( or import these images from another app that I can do this on)
    Then add bespoke text beside the image
    Play about with positions, colours sizes etc
    Has anyone tried any of the Wacom products??
    These would all then be sent to printing company to print
    Thanks for your help!

  • Change font stlye in bridge image gallery

    can anyone tell me how I can make the headings in the bridge image gallery italic text

    I haven't used the Bridge galley, but my first guess would be dig into the gallery's CSS. It's either in a CSS doc or in the head of the gallery pages, but it's sure to be in CSS somewhere.  This would be for colors and font anyway,,, I don't know if Bridge formats wilt CSS or tables, you just have to open the documents in Dreamweaver to see.
    Lawrence Cramer - *Adobe Community Professional*
    http://www.Cartweaver.com
    Shopping Cart for Adobe Dreamweaver
    available in PHP, ColdFusion, and ASP
    Stay updated - http://blog.cartweaver.com

  • Draw on TiledImage as one unified image, still managing memory using tiles

    what I am looking for is **exactly** this
    http://www.garayed.com/java/186952-question-about-tiledimage-graphics2d-jai.html
    "(...)How do I create an arbitrarily large TiledImage from scratch (lacking a
    source image) and draw onto it using the TiledImage's graphics context
    ( TiledImage.createGraphics() ) without causing an
    OutOfMemoryException?
    The content of the image would be purely Graphics2D geometry. I don't
    need to read in any external images, just to be able to create, and
    draw on, very large blank images. I'm assuming that TiledImage is the
    most appropriate class for this, but haven't been able to find any
    sample implementations.
    There must be some way to draw on a TiledImage as one unified image,
    while still managing memory using tiles.(...)"
    any ideas?
    TIA

    great article
    my conclusion is that it seems java can't provide a huge graphics environment for drawing in a transparent manner, I think.
    let's suppose I have a huge tiledImage. 20,000 x 20,000 pixels
    now I want to draw a huge circle, radius = 10,000, center is the same square center
    just an example, to clarify my doubt
    when I request a Graphics2D context to draw this circle, tiledImage will intelligently and transparently request the necessary tiles to draw this circle, or I would have to code manually something to grab these tiles, calculate what to draw in each one and manage the tile cache?
    TIA

  • How Do I Draw a Circle / Line Through An Image In Pages?

    Hi guys,
    I never do anything very involved in Pages but today ...
    I have an image (jpeg file) and I would like to draw a circle around it and a line through it -- you know, turn it into one of those International "Don't Do This" signs.
    Is there an easy way?
    Thanks
    I'm using Pages '09 version 4.1

    Insert a round Shape and give it a very thick border with equally thick line (also in Shapes) diagonally across the circle.
    To add the image just drag it onto the shape and when you positioned it the way you like it, group the two.
    Peter

  • Please help.. !! Can I make an offscreen Image by painting JComponent

    Hello friends,
    I have a class Sprite which extends JComponent.. and it is overriding paintComponent(Graphics g) and painting image in it.. !!
    I just want to know that.. can I make my own offscreen Buffered Image like this..!!
    BufferedImage buffer = new BufferedImage(128, 128, BufferedImage.TYPE_3BYTE_BGR);
    Graphics g = buffer.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, 128 , 128);
    for (int i = 0; i < 4; i++) {
    Sprite s = (Sprite) stack.get(i);
    g.drawImage(s.img, s.getLocation().x, s.getLocation().y, null);
    }Will this make my offscreen Buffered Image buffer?
    Thanking in advance
    gervini

    Hello friends,
    I have a class Sprite which extends JComponent.. and it is overriding paintComponent(Graphics g) and painting image in it.. !!
    I just want to know that.. can I make my own offscreen Buffered Image like this..!!
    BufferedImage buffer = new BufferedImage(128, 128, BufferedImage.TYPE_3BYTE_BGR);
    Graphics g = buffer.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, 128 , 128);
    for (int i = 0; i < 4; i++) {
    Sprite s = (Sprite) stack.get(i);
    g.drawImage(s.img, s.getLocation().x, s.getLocation().y, null);
    }Will this make my offscreen Buffered Image buffer?
    Thanking in advance
    gervini

  • How to save or save a drawing in a PNG or any Image file format ?

    Hi,
    I am working on a signature capturing application using J2ME MIDP 2.0 for Palm Treo 750 with Windows Mobile 6.0
    I am taking signatures as a drawing on a CustomItem.
    Now, i want to send it to a php script running on Apache server to save this signature as a PNG, jpeg or any image file at server end.
    or how can i save this drawing on my local file system as a png or any other type of image file.
    Plz help if anybody knows the right way....
    Thanks.

    Hi Hithayath,
    Thnx for the reply.
    Actually, i hv no problem in storing a data locally or sending it on a web server. The problem in related with the formats.
    I mean, how can we create a png or jpg file using the raw bytes of an image drawn on a canvas or CustomItem.. ?
    We can get the integer array of RGB points using getRGB() method of image object. Now, if i will write this data after converting to binary in a file then that file
    will show a message like "Preview not available". It means the format is not recognized.
    So, my question is how can we convert this raw data in a png or jpg format so it can be displayed on a web page or stored in a png or jpg file..?
    I think now u can better understand the problem.
    Waiting for the reply....
    Thanks. :)

  • What is the font name in the image provided?

    I have been searching for days for a particular font. My HR department provided me with an image but I can't find the exact font.
    Thank you,
    Branden

    I would check out http://www.myfonts.com/WhatTheFont/

Maybe you are looking for

  • List of po with open advances

    Hi,    I want to know list of purchase orders which have open advances.   plz suggest me the report or transaction name where i will get this details of vendor/ purchase order and balance advance amount.

  • Is there any documentation on Peoplesoft CRM 9 HelpDesk SLA's?

    Hi, Is there any documentation available on Peoplesoft CRM 9.0 HelpDesk about Service Level Agreements for internal employees? We are looking into implementing Service Level Agreements on the Help Desk module for internal clients (employees). I am lo

  • Best external drive for Air Tunes?

    My eight month old Western Digital My Book Pro just died. I had used it to backup various files but mostly to house my 260 GB iTunes music folder. I use iTunes to stream music to my living room receiver, so I'd often leave it running all day. While t

  • Maintenance View select query

    Can we write a select query for maintenace view. If no why  please explain. What is the purpose of maintenace view

  • How do we decide the number of data base servers and application servers ?

    Dear Gurus, How do we decide the number of data base servers and application servers in BW ? How does this number help in data load balance and reporting needs ? Any hard n fast rule in the number of servers ? Regards Mohan