Converting transparent GIF and PNG to JPEG

Hi,
I have been reading in various sample gifs and png files and converting them to jpeg via javax.imageio.
This works fine if there is no transparency colour defined in the png or gif file. But if it has a transparency colour, the resulting jpeg is messed up. Now, it appears the reason is because jpeg has no transparencies. So, my question is, how does one get rid of the transparency (assuming I want to convert it to 'white')?
For the record, I am calling
BufferedImage image= reader.read(0);Where reader is an ImageReader and I then convert "image" to jpeg.

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class LoseTransparency {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://java.sun.com/docs/books/tutorial/figures/uiswing/components/ButtonDemoFiles.gif");
        BufferedImage bi1 = ImageIO.read(url);
        int w = bi1.getWidth();
        int h = bi1.getHeight();
        BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi2.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,w,h);
        g.drawRenderedImage(bi1, null);
        g.dispose();
        JPanel p = new JPanel(new GridLayout(2,1));
        p.setBackground(Color.YELLOW);
        p.add(new JLabel(new ImageIcon(bi1)));
        p.add(new JLabel(new ImageIcon(bi2)));
        final JFrame f = new JFrame("LoseTransparency");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(p);
        f.pack();
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                f.setLocationRelativeTo(null);
                f.setVisible(true);
}

Similar Messages

  • Logo image distored when creating a transparent gif and png

    Hi all,
    Creating a logo for my department with little or no graphic design exp.  I'm experiencing issues when saving the file as a transparent GIF or PNG.  The GIF removes the 300 dpi setting that the print shop needs to turn this into a poster and the PNG is creating some jagged edges around my logo.  The image is 2000 pixels and about 7 in. by 7 in.
    Any help would be appreciated.  I can email the PSD to anyone if they can help.  Here is the PNG:
    And here is the GIF:

    There was no abuse, just an observation. Would an abusive person be trying to help you? Is there a crime in suggesting that one prepare themselves with more experience before taking on a project like this?
    Aside from low resolution, there were a few other signs that you might be in over your head with a logo design. Logos are typically created in a vector program (not Photoshop).
    I cannot imagine a reputable print shop asking you for a PNG or GIF file when there are so many better formats.

  • Why can't PS CC read .gif and .png files anymore?

    Everytime I've tried to load my files into my PS like usual (simply dragging the photo to the dock) I get this error message "Could not complete your request because Photoshop does not recognize this type of file." for both .gif files and .png. It's quite frustrating because a lot of my files on my computer are in .png format and I have previous .gifs I've made that I'd like to edit and can't. I have a Mac OSX and I've tried rewriting the file names but I still get the same message and I've tried making a new document in PS and pasting the photo but I only end up with the image below. I'm not sure what else to do anymore. It's quite frustrating. Any suggestions?

    All right. That could also explain why my updates aren't working. (I'll try the same for my illustrator because those updates aren't working also.)

  • What is it with transparent GIFs and Black????

    I'm trying to use transparent gifs in a little game! ;o) as an introduction to graphical java!
    Problem is when I load the images using the toolkit and then setting them as say the Icon for a panel, they are surrounded by Black?! In addition when I try to display them using an BufferedImage they are also surrounded by black?!!!
    Ive been tearing my hair out trying to understand why - and have sucessfully failed :D
    Can anyone help?!
    Pleeeeeeeeeeeeease!
    Thanks

    Can't seem to get that working?!
    If I want to put that image as the icon for the whole window how would I do that?
    ImageIcon tempIcon = new ImageIcon(Toolkit.getDefaultToolkit().getImage("images/icon.gif"));
    f.setIconImage(tempIcon.getImage());where f is a JPanel.
    The above code does not work?! I just get the black surround to the gif as before!>?

  • Does Aperture 2 have a way of converting raw images to png or jpeg.

    Does Aperture 2 have a way of converting raw images to png or jpeg

    That's why we're here
    In regards to your original question converting RAW images to JPGs is one of Apertures reason for being. As Terrence stated once the image is in Aperture ad you've made chatterer adjustments you want to it you then can export the image in a wide array of formats, sizes and qualities depending on what you will be doing with the exported image.
    The Aperture user manual is a good place to start, it's well written and has a lot of good info in it.
    Good luck
    regads

  • GIF and PNG aliased when placed over bg image

    When I use Save for Web/Devices in both Illustrator and
    Photoshop, the saved files look normal and display fine in browser
    and other image viewing programs. However, when I attempt to turn
    them into a navigation bar or rollover, they become severely
    aliased when placed into a table (which is the layout). I tried
    placing them just by themselves in a XHTML document and they do not
    alias, even when the body has a bg image (I am using CSS and have
    encounted no other problems). This is pretty frustrating and would
    appreciated any help.

    > When I use Save for Web/Devices in both Illustrator and
    Photoshop, the
    > saved
    > files look normal and display fine in browser and other
    image viewing
    > programs.
    > However, when I attempt to turn them into a navigation
    bar or rollover,
    > they
    > become severely aliased when placed into a table (which
    is the layout). I
    > tried
    > placing them just by themselves in a XHTML document and
    they do not alias,
    > even
    > when the body has a bg image (I am using CSS and have
    encounted no other
    > problems). This is pretty frustrating and would
    appreciated any help.
    Have a link for us?
    My guess is you either:
    a) are using gif or 8-bit png transparency, and then placing
    it on a
    background that is of a different color than the one in the
    original file
    or
    b) the image is scaled and you're seeing pixelization rather
    than aliasing.
    -Darrel

  • Stop gif (and png I suppose) animations

    How do I stop image animations in Safari?
    I tried plugins like SafariStand and Pith Helmet, nothing seems to work.
    I'm using Safari 3.2.1 on Mac OS X 10.5.6.

    It could be related to the fact that Apple removed support for viewing animated GIF images in Mail, which also relies on WebKit to display HTML mail, in addition to display in Safari. But in my experience, it definitely works in 10.4.11, so it's probably just a Leopard-specific problem at this point.
    Mulder

  • How to make a GIF and PNG save with the same colors.

    I seem to get a slight shift in colors when saving a PNG. I save as png24 in photoshop then save as png6 in fireworks (to get degradeable alpha transparency), eg. please see logo for molecule clothing compared to background (only shows on some monitors).
    Thanks for any pointers.

    You don't note where you see the problems (which browsers, which situations) so I'm guessing it involves PNG gamma.
    http://morris-photographics.com/photoshop/articles/png-gamma.html

  • Resize BufferedImage of a Transparent GIF PNG JPG

    i must be losing my mind.
    i use this same code in another program and it works fine.
    first the images were transparent PNGs but then i changed
    them to non-transparent GIFs and then JPGs.
    no errors are thrown - but the images are being drawn at
    their original size.
    ive tried 3 different resizing methods and none work.
    why doesnt this code work:
    BufferedImage wp = ImageIO.read(new File("" + dir + "wp.gif"));
    resize(wp);
    public void resize(BufferedImage bi){
      AffineTransform tx = new AffineTransform();
         double xsc = ( sx ) / ( (double) bi.getWidth() );
         double ysc = ( sy ) / ( (double) bi.getHeight() );
        tx.scale(xsc, ysc);
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
        bi = op.filter(bi, null);
    }

    public void resize(BufferedImage bi){
        bi = op.filter(bi, null);
    }The variable in your "resize" method is a local variable. Reassigning a value to it does not change anything outside the method. You will have to return the new value of "bi" or reassign the instance variable to the filtered image:
        wp = op.filter(bi, null);
    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.*;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ImageSizing
        BufferedImage orig;
        public ImageSizing(BufferedImage image)
            orig = image;
        private BufferedImage scale(BufferedImage bi)
            AffineTransform tx = new AffineTransform();
            tx.scale(0.80, 0.80);
            AffineTransformOp op = new AffineTransformOp(tx,
                                             AffineTransformOp.TYPE_BICUBIC);
            return op.filter(bi, null);
        private JPanel getPanel()
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.add(new JLabel(new ImageIcon(orig), JLabel.CENTER));
            panel.add(new JLabel(new ImageIcon(scale(orig)), JLabel.CENTER));
            return panel;
        public static void main(String[] args) throws IOException
            String path = "images/bclynx.jpg";
            BufferedImage bi = ImageIO.read(ImageSizing.class.getResource(path));
            ImageSizing test = new ImageSizing(bi);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getPanel());
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Using a transparent GIF

    After an hour of frustration I'm turing to this group feeling totally inept.  I'm trying to insert a transparent image into an existing photo using Photoshop Elements.  I have an original photo I am trying to use as a background (I have tried using this photo in a jpg and a psd format).  I have a second photo I have cut a logo out of and saved to a file with a transparent background (have tried psd, gif, and png formats).  The new logo file has a the checkered background and seems to be transparent.  I open the photo I want to be the background and drag the logo on top of it.  A new layer is created but the transparent logo is surrounded by a gray box.  I cannot see the background image through the areas that should be transparent.  In other words, all the areas of the logo image that has a checkered background turns gray when I copy it on top of the background photo.  What am I doing wrong?  Thanks for your help.

    Select the move tool and drag the corner handles of the bounding box to scale the size.
      Make sure show bounding box is checked in the options bar.

  • Does Keynote 6.0 no longer support Transparent GIF or Quicktime Animations?

    So, I have some sample files here:
    Bees and Honey Clear Quicktime
    http://www.presentermedia.com/blog/wp-content/uploads/2013/10/beehive_bees_400_c lr_12723.mov
    Bees and Honey Clear GIF
    http://www.presentermedia.com/blog/wp-content/uploads/2013/10/beehive_bees_150_c lr_12723.gif
    Bees and Honey Green Background Quicktime
    http://www.presentermedia.com/blog/wp-content/uploads/2013/10/beehive_bees_12723 _grn.mov
    Bees and Honey Blue Background GIF
    http://www.presentermedia.com/blog/wp-content/uploads/2013/10/beehive_bees_12723 _blue.gif
    Moving on...
    At my company, we create images, animations, video backgrounds and templates for PowerPoint and Keynote etc.  Keynote '09 (iwork '09) and PowerPoint 2008 and 2011 on the Mac, all work.  Now we're hearing that the transparent backgrounds are no longer being recognized (black background instead of clear).  Is anyone able to check this for me and let me know if there is a workaround or something? I can't find any documentation on how Quicktime changed with Maverick or Keynote 6, so need to do real world testing I'm only running '09 on my Mac and won't have Keynote 6 for another 2 weeks or so.
    Please let me know, I may be able to throw in a free subscription to our website for someone who can help me with this.

    Hello all... I'm maybe a little late to the party here, but I've had the same trouble for a while with both animated Transparent gifs and quicktime movies with an alpha channel matte.
    This morning I spent half an hour tinkering with the export options from quicktime player pro on my old laptop (I used QT 7.6.6 on OSX 10.8.5) and managed to make a "transparent" quicktime movie which plays in the new version of Keynote.
    If you have access to the old version of quicktime player pro, you can open your transparent, previously playable file (.gif or .movie) and use the ProRes compressor, using the "4444" option in the list of compressors. Make sure the colours are set to "millions+" to retain the matte and you shoud be OK.
    It works a charm... you have to re-import it, simply replacing the original file in the finder seemingly doesn't work, but you can use this method to generate a working version and take 30 seconds to re-import it into the keynote.
    Yes, the files are much larger than gifs. Yes it's a lot of messing around if you're not familiar with movies. But in principle it worked for me and sorted out a whole heap of my problems.
    Just for note, I've not tried exporting it to Powerpoint as I've no need to do so, or way to test it, but I guess that is a different matter.
    Hope that makes sense!

  • Is there a JPEG encoder for j2me, PNG,GIF and BMP encoders are also wanted.

    As is known that, image encoders are not currently available in MIDP. I have tried to port a j2se JPEG encoder to J2ME, but it cost me 32M memory when generating a 800x600 image. Could anyone help me. Thanks

    well, of course ... what did you expect?Hum, I want to do some processing on my pictures, such as rotation, and then save it or send to my friends via MMS. but it's not easy to save the processed pixels to image file, such as JPEG, GIF or PNG.

  • I need to convert hundreds of TRANSPARENT PDFs into PNG or TIFF

    I need to convert hundreds of TRANSPARENT PDFs into PNG or TIFF. 
    That's not possible with Acrobat. It’s possible to convert hundreds of PDFs into PNG or TIFF using batch processing. But transparency is LOST! 
    Photoshop is the only software I know of which is able to keep transparency when converting from PDF to PNG.
    But now I have problems to get batch processing running.
    I made an Action with “Open file”, “Save as PSD” and “Export to PNG”. 
    Using this Action in batch-process-files with source as a folder with many PDFs and target as a different folder results in many opened PDFs within Photoshop. Nothing else happens:-(. 
    Any ideas? 
    Thanks
    Norbert

    Great:)
    It worked at once.
    Thank you so much for this link.
    Best regards
    Norbert

  • I'm making an intentionally terrible montage. How can I convert a gif to a transparent .mov?

    I want to be able to insert gifs into my final cut videos. They have to loop, and be transparent.
    Is there a program that can convert them into transparent .movs or some other format recognized by Final Cut Pro?

    Quick Time Pro should be able to open the GIF and save as a Quicktime .mov file. Whether the looping will work I don't know and can't test it.myself.
    If you don't have QT Pro, it's a $30 license.
    Russ

  • Why Does Reading A Gif Or Png Containing Transparent/Alpha Pixels Fail?

    I'm trying to read in gif or png with transparent pixels into a BufferedImage so that I can create a font inside of Java. Right now, I'm defaulting to the assumption that the background of the font image is white. However, I want to make it so that the font background is whatever pixels happen to be transparent. The images I'm reading in have only two colors: black and white. I set all the white pixels to transparent when creating the images in hopes that I could do a check for all pixels with Alpha < 255. I have tried numerous possible solutions, such as saving the png files with different applications, ImageIO.read, and Toolkit.getDefaultToolkit().createImage, and JAI.The types of the resulting BufferedImages have varied between TYPE_BYTE_BINARY, TYPE_BYTE_INDEXED, and TYPE_CUSTOM. What I want is TYPE_INT_ARGB so I can get the dang alpha pixels.
    1. Is there a way to read in alpha pixels of png or gif (doesn't have to be both) from within the main Java libraries as a BufferedImage with type TYPE_INT_ARGB? If so, how?
    2. Failing that, is there a way to read in alpha pixels of png or gif (doesn't have to be both) by using a decent external library as a BufferedImage with type TYPE_INT_ARGB? If so, how and with which one?
    This has been frustrating the heck out of me, since I thought this was something very simple to do, but I've spent two days poring over the entire Internet for a possible solution.

    package aerobush.ocr.translator;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.image.BufferedImage;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.ImageInputStream;
    import javax.media.jai.JAI;
    import javax.media.jai.PlanarImage;
    import com.sun.imageio.plugins.png.PNGMetadata;
    public class ImageUtils
         static public BufferedImage readPng1(
                   File pngFile ) {
              try {
                   BufferedImage image = ImageIO.read(pngFile);
                   return image;
              catch (Exception e) {}
              return null;
         static public BufferedImage readPng2(
                   File pngFile ) {
              try {
                   BufferedImage image = (BufferedImage) Toolkit.getDefaultToolkit().createImage(
                             pngFile.getAbsolutePath());
                   return image;
              catch (Exception e) {}
              return null;
         static public BufferedImage readPng3(
                   File pngFile ) {
              try {
                   final PlanarImage planar = JAI.create(
                             "FileLoad",
                             pngFile.getAbsolutePath());
                   BufferedImage img = planar.getAsBufferedImage();
                   return img;
              catch (Exception e) {
                   e.printStackTrace();
              return null;
         static public BufferedImage readPng4(
                   File pngFile ) {
              try {
                   ImageInputStream stream = ImageIO.createImageInputStream(new FileInputStream(
                             pngFile));
                   ImageReader r = ImageIO.getImageReadersByFormatName(
                             "png").next();
                   r.setInput(
                             stream,
                             true,
                             false);
                   PNGMetadata metadata = (PNGMetadata) r.getImageMetadata(0);
                   BufferedImage i = r.read(0);
                   if (!i.getColorModel().hasAlpha() && metadata.tRNS_present) {
                        int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8)
                                  | (metadata.tRNS_blue);
                        BufferedImage tmp = new BufferedImage(
                                  i.getWidth(),
                                  i.getHeight(),
                                  BufferedImage.TYPE_INT_ARGB);
                        for (int x = 0; x < i.getWidth(); x++) {
                             for (int y = 0; y < i.getHeight(); y++) {
                                  int rgb = i.getRGB(
                                            x,
                                            y);
                                  rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                                  tmp.setRGB(
                                            x,
                                            y,
                                            rgb);
                        i = tmp;
                   return i;
              catch (IOException e) {}
              return null;
    }Edited by: oldbushie on Sep 13, 2009 2:07 PM
    Edited by: oldbushie on Sep 13, 2009 2:08 PM

Maybe you are looking for

  • My Firefox synced the "wrong way" and I need to recover my bookmarks.

    On Wednesday I opened Firefox on my WORK computer (PC) after a long hiatus and it recommended I refresh Firefox since I hadn't used it in so long. It said it would preserve all my bookmarks, etc. Did so, everything was fine. Yesterday I logged on to

  • How to get the Net value in SD Bex query

    Dear All, We have a  key figure called Net Value in SD query 0SD_C03_.  But in validating data with ERP system to this bex the value is not matching. In this Query we are maintain sales doc category -C and Item category. Because the  Net value is dep

  • Custom attributes added to user objects not visible in OWA address book

    Hi, I am using Exchange 2013 and recently added a new custom attribute in the user object properties using the details template editor to be visible in the GAL  The new attribute is correctly getting displayed in the GAL from outlook clients but not

  • How can purchased music that is missing from iTunesbe restored?

    All music that I have purchased over the last 2 years is missing from iTunes. Also, my iPod nano (6th gen) will charge, but not sync. Any suggestions on how to repair these issues?

  • Loose screen?

    I have a slightly old Macbook (2008/09) that looks like the Macbook pro. Lately I've noticed that the screen is loose and wiggles baack and forth when I move my computer. Is there any way this can be fixed? aditionally, it takes about 4 hours to full