Drawing on top of an image

Hello!
I am trying to create a Panel on which I can draw stuff using the mouse. I have managed to get it working, apart from one small part. I want to have an image (jpg) as a background, and as soon as I try to add an image either the image does not show or the drawing stuff stops working.
Here is my working drawing code (i.e. without image):
public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (image == null || image.getWidth(null) != getWidth()
               || image.getHeight(null) != getHeight()) {
            image = (BufferedImage) createImage(getWidth(), getHeight());
            graph = (Graphics2D) image.getGraphics();
            graph.fillRect(0, 0, getWidth(), getHeight());
            graph.setColor( Color.white );
            graph.setStroke(new BasicStroke(3));
            graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                  RenderingHints.VALUE_ANTIALIAS_ON));
         Rectangle r = g.getClipBounds();
         g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
               r.x + r.width, r.y + r.height, null);
         if (endPoint != null) {
            g.setColor(currentColor);
            if (shapeType == 0)
               g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
            if (shapeType == 1)
               g.drawOval(pn.x, pn.y, pn.width, pn.height);
            if (shapeType == 2)
               g.drawRect(pn.x, pn.y, pn.width, pn.height);
         public void mouseDragged( MouseEvent m ) {
            if (shapeType > 3 && shapeType != 8)
               return;
            if (endPoint == null)
               endPoint = new Point();
            repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
            pn.x = Math.min(startPoint.x, m.getX());
            pn.y = Math.min(startPoint.y, m.getY());
            pn.width = Math.abs(m.getX() - startPoint.x);
            pn.height = Math.abs(m.getY() - startPoint.y);
            if (shapeType == 0) {
               endPoint.setLocation(m.getPoint().getLocation());
            if (shapeType == 3) {
               graph.setColor(currentColor);
               graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
               startPoint = m.getPoint();
            repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
         public void mouseReleased(MouseEvent m) {
            if (endPoint != null)
               draw();
            endPoint = null;
         public void mousePressed(MouseEvent m) {
            startPoint = m.getPoint();
         public void draw() {
            graph.setColor(currentColor);
            if (shapeType == 0)
               graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
            if (shapeType == 1)
               graph.drawOval(pn.x, pn.y, pn.width, pn.height);
            if (shapeType == 2)
               graph.draw(pn);
            repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
         }To me it seemed logical to add:
graph.drawImage(my_gif, 0, 0, this);at the end of the if statement, but that did not work.
Where and how should I add the image?
Thanks!

Thanks for answering!
Here is the entire code:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class ImageExample extends JApplet {
   private static final Dimension DRAWING_AREA_SIZE = new Dimension(300,300);
   private static final Point DRAWING_AREA_UPPER_LEFT = new Point(100,50);
   private static final Color BACKGROUND_COLOR = Color.black;
   private Image my_gif;
   private Color currentColor = Color.white;
   private JLabel currentColorIndicator;
   private JPanel pane = new JPanel(null);
   Point startPoint, endPoint;
   Rectangle pn = new Rectangle();
   BufferedImage image;
   Graphics2D graph;
   int shapeType = 3;
   public void init() {
      setContentPane(pane);
      my_gif = getImage( getDocumentBase(), "fractal.gif" );
      pane.setOpaque(true);
      pane.setBackground(BACKGROUND_COLOR);
      createColorMap();
      DrawingPanel drawingPanel = new DrawingPanel();
      drawingPanel.setBounds(DRAWING_AREA_UPPER_LEFT.x, DRAWING_AREA_UPPER_LEFT.y, DRAWING_AREA_SIZE.width,
            DRAWING_AREA_SIZE.height);
      pane.add(drawingPanel);
   // Private methods
   private void createColorMap() {
      ColorPickerListener listener = new ColorPickerListener();
      JLabel colorText = new JLabel("Color");
      colorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y-20, 50, 25);
      colorText.setForeground(Color.white);
      pane.add(colorText);
      JLabel redColor = new JLabel("");
      redColor.addMouseListener(listener);
      redColor.setBackground(Color.RED);
      redColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+10, 50, 30);
      redColor.setOpaque(true);
      pane.add(redColor);
      JLabel blueColor = new JLabel("");
      blueColor.addMouseListener(listener);
      blueColor.setBackground(Color.blue);
      blueColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+40, 50, 30);
      blueColor.setOpaque(true);
      pane.add(blueColor);
      JLabel whiteColor = new JLabel("");
      whiteColor.addMouseListener(listener);
      whiteColor.setBackground(Color.white);
      whiteColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+70, 50, 30);
      whiteColor.setOpaque(true);
      pane.add(whiteColor);
      JLabel greenColor = new JLabel("");
      greenColor.addMouseListener(listener);
      greenColor.setBackground(Color.green);
      greenColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+100, 50, 30);
      greenColor.setOpaque(true);
      pane.add(greenColor);
      JLabel blackColor = new JLabel("");
      blackColor.addMouseListener(listener);
      blackColor.setBackground(Color.black);
      blackColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+130, 50, 30);
      blackColor.setOpaque(true);
      pane.add(blackColor);
      JLabel grayColor = new JLabel("");
      grayColor.addMouseListener(listener);
      grayColor.setBackground(Color.gray);
      grayColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+160, 50, 30);
      grayColor.setOpaque(true);
      pane.add(grayColor);
      JLabel yellowColor = new JLabel("");
      yellowColor.addMouseListener(listener);
      yellowColor.setBackground(Color.yellow);
      yellowColor.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+190, 50, 30);
      yellowColor.setOpaque(true);
      pane.add(yellowColor);
      // Display currently chosen color
      JLabel currentColorText = new JLabel("Current");
      currentColorText.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+230, 50, 25);
      currentColorText.setForeground(Color.white);
      pane.add(currentColorText);
      currentColorIndicator = new JLabel("");
      currentColorIndicator.setBounds(10, DRAWING_AREA_UPPER_LEFT.y+260, 50, 30);
      updateCurrentColorLabel();
      currentColorIndicator.setOpaque(true);
      pane.add(currentColorIndicator);
   private void updateCurrentColorLabel() {
      currentColorIndicator.setBackground(currentColor);
      currentColorIndicator.setForeground(new Color(255 - currentColor.getRed(), 255 - currentColor.getGreen(),
            255 - currentColor.getBlue()));
   // Private classes
   private class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener {
      BufferedImage image;
      public DrawingPanel() {
         addMouseMotionListener(this);
         addMouseListener(this);
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         if (image == null || image.getWidth(null) != getWidth()
               || image.getHeight(null) != getHeight()) {
            image = (BufferedImage) createImage(getWidth(), getHeight());
            graph = (Graphics2D) image.getGraphics();
            graph.fillRect(0, 0, getWidth(), getHeight());
            graph.setColor( Color.white );
            graph.setStroke(new BasicStroke(3));
            graph.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                  RenderingHints.VALUE_ANTIALIAS_ON));
            graph.drawImage(my_gif, 0, 0, this);
            System.out.println(my_gif + " <- my_gif");
            System.out.println(my_gif.getWidth(this) + " <- my_gif.getWidth(this)");
            System.out.println(my_gif.getHeight(this) + " <- my_gif.getheight(this)");
         Rectangle r = g.getClipBounds();
         g.drawImage(image, r.x, r.y, r.x + r.width, r.y + r.height, r.x, r.y,
               r.x + r.width, r.y + r.height, null);
         if (endPoint != null) {
            g.setColor(currentColor);
            if (shapeType == 0)
               g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
            if (shapeType == 1)
               g.drawOval(pn.x, pn.y, pn.width, pn.height);
            if (shapeType == 2)
               g.drawRect(pn.x, pn.y, pn.width, pn.height);
         public void mouseDragged( MouseEvent m ) {
            if (shapeType > 3 && shapeType != 8)
               return;
            if (endPoint == null)
               endPoint = new Point();
            repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
            pn.x = Math.min(startPoint.x, m.getX());
            pn.y = Math.min(startPoint.y, m.getY());
            pn.width = Math.abs(m.getX() - startPoint.x);
            pn.height = Math.abs(m.getY() - startPoint.y);
            if (shapeType == 0) {
               endPoint.setLocation(m.getPoint().getLocation());
            if (shapeType == 3) {
               graph.setColor(currentColor);
               graph.drawLine(startPoint.x, startPoint.y, m.getX(), m.getY());
               startPoint = m.getPoint();
            repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
         public void mouseReleased(MouseEvent m) {
            if (endPoint != null)
               draw();
            endPoint = null;
         public void mousePressed(MouseEvent m) {
            startPoint = m.getPoint();
         public void draw() {
            graph.setColor(currentColor);
            if (shapeType == 0)
               graph.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
            if (shapeType == 1)
               graph.drawOval(pn.x, pn.y, pn.width, pn.height);
            if (shapeType == 2)
               graph.draw(pn);
            repaint(pn.x, pn.y, pn.width + 1, pn.height + 1);
         public void mouseClicked(MouseEvent arg0) {}
         public void mouseEntered(MouseEvent arg0) {         }
         public void mouseExited(MouseEvent arg0) {         }
         public void mouseMoved(MouseEvent arg0) {         }
   //Listeners
   private class ColorPickerListener extends MouseAdapter {
      public void mouseClicked(MouseEvent e) {
         JLabel color = (JLabel) e.getSource();
         currentColor = color.getBackground();
         updateCurrentColorLabel();
}So the problem might be that the system.outs in there put out:
sun.awt.image.ToolkitImage@1a0c10f <- my_gif
-1 <- my_gif.getWidth(this)
-1 <- my_gif.getheight(this)I don't know how to fix so that the height and width are set. Isn't it enough to do the:
      my_gif = getImage( getDocumentBase(), "fractal.gif" );before initializing the drawing panel?
Thanks again!

Similar Messages

  • How can I draw on top of an image?

    I'm using a JApplet with three JPanel's inside of it.
    Inside one of those JPanel's I would like to place an image and a button. When the button is clicked, I want to draw an oval on top of the image . Each subsequent time the button is clicked, the oval will move to a different location.
    So here are my questions:
    1) What should I use to draw the image? (a JLabel with an ImageIcon on it?)
    2) Could I simply use g.drawOval() in paintComponent() to directly draw on top of the image/JLabel?
    Any help will be greatly appriciated.

    Here's a sample to study;-import java.awt.*;
    import java.awt.event.*;
    public class DrawOnImage extends java.applet.Applet{
      int xPos, yPos;
      Image img;
      public void init() {
        add(new Label("Hello World") );
        Button press = new Button("press");
        add(press);
        press.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            xPos = (int)(Math.random()*270);
            yPos = (int)(Math.random()*170)+30;
            repaint();
        img = getImage(getDocumentBase(), "anImage.JPG");
      public void paint(Graphics g){
        g.drawImage(img,0,30,this);
        if(yPos>=30)g.fillOval(xPos, yPos, 45, 45);
    }

  • 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.

  • Exporting Text out of Fireworks on top of BG image

    In Fireworks I have a black background with text content on top of it.  I would like to export both so that the bg comes into dreamweaver as a background image and the text comes in as editable text.  Right now when I slice the bg it automatically includes the text in the image.  How do I export text that is on top of an image?

    I forgot earlier to say that you must finally export as CSS and Images.
    I'll try to give some simple advice while trying to export css from Fireworks CS4.
    You can apply the blue background, by simply adding it from the CSS and Images export options. You should not draw it in your document(, it doesn't matter at all).
    Draw Rectangles all over your document to finally export them as div tags.
    When you need to apply a background, think of what exactly you want your background to be, solid color, or a picture?
    If it's going to be a picture, you must place that picture and insert a slice to it, set as background.
    If you want color, you don't put a slice. You just ...draw a rectangle. Write some text over the rectangle, and you can export it as CSS.
    A slice is used to export images. Otherwise, you just draw rectangles to export the current color as a value in your exported CSS.
    The black background color of your document, can be set as a color value inside your exported css, so you don't have to place a slice for that.
    Watch not to overlap objects like images, rectangles and slices. It is going to be hard to achieve an excellent result in order to construct your web site with Fireworks while trying to export CSS.
    Jim has already said it Fireworks won't help you that much with coding like hand coding or Dreamweaver will.

  • Drawing on top of a component

    Hi there.
    if I have JPanel that contains a JLabel that contains is a 600x800 image, how can i draw a shape like circle on top of the image? I would like to be able to see the image with the circle on it. How can i make this possible?
    Right now i can draw the circle on its own JPanel, but that is not what i want.
    Thanks

    Notably, that you have a inner class referencing
    image variables defined in the class it's nested in.Inner classes can access all members of the declaring class,
    even private members. In fact, the inner class itself is said to be
    a member of the class; therefore, following the rules of
    object-oriented engineering, it should have access to all
    members of the class.
    The inner class does nothing to set it's own size,
    , since as far as that JLabel instance knows, it
    contains nothing.
    But this is not corrected, it's
    only relying on the BorderLayout to fill the frame
    with the label.
    While your sample works fine as is, it's not very
    portable. As the OP posted after, he attempted to
    use your code adding a JPanel in between the content
    pane and the label, and it wouldn't work because of
    the layout issues. To solve that, one might tend
    towards defining a null layout and setting the bounds
    explicitly, or one might add a setMinimumSize or
    setPreferredSize call to get a size.
    But that's adding more code to fix a problem that has
    a much simpler solution. Which is to just give the
    label the image directly, let the label size itself
    automatically based on that image, let the label draw
    the image itself and only override paint to get the
    custom drawing done on top.
    Myself, I understand what you were saying in your
    code. But clearly the OP did not, and I suspect was
    heading to starting patching what wasn't working by
    applying more code when one could more cleanly use
    less code and take advantage of what JLabel will
    already do for you.Agreed. But this problem can also be easily solved with "setPreferredSize(new Dimension(200,200));" in the constructor of "Picture".

  • Photo editor: fade a photo and draw on top of it?

    I want to "fade" JPG pictures of people and then draw on top of them with a brush tool to emphasize posture (for instructional purposes) and save as a JPG. By "fade" I mean lighten the pic so that my drawn lines will stand out.
    It appears that GIMP will do this. Can you also do that with SeaShore? In their documentation it is not clear to me; I get bogged down with tech lingo about layers and transparent colors and so on. My goal is to find a tool to do the above without getting something way more sophisticated than I need. Thanks for any help.
    Fran

    I'm not familar with GIMP, but I can shed some light onto the layers and transparency you would need to use.
    Layers are quite simple. They are like a stack of papers, you can see the page on top, and the page below if it sticks out beyond the edges of the top sheet. The same is true in photo programs. You will see the top layer, and things behind it will be obscured by the objects or images on the top layer.
    Transparency is the "fade" you are looking for. Note that Opacity is the opposite of transparency (as in 100% opaque is 0% transparent). My reducing transparency on a layer, you allow the layers behind it to become partially visible, IE you allow them to sneak through.
    To accomplish your goal, should should take the images, and fade them by reducing their opacity. I would start with reducing it to 70%, but you'll have to play with it to get things just right.
    After doing this, create a new layer, and be sure the new layer is on top off the image layer. In this new layer, take a brush tool and draw whatever you like. You should see you drawing ontop of the photo. If not, I suspect you have actually placed your line layer behind your photo layer, and you should simply trade their locations.
    Hope this helps,

  • Is it possible to draw shapes on an background image?

    Hi all,
    I wanna ask if it is possible for loading an jpg as background image in Canvas, and draw shapes(ovals/rectangles) on it?
    I've tried, but it seems the shapes always covered by the image. How can I due with this? I want the shapes drawn on top of the image, not underneath it.
    Please Help! Thx.

    Am I doing anything wrong? cos I've already draw the shapes after the image in the paint method.
    Here's some of the program coding:
    // init
    PictCanvas coffeeCanvas=new PictCanvas();
    //set up Picture Canvas
    coffeeCanvas.thePic=getImage(getCodeBase(),"50p.jpg");
    coffeeCanvas.setSize(200,200);
    // paint method
    public void paint(Graphics g)
    g.drawImage(thePic,0,0,this);
    g.drawOval(0,0,20,20);
    repaint();
    }

  • Drawing on top

    Is it possible to layer a see through pane on top of my contents pane so that i can effectively draw on top of my current image without having to call paintComponent().
    how can i do it?

    from the desciption of panes glasspane seems to be what you want but i never have done anything with theese panes so don't count on it.

  • When i try to scroll on a image webside it scips to the bottom and then to the top of the image w/ a vertical black line instead of the curser

    whaen i try to sroll on images on a website that has a gallery and where there is a description up top and a image in th middle and more txt on the sides the scrolling is extremly choppy when i use the arrow keys to scroll

    Have you upgraded to iPhoto 9.6 for compatibility with Yosemite? If not, try that first.
    It looks like iPhoto has lost the connection between the thumbnails and the original image files.
    This can be caused by a corrupted iPhoto library, or the originals have been deleted or moved.
    Try first to rebuild your iPhoto Library:
    If you do not have a current backup of the iPhoto library, make a copy of the library, but do not overwrite any previous backup.
    Launch iPhoto with the ⌥⌘-key combination (option-command) held down.
    Select "rebuild" from the first aid panel.  This may take a while for a large library.
    Can you now see your photos again?
    If not, rebuild the library with iPhoto Library manager as described by Old Toad:            Re: iphoto crashed

  • How do I get rid of the thin line that goes across the top Persona background image.

    There is a 1-pixel wide light grey line across the top Persona background image between the navigation toolbar and the bookmarks toolbar from left to right. Nomatter whatever persona I have installed, it is there. Same thing also when i hover on any other Persona at Getpersonas.com. It is not there when using any other program and not when only showing the desktop. Only when using FF4. My PC is a HP Pavilion dv6000 laptop using Windows Vista. This is not a monitor issue nor a graphic card issue since it only shows in FF.

    for me, it happens on a maximized window. when i do restore to window, the line disappears.

  • How can I add callouts on top of anchored images in CS6?

    I am using InDesign CS6 on a MacBook. I have multiple anchored images in a long document. Some of the images require callouts, such as labels or arrows, which should display on top of the image and should always stay with the image as if these items were also anchored. Is there a way to layer images in InDesign so that they are all anchored?
    I tried grouping the callout objects with the anchored object, but you cannot select an anchored object and other objects at the same time. I know in Word you can create an image canvas and add multiple items to that, and they are all grouped together. Is there a way to do that in InDesign? Or would I have to anchor each callout along with its corresponding image?

    Peter, your advice was very helpful. However, the text boxes (callout labels) that are included in the grouped objects get distorted once the grouped objects are anchored. Each text box shows the red +. When I expand the text box to fit content, the text box expands vertically so that all of the text is below the originally anchored object.
    The other callouts (just lines) stay in place perfectly.  Any insight into why the text boxes don't behave the same way that the lines do?

  • Adding slide in caption on top of main image in gallery

    ok, now the same caption question from another angle...how
    would you get the caption to display on top of the main photo...and
    once that is accomplished, I want to add a slide effect *smile*
    I found a page that I want to recreate with spry...but its
    gonna be hard...I have the basics started, but cannot figure out
    how to put the text on TOP of the image
    http://www.nmdhsem.org/default.asp?CustComKey=270308&CategoryKey=274276&pn=Page&DomName=nm dhsem.org
    oh I am using the photo gallery demo, but hiding the select
    and gallery name so that just 3 images cycle on opening the page
    Edited: 08/28/2007 at 03:06:40 PM by karonz

    ok, so far I have this...I got the images to fade, but still
    would like to have a caption that fades in and out as well...
    any suggestions
    http://www.nmprc.state.nm.us/Copyindex.htm
    oh...and lol...I still have to get some images from NM
    instead of china *g*

  • "File could not be found" message on top of all images in Library:  How do I fix this?[was:Question]

    New to LR 5.2 Running OS X 10.8.5. Tried to save image in file folder. Now get this message at top of all images in Library: "File could not be found." How do I fix this?

    “Save” is not a term used with LR to create images.  What are you trying to do, exactly, in terms of LR menu options? 
    Are there questions marks on the thumbnails for the images that say File could not be found?
    Sometimes a screenshot can communicate things quicker than words.

  • I made a reverse radial gradient to look like "sunlight" and I would like to move it to the top of my image to appear like the light is coming from above, but it won't allow me to move the radial gradient anywhere.  I have CS6.  Help please :)

    I made a reverse radial gradient to look like "sunlight" and I would like to move it to the top of my image to appear like the light is coming from above, but it won't allow me to move the radial gradient anywhere.  I have CS6.  Help please

    Assuming you did this with a Fill Layer, double-click the thumbnail in the Layers panel to bring up the Gradient Fill dialog, see to it that the [ ] Align with layer checkbox is set, and (while the Gradient Fill dialog is still up) try dragging the gradient to where you want it on the main display.  Then [ OK ] out of the Gradient Fill dialog.
    -Noel

  • How to draw 2D shapes on the image generated by JMF MediaPlayer?

    Hello all:
    IS there any way that we can draw 2D shapes on the image generated by JMF
    MediaPlayer?
    I am currently working on a project which should draw 2D shapes(rectangle, circle etc) to
    mark the interesting part of image generated by JMF MediaPlayer.
    The software is supposed to work as follows:
    1> first use will open a mpg file and use JMF MediaPlayer to play this video
    2> if the user finds some interesting image on the video, he will pause the video
    and draw a circle to mark the interesting part on that image.
    I know how to draw a 2D shapes on JPanel, however, I have no idea how I can
    draw them on the Mediaplayer Screen.
    What technique I should learn to implement this software?
    any comments are welcome.
    thank you
    -Daniel

    If anyone can help?!
    thank you
    -Daniel

Maybe you are looking for