Making certain parts of an image transparent laying it on top of another

I am currently doing an MSc project, where I am simulating the behaviour of ants in Java, however I have hit a stumbling block. Currently, I have an AntTerrain class that contains a paintComponent method. Every time this is called it draws a BufferedImage of the terrain which consists of all the obstacles and food, over which the ants are drawn by iterating through a 2D array. I have been trying to implement pheromones into the simulation, and although I am able to do it I want to have the functionality to be able view or not view them. Initially I had two Buffered images, one containing all the terrain information and the pheromones, and one not containing the pheromones. This became rather costly as the simulation progressed and more pheromones were laid, so recently I have been trying to create a buffered image of just the pheromones which I can overlay onto the terrain as and when the user wants to.
This has been causing me immense problems. I have had limited success with using the alpha channels of the terrain image, by making it almost completely transparent, then drawing it on top of the terrain image, by setting the compositing to SRC_OVER, however, this muddys the terrain image below.
I have been looking up various books and documentation on line to try and work out how to do it in a more elegant fashion without success. Peter has come up with the idea of using either Regions of Interest, Bitmasking or a combination of both. Neither of these techniques have been particularly well explained in the documentation I have found and I am more confused than when I started. Any help you could give me in this matter would be greatly appreciated.

If the pheromones can be drawn independent of the array of ants then I would use a single BufferedImage and make a new one for each user change of pheromone visibility. If this is to unwieldy of if the pheromones require the ant array then I would try an OverlayLayout with the BufferedImage of obstacles/food/etc on the bottom and the pheromones on top. The ants could go on either one; maybe they would look better drawn above the pheromones on the top layer (guessing...). If you want to draw the pheromones with an AlphaComposite and they would look okay drawn above the ants you could draw the ants below and the pheromones above. This would be easy and fast.
Here's an example of the OverlayLayout option:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ToggleTest
    public static void main(String[] args)
        JPanel panel = new JPanel();
        OverlayLayout overlay = new OverlayLayout(panel);
        panel.setLayout(overlay);
        panel.add(new Top());
        panel.add(new Bottom());
        JFrame f = new JFrame("click me");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(panel);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class Top extends JPanel
    boolean showPheromones;
    public Top()
        showPheromones = false;
        setOpaque(false);
        addMouseListener(toggler);
    protected void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        if(showPheromones)
            int w = getWidth();
            int h = getHeight();
            AlphaComposite ac =
                AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25f);
            g2.setComposite(ac);
            g2.setPaint(Color.red);
            g2.fill(new Ellipse2D.Double(w*2/5, h/3, w/3, h/3));
    private MouseListener toggler = new MouseAdapter()
        public void mousePressed(MouseEvent e)
            showPheromones = !showPheromones;
            repaint();
class Bottom extends JPanel
    BufferedImage image;
    public Bottom()
        addComponentListener(resizer);
    protected void paintComponent(Graphics g)
        if(image == null)
            makeImage();
        g.drawImage(image, 0, 0, this);
    private BufferedImage makeImage()
        int w = getWidth();
        int h = getHeight();
        image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setBackground(UIManager.getColor("Panel.background"));
        g2.clearRect(0, 0, w, h);
        g2.setPaint(Color.red);
        g2.draw(new Ellipse2D.Double(w/2, h/5, w/9, h/3));
        g2.setPaint(Color.green.darker());
        g2.draw(new Ellipse2D.Double(25, 16, w/6, h/2));
        g2.setPaint(Color.blue);
        g2.draw(new Ellipse2D.Double(w/4, h*5/6, 125, 25));
        g2.setPaint(Color.blue);
        g2.draw(new Ellipse2D.Double(w*5/9, h/2, 55, 60));
        g2.dispose();
        return image;
    private ComponentListener resizer = new ComponentAdapter()
        public void componentResized(ComponentEvent e)
            image = null;
            repaint();
}

Similar Messages

  • I'm unable to use a brush mask over certain parts of an image...

    I am brand new to Lightroom, coming over from Photoshop and it is immensely different, still trying to figure the workflow out. There are times that I want to add a brush mask over parts of an image, but for some reason, whenever I try to edit a particular region, the brush disappears and turns back into the selection arrow. Can anyone explain to me why this happens?
    Thanks!

    GTPhilippa wrote:
    ...When I am looking at emails, and some junk email, how do I unsubscribe?...
    Indeed, if it's a phishing attempt as BobTheFisherman points out, an active "unsubscribe" link might well be notification to the Spammer that your email address is live and can be sold to others for further use. You don't want to tell the Spammer that.

  • Making a portion of an image transparent

    Hello, I have an image with 3 images on a transparent background, one of the images is square, the other two rectangle, I need to crop the two rectangular ones to match the square one.  How?

    You can use the rectangle selection tool, In the top tool bar you can set the size/ratio of the rectangle. Since you want the to be square, you can use the ratio of 1:1 to lock the rectangle selection tool to a square. Or you can hold down the shift key while dragging the rectangle selection tool onto the document.
    Once this is done, you have two options you can create a mask by clicking on the icon at the bottom of the layers panel that looks like a circle inside of a square. Or you can just hit the delete key.
    The difference between the two comes down to future proofing your edits. A mask is non-destructible allowing you to undo or change it any time in the future. whereas the delete key permanently removes the pixels which makes it a destructive process.
    In the end it is up to you, for example if you know you have a copy of the same image in another file, then it doesn't really matter. But if it is a precious keepsake, then preserving is a must.
    Keep in mind not all file formats are equal - jpg does not support, layers, transparency, vector objects, live type, etc. But is an excellent at compressing files for sharing.
    Png does not support layers, vectors, or live type but does support transparency.
    Tiff and psd support all or most of the advanced features of photoshop.
    So tiff and psd are excellent choices for keeping a master editable file, png is great for transparent images for the web and some archiving, and jpg is for sharing.

  • Setting a specific color on a image transparent

    I want to take a image that im drawing in the paint(graphics g) method, and set a certain color on that image transparent. so it blends with the background image properly.
    any ideas would be appreciated.

    Bird.gif
    import java.awt.*;
    import java.awt.image.*;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class TransparencyTest extends JPanel
        BufferedImage image;
        public TransparencyTest(BufferedImage orig)
            Color toErase = new Color(248, 248, 248, 255);
            image = eraseColor(convertImage(orig), toErase);
            setBackground(Color.pink);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            int x = (w - image.getWidth())/2;
            int y = (h - image.getHeight())/2;
            g.drawImage(image, x, y, this);
        private BufferedImage convertImage(BufferedImage in)
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            BufferedImage out = gc.createCompatibleImage(in.getWidth(), in.getHeight(),
                                                         Transparency.TRANSLUCENT);
            Graphics2D g2 = out.createGraphics();
            g2.drawImage(in, 0, 0, this);
            g2.dispose();
            return out;
        private BufferedImage eraseColor(BufferedImage source, Color color)
            int w = source.getWidth();
            int h = source.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            g2.setPaint(new Color(0,0,0,0));
            g2.fillRect(0,0,w,h);
            int target = color.getRGB();
            for(int j = 0; j < w*h; j++)
                int x = j % w;
                int y = j / w;
                if(source.getRGB(x, y) == target)
                    source.setRGB(x, y, 0);
            g2.drawImage(source, 0, 0, this);
            g2.dispose();
            return out;
        public static void main(String[] args) throws IOException
            String path = "images/Bird.gif";
            BufferedImage bi = ImageIO.read(TransparencyTest.class.getResource(path));
            TransparencyTest test = new TransparencyTest(bi);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • I need to replace a color on my image with a specific color from another part of the image.  How?!

    I have spent over 2 hours trying to figure out how to replace a color on one part of my image with a specific color shown on another part of the image.  So far I have been able to go to "Replace Color" on my Adobe Photoshop version, but it seems that I can only change the hue and brightness of the color that it currently is.  I need to use a specific color so this does not help me.  Does anyone know how to complete the task I am referring to?
    Also, please keep in mind that I am using Adobe Photoshop 6.0, not a fancy cs version or anything.  So it's pretty old school...
    Any help/feedback is greatly appreciated!  Thank you.

    Hi brookehelene,
    You might consider making a selection the object and using a color fill layer set to the color blend mode instead of replace color.
    I used the same picture as kendallplant did and changed the color on the same flower by sampling the pink color from the flower to the right)
    (click on the screenshots below for larger views)
    1. Select>Color Range
       (i used color range because the dialog is somewhat similar to the replace color dialog, except one is making a selection instead of replacing a color)
       (there are many other ways to make the selection such as the magic wand, so if your more familar with the other selection tools you can use those instead to make your selection)
    2. Use the eyedroppers and fuzziness slider in the color range dialog to make the selection of the object.
       (in the screenshot below the white areas are selected and black areas are not)
       (your selection probably won't be perfect, but you can paint on the layer mask to refine the selection)
    3. After you press the okay in the color range dialog you'll see the selection (marching ants)
       At the bottom of the layers palette press the Create New Fill or Adjustment Layer icon
       to reveal a list and choose Solid Color.
       Then use the eyedropper to sample a color from your image and press ok.
       Change the Blend mode for the color fill layer to Color (top of the layers palette)
    4. As you can see a lot has been selected besides the flower.
        To refine the areas of color, paint on the layer mask with the paintbrush tool.
        Use white to add the color or black to subtract the color
        You can press the D key on the keyboard to get the default colors (black and white) in the toolbox
        and press the X key to switch between the two when painting on the layer mask.
    Even though the above takes longer you can easily change the color or modify the areas that you want to change the color on.
    To change the color you can double click on the color fill icon in the layers panel.
    You can also use other layer blend modes besides color such as hue, so you might try some of the others and see what they do.

  • Help Merging And Deleting Part Of Two Images

    Hi All,
    im having trouble with cutting part of a image out and putting it ontop of another to form one image i used to use gimp before but ive started using photoshop after building my own PC
    these are the two images i want merging:
    https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTfNmYfTBCmaN3zTV3_qrrQF48rJPd3QUrW5E t3AiDe-x8RD5rX
    https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRYeijxO3WUIMajNSW_RMvb5u0ksNGrgHGMCG 5Pc7ZqY25ABnNtKg
    its for a tattoo design no doubt most wont like it but hey ho, i want the woman in the middle of the second picture placing inbetween the two faces one the first image (if you understand what i mean) im not to bothered about all the writing as i will be having a saying underneath it all
    any suggestions on the best way to go about this need the image to look as clear as possible and 6" high and 10 wide
    thanks

    Hi EvilJester2013,
    It sounds like you want to composite two images together, this very helpful tutorial can help you with that: http://www.smashingmagazine.com/2010/12/16/compositing-in-adobe-photoshop-time-saving-tips /

  • After Preflighting a PDF, using Convert to CMYK, Flatten Transparency and Prepress Profile Convert to CMYK only the resultant PDF has a grubby halo along the edge of some white type sitting on an image. The type is part of the image.

    I am using a 27" iMac 3.2 GHz Intel Core 5, 8 GB Memory, running Yosemite 10.10.1. 
    The version of Acrobat that I am using is: Acrobat XI Version 11.0.10
    After Preflighting a PDF, using Convert to CMYK, Flatten Transparency (high resolution) and Prepress Profile "Convert to CMYK only" the resultant PDF has a grubby halo along the edge of some white type sitting on an image. The type is part of the image which is 300 dpi.
    It is like the image isn't really 300 dpi but has been artificially boosted to that to avoid being tagged by Preflighting, but when Preflighting the file it knows the original resolution.
    I have screen grabs which illustrate the problem perfectly but do not know how to post them, if indeed they can be.
    Any help or comments gratefully received.

    Without the files and possibly screen prints, it is virtually impossible to assist you.
              - Dov

  • How do I remove white jagged edges after making image transparent?

    How do I remove white jagged edges after making image transparent?  Is there a feature to help out with this?

    It's a file format limitation. GIF supports 1 bit of transparency.  That is 2^1 (which equals 2 total) levels of transparency.  This equates to either NO transparency at all, or specifying 1 single color of the 256 total possible values to being fully transparent.
    This will leave a very ugly fringe around the edge no matter what; it will only not be visible in color that match or are close to the fringe color; and then, that's a perception issue.
    Try creating an alpha channel and saving the image as a PNG.  That supports 8 bits of transparency, which equals 2^8 or 256 total different levels of transparency.  This will let your image have very smooth edges with no jagged transitions.

  • Make image transparent outside of selected area.

    I have some code that paints a BufferedImage to screen with ability to draw a single rectangle in the image at any location.
    I want the part of the image that is not in the rectangle to have some transparency.
    How can I accomplish this?
    my Current code is:
        public void paint(Graphics g) {
             Graphics2D g2 = (Graphics2D) g;
             g2.clearRect(0, 0, this.getWidth(), this.getHeight());
             g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                   RenderingHints.VALUE_ANTIALIAS_ON);
             if (snapshot != null) {
                g2.drawImage(snapshot, 0, 0, this);
             g2.setStroke(dashed);
             g2.setColor(Color.WHITE);
             rectX = start.getX();
             rectY = start.getY();
             rectWidth = end.getX() - start.getX();
             rectHeight = end.getY() - start.getY();
             if (rectWidth < 0) {
                rectX += rectWidth;
                rectWidth *= -1;
             if (rectHeight < 0) {
                rectY += rectHeight;
                rectHeight *= -1;
             g2.draw(new Rectangle2D.Double(rectX, rectY, rectWidth, rectHeight));
          }start and end are of type Point.
    snapshot is a BufferedImage

    You can draw portions of an image with the other graphics#drawImage methods. Most notably this one
    drawImage(Image img, int dx1, int dy1, int dx2, int dy2,
                         int sx1, int sy1, int sx2, int sy2,
                         ImageObserver observer)So you can draw the four regions of the image not included in the rectangle with a translucent AlphaComposite using the above method (4 times). And then you can use it one more time to draw the rectangular region with an opaque AlphaComposite.
    Also, if start is of type Point then your rectangular coordinates are integers. This implies you can use g2.drawRect instead of creating a new Rectangle2D.Double object each paint call. It's just a side not though. It dosen't really matter much.
    Edited by: Maxideon on Apr 6, 2009 11:25 PM
    Too late, seems you found a way.
    Edited by: Maxideon on Apr 6, 2009 11:26 PM
    Ah, foolish me. I was thinking of the hard way. You can just draw the whole image at a certain transparency. And then draw the rectangular region as opaque.

  • How do you cut out the part of an image in a photo?

    How do you cut out a part of an image on a photo that you have added to Pages. For example, if I have added a picture of a giraffe to Pages how would I cut out the giraffe from the image and get rid of the rest of the image

    You can use the instant alpha tool to make the background transparent.
    FYI: Pages is part of iWork, not iLife.

  • How to make some part of front panel transparent?

    There is a property node to make a front panel completly transparent...but is there anything that only makes some part of the vi transparent like if I define a decorative block in the vi which takes 1 quardant of front panel and I have a control to make it transparent during runtime...
    And moreover the frontpanel transparent property makes the whole window transparent, is there any way to retain toolbar of window like stop, run button when front panel is transparent??

    Hi,
    Have a look at this VI (attached). To make it work you need to create an image mask as a .png (open paint, colour in the areas that you want to become invisible and save it as a .png). The VI diffentiates between white areas and black areas of the mask you create, the black areas will become transparent and the white areas will remain the same- this will be implemented on your front panel. I've included an example of a possible paint image in "mask2.png".
    You may also want to play around with the resolution of the mask created in paint, this will effect how the program works (I advise you use a lower resolution than your display- I used 500x300)
    NT: If the front panel controls disappear, go into the block diagram window and attach a false constant instead of a control. Let me know if this works
    Cheers, Tom
    Attachments:
    custom window.zip ‏107 KB

  • How to make white part of gif file transparent?

    I have an icon and I would like to change the color of its white part by changing the background color. If I could set the white part to be transparent I could do this. Any ideas how this can be done?

    If you know Adobe Photoshop or Macromedia Fireworks or somethin like that, you can do it easily just by deleting the parts of the image which you don't want. By default it will make those parts transparent. Remember this can only be possible in GIF format.
    For a new image just open a new file in PhotoShop, there you will get options for the color of background, set it to transparent and start drwing in the area. The parts on which you won't make any drawing will be transparent.
    Note: Don't try to fill transparent areas with white, as it will loose its transparency.
    [email protected]

  • Web Part Title Bar image

    I can't believe no one has asked about this, but my search
    came up empty.
    How does one change the tiny (16x16) image on the Web Part
    Title Bar? I see where to set the title, but not the image.

    .oO(Michael Palmer Photo)
    >
    quote:
    Originally posted by:
    Newsgroup User
    > .oO
    >
    > But even without knowing the proper name finding it
    should have been
    > quite easy. Just throw something like title bar icon or
    address bar icon
    > at any search engine you like ...
    >
    > Micha
    >
    >
    > Actually I did and did get anything I understood and
    certainly not in terms of
    >what Dreamweaver can do for me automatically. I found out
    from an MS page that
    >it was in fact called a "Web Part Title Bar image", but
    even knowing that
    >didn't get me any further.
    Strange term ... must be MS-speak. ;)
    > Dreamweaver has a place for the title, but nowhere does
    it mention the image
    >that is next to it on web sites. On this forum the terms
    "title image" came
    >up with nothing.
    Most people refer to it as the "address bar icon", which
    returns a lot
    of useful results on Google.
    > I apologize if I asked a question that had been answered
    before, but sometimes
    >knowing how to phrase the question to find the answers
    can be tricky.
    No reason to apologize. I know that sometimes finding the
    right words
    can be difficult if you don't actually know what to search
    for. In this
    case it just seemed quite easy and straightforward to me ...
    but anyway.
    Micha

  • Illustrator is chopping off a part of my image when exporting

    Okay so I have an image I created on a canvas that is larger than the image. When I export the image as a png, I get the image without any of the white space there was surrounding in illustrator and a very small part of the image is actually chopped off ... Is there anyway I can get illustrator to export the entire canvas or at least not chop off a part of the image if it is going to auto-crop?
    Thanks

    Add a rectangle the size of your artboard, or at least larger than the rest of the artwork, fill it with white but no stroke and send it behind the rest of the artwork. Save and export. The result should be the size of the white background.
    Not a good solution if you want the background transparent. In that case, put a stroke around the rectangle but no fill. Then, upon export, open it in Photoshop and crop out the stroke around the outside. If you are using some other program to manipulate it, you should be able to crop out the stroke there as well.

  • Finding center in black part of greyscale image

    Hi all,
    Basically what I want to do is find the center of a black part of a gray scale image. I'm having a bit of a problem using built-in LV functions, because the part of the image is somewhat spherical but not completely.
    What I'm doing is imaging drops (I attached an example one to the post), and the drops show up as mostly black (except for the center) due to a bright blacklight. I am currently calculating the size of the drop by converting the image to an array of 1/0s where the 1s represent the region of the drop (and sometimes the edge of the image, depending on the exposure), I then scan each column of the array to calculate the diameter of the drop at that column by subtracting the first and last 1 that I find, then summing over the entirety of the drop and converting that into voxels then microliters. Phew.
    So now, what I'm trying to do, is find the center of the drop in x and y. I was thinking I'd be able to use some sort of average of the first/last numbers of each column (and then of each row) but everything I tried didn't seem to make sense and I can't figure out if my method is bad, or my implementation in LV was bad. Any ideas on what I could do here? I attached the code I'm using currently to take the pictures and calculate the drop size, although it may be easier to just start from scratch using the attached image.
    I appreciate any advice! Hopefully I explained that well enough, but I know it's a bit confusing.
    Laura
    Attachments:
    Manta camera - FINAL - JMcH with our camera with file save.vi ‏63 KB
    water drop, disp 3, exp 300.png ‏420 KB

    Hi (again) Burrito,
    I started out trying to use the Vision functions, but since my image isn't necessarily a circle nor does it have any straight edges I was having a hard time trying to figure out the best way to use the functions. Someone else I discussed the code with though also recommended making more use of the vision functions if possible - I'll look more into the particle analysis VI. Thanks for the advice!
    Laura

Maybe you are looking for