How to embed an Image onto a Shape?

I'd like to use Shape.contains() and intersects() functionalities on clipped free-form Images on a custom component. Could we embed an Image into a Shape? If the answe is yes, then, how?
If Shape is not usable, then, how could we achieve similar functionalities on Images? Do we only have run-of-the-mill coord caluculation?

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageShapes extends JPanel {
    BufferedImage image;
    Shape[] shapes;
    JLabel xLabel, yLabel;
    ImageShapes(BufferedImage image) {
        this.image = image;
    public void setCoordinates(Point p) {
        String sx = "";
        String sy = "";
        if(p != null) {
            sx = String.valueOf(p.x);
            sy = String.valueOf(p.y);
        xLabel.setText(sx);
        yLabel.setText(sy);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        if(shapes == null)
            initShapes();
        Shape origClip = g2.getClip();
        for(int j = 0; j < shapes.length; j++) {
            g2.setClip(shapes[j]);
            Rectangle r = shapes[j].getBounds();
            // center image in clip shape
            int x = r.x + (r.width - image.getWidth())/2;
            int y = r.y + (r.height - image.getHeight())/2;
            g2.drawImage(image, x, y, this);
            // smooth the edges of the clipped image
            g2.setClip(null);  // or origClip
            g2.setPaint(getBackground());
            g2.draw(shapes[j]);
    private void initShapes() {
        int w = getWidth();
        int h = getHeight();
        shapes = new Shape[3];
        shapes[0] = new Ellipse2D.Double(w/2, h/3, 175, 175);
        int R = 60;
        int sides = 5;
        int[][]xy = generateShapeArrays(w/4, h/4, R, sides);
        shapes[1] = new Polygon(xy[0], xy[1], sides);
        GeneralPath path = new GeneralPath();
        double x1 = w/4;
        double y1 = h*9/16;
        double ctrlx1 = w*9/32;
        double ctrly1 = h*5/16;
        double ctrlx2 = w*11/16;
        double ctrly2 = h*9/16;
        double x2 = w/4;
        double y2 = h*15/16;
        CubicCurve2D curve = new CubicCurve2D.Double(x1, y1, ctrlx1, ctrly1,
                                                     ctrlx2, ctrly2, x2, y2);
        path.append(curve, false);
        AffineTransform at = AffineTransform.getTranslateInstance(w/2, 0);
        at.scale(-1,1);
        Shape left = at.createTransformedShape(curve);
        path.append(left, false);
        shapes[2] = path;
    private int[][] generateShapeArrays(int cx, int cy, int R, int sides) {
        int radInc = 0;
        if(sides % 2 == 0)
            radInc = 1;
        int[] x = new int[sides];
        int[] y = new int[sides];
        for(int i = 0; i < sides; i++) {
            x[i] = cx + (int)(R * Math.sin(radInc*Math.PI/sides));
            y[i] = cy - (int)(R * Math.cos(radInc*Math.PI/sides));
            radInc += 2;
        // keep base of triangle level
        if(sides == 3)
            y[2] = y[1];
        return new int[][] { x, y };
    private JPanel getLabels() {
        xLabel = new JLabel(" ");
        yLabel = new JLabel(" ");
        Dimension d = new Dimension(45, 25);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2,2,2,2);
        gbc.weightx = 1.0;
        addComponents(new JLabel("x"), xLabel, panel, gbc, d, false);
        addComponents(new JLabel("y"), yLabel, panel, gbc, d, true);
        panel.setBorder(BorderFactory.createEtchedBorder());
        return panel;
    private void addComponents(JComponent c1, JComponent c2, Container c,
                               GridBagConstraints gbc, Dimension d, boolean b) {
        gbc.anchor = gbc.EAST;
        c.add(c1, gbc);
        c2.setPreferredSize(d);
        gbc.weightx = b ? 1.0 : 0;
        gbc.anchor = gbc.WEST;
        c.add(c2, gbc);
    public static void main(String[] args) throws IOException {
        BufferedImage image = ImageIO.read(new File("images/cougar.jpg"));
        ImageShapes test = new ImageShapes(image);
        test.addMouseMotionListener(new ShapeFinder(test));
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(test);
        f.getContentPane().add(test.getLabels(), "Last");
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class ShapeFinder extends MouseMotionAdapter {
    ImageShapes imageShapes;
    boolean hovering = false;
    ShapeFinder(ImageShapes c) {
        imageShapes = c;
    public void mouseMoved(MouseEvent e) {
        Point p = e.getPoint();
        boolean haveSelection = false;
        Shape[] shapes = imageShapes.shapes;
        if(shapes == null) return;
        for(int j = 0; j < shapes.length; j++) {
            if(shapes[j].contains(p)) {
                haveSelection = true;
                imageShapes.setCoordinates(p);
                if(!hovering)
                    hovering = true;
        if(!haveSelection && hovering) {
            hovering = false;
            imageShapes.setCoordinates(null);
}

Similar Messages

  • How to embed the Images in the java sourse

    How to embed the Images in the java sourse
    The size of the file will be too large while I put the binary code of the image into the java sourse!
    thanks

    You could encrypt them with a private key and then
    decrypt them with a public key.
    Almost had it... public key encryption works the other
    way around... otherwise what's the point of
    encrypting... if the decryption key is public?Spinoza's right. Public key encryption works both ways, but it would be useless in this case to encrypt with the private key. The problem is, how do you package your private key with the application in a way that doesn't allow the user to get it? Encrypt it? :-) I agree that there's no point to this exercize. If users want to screw up the application by editing its image files, let 'em.

  • HELP!!!! I have spent hours trying to find out how to embed an image with a link or a Microsoft Word document with a hyperlink built within the document -- not as an attachment! Does ANYONE know the secret? Can it be done, or not! My PC clients do it.

    HELP!!!! I have spent hours trying to find out how to embed an image with a link, or embed a Microsoft Word document with a hyperlink built within the document -- not as an attachment into my email -- but where it shows as the email content when opened! Does ANYONE know the secret? Can it be done, or not? My PC clients do it all the time easily. Then I want to be able to send the embedded image/document (not as an attachment, but visable within the email when opened) to many email contacts at once, BUT the individuals receiveing them DO NOT SEE the other email contacts. Cannot seem to be able to find anything on being able to do these 2 tasks.PLEASE, SOMEONE, HELP!!!

    Don't know if this applies to Lion, but read here:
    http://www.makeuseof.com/tag/create-html-announcement-mail-iweb-mac/

  • How to add external images onto a control and still be able to resize

    Hello,
    I'm a LabVIEW newbie.  I'm trying to customize the appearance of my VIs, and one of the things I like to do is to import external image and paste it onto the faceplate of the gauge indicator.  I've followed the instruction in the Labview application note using the control editor and was able to paste the picture into indicator.  But when I use it in the front panel and resize the gauge indicator, the image (added as a decoration) doesn't resize together with the indicator.  My questions are:
    1. How to add external images onto a control/indicator and still be able to resize the image automatically when I resize the control/indicator?
    2. How to "add" a new part to an existing control/indicator?  It looks like I can only customize/modify the existing parts of the control/indicator in the control editor. 
    Any help is appreciated.  Thanks.

    1/ Do not use the image as an added decoration. Instead replace part of the control with the image. Tis is illustrated in the attached vi : the arrow was pasted as a decoration, and also used to replace the slide cursor. Changing the control size do not affect the decoration, but changes the cursor.
    2/ What do you mean by adding new parts to a control. We have just seen that it was possible to modify a control. Now, if you want to include additionnal functionnality, that's another story. You can replace parts of the control, and this can give interesting results.  You can edit a slide control, and replace the numeric indicator by another control, including a numeric indicator, that you can replace with etc...
    But there, it still the same info displayed under different forms. If you want to have several independant functions on the same control, such as a string display and a boolean and a numeric indicator, then that's a job for a cluster...
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Slide with Arrow.vi ‏13 KB

  • How to project an image onto a background image?

    Hi,
    I am looking for help with projecting an image over another image.
    I am looking for a similar effect to the image above where it looks like the image of the player as (physically) been projected onto the tunnel.
    Looking closely at the detail of the image you can see that the projection adjusts to the contours of the tunnel i.e. over the framing. This is what I specifically need some help with. I know how to overlay an image onto another using different layers but it doesn't really give a three-dimensional perspective and looks rather flat.
    Any help or advice would be greatly appreciated. Thanks
    Ravi.

    Hi Ravi -
    Could you post what you have done so far, and include your expanded layers panel? The source images would also be helpful, if possible!
    One thing you could try is creating a Displacement Map of your background tunnel image and then wrapping your overlay image to it. The video tutorial below shows you how to do this:
    Beside this, you might just have to spend time tweaking your image to create a realistic overlay. This includes adjusting lighting, but also distorting your overlay image. Have you tried using Edit > Transform > Perspective to align your image to the tunnel? The other Transform tools like Distort and Warp might also come in handy.
    I'm looking forward to helping you with this effect!
    Cheers,
    Kendall

  • Can anyone tell me how to load an image to custom shape in Photoshop? I can't save it as csh...

    I've made an image, as the watermark of our photos, but I can't load it to Custom Shape in PS CS4 as I can't save it as csh. Do you know how to upload an image type file that is not csh? Or how to convert the image to csh? Thanks.

    As Chris says, you can't make it into a custom shape unless you create it as a path. But you can save it as a Custom Brush (in monochrome).

  • How to embed multiple images

    Hello!
    I have been tying to figure out how I could easily embed multiple linked images easily. I have some 1000 .svg  images which have about 1-7 .tif images linked in to them. I now need to get those links embedded and becouse of the amount of images I'm hoping to make an action out of it. I have a script to embed single image in .svg but haven't have luck with multiple embeddings.
    Any ideas?

    Great got it working now. Thanks for Your help.
    BUT (there always seems to be a but) now I'm facing new troubles. Kind of the same that Dovidgold seems to be facing http://forums.adobe.com/message/4733717#4733717
    After running the script on a image with two linked items. One of the items jumps on a different layer and scales it self to original size.
    So, once again, any ideas?

  • How to place an image onto each page

    Hi !
    How do I place an image onto each page (like a logo in a sidebar) using Pages 5.5 ?
    Thanks,
    Karsten

    Karsten,
    I am surprised no one has answered you yet - there are so many Pages users here.
    I am not a Pages user but I did find one way here on this thread in an answer from Arno Jannarelly
    insert image to header in Pages, template header
    "If you want any layout item to be repeated to all of the pages of your document, you just have to select the item(s), then go to Arrange/Section Masters/Move Object to Section Master.
    The good thing of this is that you can repeat any item or group of items placed anywhere you want on the page."
    Now when I first tried it I had no luck, until I selected the image and went to Arrange > Section Masters from the main menu, not on the right hand side from the Format/Document area.  
    From there there is an option: Move Object to Section Master.
    You then can format your image with drop shadows, opacity, etc. and it should be there on new pages in Pages. 

  • How to embed 32 images and a cover letter in an email and then send.

    I write and illustrate picture books. I need to know how to be able to embed an entire book and a cover letter in an email to send out for submissions. What is the best way of compressing the images so they arrive embedded.

    If you have an App which can handle PDFs you can use the Share icon (box with arrow) to create and send an email containing the PDF.

  • How to embed multiple images easily

    Hello!
    I have been tying to figure out how I could easily embed multiple linked images easily. I have some 1000 .svg  images which have about 1-7 .tif images linked in to them. I now need to get those links embedded and becouse of the amount of images I'm hoping to make an action out of it.
    Any ideas?

    If you try making an action, embed unfortuantley cannot be added even using "insert menu item" in the actions flyout menu.
    You could record "rasterize" which will embed, works good cause you wont get prompted for each image. Problem is if you used "select all", it would rasterize everything selected. So unless you have a layer with all your images you would have to manually select all links, since there is not a "select linked images" command.

  • How to draw an image onto a canvas3d?

    hi,
    i managed to draw onto a canvas 3d overwriting postRender() of canvas3d.
      public void postRender()
        J3DGraphics2D g = getGraphics2D();
        //  TEST BEGINN
          Image pic = this.getToolkit().createImage("Graphics" + File.separator + "start2.png");
          MediaTracker helpMT = new MediaTracker(this);
          helpMT.addImage(pic,0);
          try{
            helpMT.waitForAll();
          } catch(InterruptedException e) {}
          g.drawImage(pic,10,10,200,200,this);
          g.setColor(Color.yellow);
          g.drawString("yellow",20,300);
          g.setPaintMode();
          g.setColor(Color.red);
          g.drawString("red",20,320);
          g.setColor(Color.green);
          g.drawString("green",20,340);
          g.setColor(Color.orange);
          g.drawString("orange",20,360);
          g.flush(true);
        //  TEST ENDE
      }However the colors are totally messed up. red is purple, for example, and images are also shown with the wrong colors. What am I doin wrong, and how can I fix it?
    thanx,
    Usul

    Please, Im stuck.
    Here are the only two classes needed:
    Test2d.class:
    import java.awt.*;
    import com.sun.j3d.utils.universe.*;
    import javax.media.j3d.*;
    import javax.swing.*;
    public class Test2d extends JFrame
      public Test2d ()
        getContentPane().setLayout(new BorderLayout());
        Canvas3D c = new Visual_Canvas3D(SimpleUniverse.getPreferredConfiguration());
        getContentPane().add("Center", c);
        SimpleUniverse simpleU = new SimpleUniverse(c);
        BranchGroup scene = new BranchGroup();
        simpleU.getViewingPlatform().setNominalViewingTransform();
        scene.compile();
        simpleU.addBranchGraph(scene);
       public static void main(String[] args)
         Test2d mainApp = new Test2d();
         mainApp.setSize(800,600);
         mainApp.show();
    }Visual_Canvas3D.class:
    import java.awt.*;
    import javax.media.j3d.*;
    public class Visual_Canvas3D
    extends Canvas3D
      public Visual_Canvas3D(GraphicsConfiguration gc)
        super(gc);
      public void postRender()
          J3DGraphics2D g = getGraphics2D();
          g.setColor(Color.red);
          g.drawString("red",20,320);
          g.setColor(Color.green);
          g.drawString("green",20,340);
          g.setColor(Color.orange);
          g.drawString("orange",20,360);
          g.setColor(Color.yellow);
          g.drawString("yellow",20,100);
          g.flush(false);
    }Where could be the problem?

  • How to embed an image in swf at run time?

    Hi all,
    I have created an Image component in flash which is having a "imageSource" paramter, where in a user can provide the path of his/her image(both from web or from  harddisk). I want that image to be compiled with the swf. how can i do that?......any help will be greatly appreciated
    Thanks,
    Roopesh

    Hi kglad,
    Thanks alot for your quick reply.
    well I have created such a custome component, which user can drag on stage and configure accordingly. If a user provides the path of a image which is on server, things works fine as when i deploy my swf to server it fetches the image properly but if a user provides the path of a image which is present locally on hardisk, image is not loaded when the swf is deployed to server as the path provided is local . So i am searching for a solution for resolving this path conflict issue in desgin and deployment phase. one probable solution is, if the images gets embedded with swf but embedding is not possible at run time. Do you have any other solution for this?

  • How to superimpose still images onto video?

    Hi there,
    I'm an absolute beginner with iMovie (and video editing in general), so please forgive my ignorance!
    OK, my question is this: Is it possible to superimpose still images on top of video in iMovie, and if so how? I'm using iMovie because it has a reputation for ease of use, and yet I can't figure out how to do this... Basically, all I want to do is take a single piece of video about 5 minutes long and periodically fade in and fade out some still images on top of the action. Am I being too ambitious here?! Should I just give up on the idea...?!
    Any help or advice would be very gratefully received!
    Thanks.

    Just in case anyone else is interested in doing something similar - I found two (commercial) solutions to this problem:
    Gee Three software's 'Slick 4 - Hollywood edition' plug-ins package includes 'Picture-in-Picture' - $50 (also includes three other great effects): http://www.geethree.com/slick/V_04.html
    cf/x's 'Picture in Clip (Static)' does exactly the same, but only costs a bargain $1.50 - available here: http://www.imovieplugins.com/plugs/pictinclipstat.html
    Cheers!

  • How to insert an image onto a blank canvas doc?

    i am trying to create a blank canvas (700 width and 400 length) and then insert a photo onto it.  I am trying to make slides for a slideshow on my website's home page.
    PLEASE help.  i am new to photoshop and i have been searching for an answer.  I have a MAC

    This forum is intended to specifically support the Photoshop Getting Started experience, and in the future you'll likely get a faster response in the Photoshop forum. That said, here's what you want to do:
    Open Photoshop
    Select File, New
    Enter the size you want, you may need to change the size drop down to pixels
    Clock OK to create the blank canvas
    Select File, Place, this will let you select the image to insert
    I'll just add that if you want to create a web page slideshow, then you probably want to use Photoshop to edit or resize the images, and then Dreamweaver to actually build the web pager slideshow.
    --- Ben

  • How to import numerous images onto seprate consecutive frames?

    Hello. I was wondering if anyone knows if it is possible to
    import a whole bunch of images into flash but on consecutive
    frames. I have almost 3000 images that I need to be placed onto
    3000 frames.
    Thanks!

    If the images are named with consecutive numbers, then Flash
    will do exactly what you're asking. point to one file in the Import
    dialogue and Flash will identify the sequence and suggest you
    import them all.
    Good luck!

Maybe you are looking for

  • How to install Final Cut Pro on 2 computers with a multiple user license

    Our church purchased a multiple user copy of Final Cut Pro, and the music minister who bought it downloaded it onto his computer.  I need to get a copy onto my computer - but he doesn't know what I need to do to get a copy onto mine.  Do I have to ha

  • IOS 8.1, Airplay on iPad Mini and Apple TV

    Just to add to all the 8.1 issues on my iPad, has anyone tried using Airplay to screen share to Apple TV?  It doesn't works at all.  Its completely jumpy, it stalls and you simply can't use it.  It worked fine on IOS 7.x with no problems. Shut the iP

  • 2.1 EA 1: ORA-00923: FROM keyword not found where expected

    Hi, there is a simple table which results in this error when opening the data tab. All other tabs are ok. In 1.5 the table can be opened with the data tab. Columns: ID     NUMBER     No          1 PARENT_ID     NUMBER     Yes          2 NODE_NAME    

  • Hlep me please

    I Have a problem. I already paid for lucky package from Sumoners war game is $49.99  But I didn't get it yet. I would like to get my money back. Thank you every much.

  • Pages 8 launches but won't open files

    I've purchased the family pack iWorks 8 and installed it on 3 of my macs. Two work flawlessly but my older G4 desktop is a problem. Numbers and Keynote work so far, but Pages doesn't. When I launch the program, it won't open a new file or any existin