Alpha channel in PNGs

Hi everyone,
I have the following problem:
I'm using ImageIO and a BufferedImage to read a PNG with transparency. The PNG was created with another program by setting the alpha value to 0. Then, I try to localize the pixels with transparency using new Color(img.getRGB()).getAlpha(), but all pixels have the alpha value 255.
Is there another / better way to read the alpha values of PNGs?
Thanks in advance.

To get better help sooner, post a [url http://mindprod.com/jgloss/sscce.html]SSCCE (Short, Self Contained, Compilable and Executable) example that demonstrates the problem. Provide a suitable image for testing on a file sharing site.
db
edit but before that, read the API for the Color constructor you have used, more carefully.
Edited by: Darryl Burke

Similar Messages

  • Cannot save alpha channel as PNG. need help.

    Hi, I am running PS CS5. I am working on my business logo and love the way it has turned out with a texture I added as a new channel (alpha channel). I am using a transparent background on my image, the only compatible way to save is PNG format.(and this is the only way to go with my website restrictions) So when I go to save as a PNG it isnt saving the new channel I have made. Is there any way around this? Any suggestions would be very helpful. I worked all day on this logo only to find that I cant save it the way I like it. frustrating..................
    Linz

    Ok, maybe this will help matters. In the beginning I did a google search on how to get the "distressed" look on my logo, this is the link I found, I did all that he said and did acquire the look I want, now I am having trouble saving as a PNG. When I choose to save as a PNG the alpha channel does not save (when I open the saved PNG file the alpha channel is unchecked). I dont know a whole lot about PS, I am new and dont understand alot of the lingo that alot of you are using, but maybe if you see the steps I took on this link then possibly someone may be able to help me. Thanks
    http://www.promotinggroup.com/design-tips/distressed-effect-photoshop/

  • Enabling alpha channel for PNG file

    I want to include a logo with a transparent background in an iMovie video, but when I import a PNG file with a transparent background, the background turns black. I think this is because the PNG needs to have alpha channel enabled.
    When I attempt to save the file as a new version, the "alpha channel" option is greyed out. How can I save the file with the alpha channel enabled?

    Hi,
    You might want to visit this thread for more info on iMovie's handling of transparency:
    http://discussions.apple.com/thread.jspa?messageID=13123097
    It sounds like iMovie converts the PNG to a JPG internally for some cases (fit, crop, Ken Burns effect).
    regards,
    steve

  • How to render with alpha channel?

    Hello,
    I am trying to render a comp with alpha  channel QT PNG. When i play the clip it's with black BG but if i  imported in AE is with alpha channel. How to render in such way that i  can play in Quicktime without the black BG? Am i missing something?
     Thanks!

    robert_ro wrote:
    Hello,
    I am trying to render a comp with alpha  channel QT PNG. When i play the clip it's with black BG but if i  imported in AE is with alpha channel. How to render in such way that i  can play in Quicktime without the black BG? Am i missing something?
     Thanks!
    You've successfully rendered the alpha channel. Alpha information is not displayed as expected in some players. IN QT Player, your alpha is transparent but the player has no background so it defaults to black. Check the playback operations and settings/prefs for QT Player, there may be a way to tell it to show alpha information.
    bogiesan

  • ImageIO PNG Writing Slow With Alpha Channel

    I'm writing a project that generates images with alpha channels, which I want to save in PNG format. Currently I'm using javax.ImageIO to do this, using statements such as:
    ImageIO.write(image, "png", file);
    I'm using JDK 1.5.0_06, on Windows XP.
    The problem is that writing PNG files is very slow. It can take 9 or 10 seconds to write a 640x512 pixel image, ending up at around 300kb! I have read endless documentation and forum threads today, some of which detail similar problems. This would be an example:
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215304|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6215304]
    This surely must be resolvable, but after much searching I've yet to find a solution. If it makes any difference, I ONLY want to write png image, and ONLY with an alpha channel (not ever without), in case there are optimisations that that makes possible.
    If anyone can tell me how to address this problem, I'd be very grateful.
    Many thanks, Robert Redwood.

    This isn't a solution, but rather a refinement of the issue.
    Some of the sources I was reading were implying that the long save time might be due to a CPU heavy conversion process that had to take place before the BufferedImage could be saved. I decided to investigate:
    I loaded back in one of the (slowly) saved PNG images using ImageIO.read(file). Sure enough, the BufferedImage returned differed from the BufferedImage I had created. The biggest difference was the color model, which was DirectColorModel on the image I was generating, and was ComponentColorModel on the image I was loading back in.
    So I decided to manually convert the image to be the same as how it seemed to end up anyway. I wrote the following code:
          * Takes a BufferedImage object, and if the color model is DirectColorModel,
          * converts it to be a ComponentColorModel suitable for fast PNG writing. If
          * the color model is any other color model than DirectColorModel, a
          * reference to the original image is simply returned.
          * @param source The source image.
          * @return The converted image.
         public static BufferedImage convertColorModelPNG(BufferedImage source)
              if (!(source.getColorModel() instanceof DirectColorModel))
                   return source;
              ICC_Profile newProfile = ICC_Profile.getInstance(ColorSpace.CS_sRGB);
              ICC_ColorSpace newSpace = new ICC_ColorSpace(newProfile);
              ComponentColorModel newModel = new ComponentColorModel(newSpace, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
              PixelInterleavedSampleModel newSampleModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, source.getWidth(), source.getHeight(), 4, source.getWidth() * 4, new int[] { 0, 1, 2, 3 });
              DataBufferByte newDataBuffer = new DataBufferByte(source.getWidth() * source.getHeight() * 4);
              ByteInterleavedRaster newRaster = new ByteInterleavedRaster(newSampleModel, newDataBuffer, new Point(0, 0));
              BufferedImage dest = new BufferedImage(newModel, newRaster, false, new Hashtable());
              int[] srcData = ((DataBufferInt)source.getRaster().getDataBuffer()).getData();
              byte[] destData = newDataBuffer.getData();
              int j = 0;
              byte argb = 0;
              for (int i = 0; i < srcData.length; i++)
                   j = i * 4;
                   argb = (byte)(srcData[i] >> 24);
                   destData[j] = argb;
                   destData[j + 1] = 0;
                   destData[j + 2] = 0;
                   destData[j + 3] = 0;
              //Graphics2D g2 = dest.createGraphics();
              //g2.drawImage(source, 0, 0, null);
              //g2.dispose();
              return dest;
         }My apologies if that doesn't display correctly in the post.
    Basically, I create a BufferedImage the hard way, matching all the parameters of the image I get when I load in a PNG with alpha channel.
    The last bit, (for simplicity), just makes sure I copy over the alpha channel of old image to the new image, and assumes the color was black. This doesn't make any real speed difference.
    Now that runs lightning quick, but interestingly, see the bit I've commented out? The alternative to setting the ARGB values was to just draw the old image onto the new image. For a 640x512 image, this command (drawImage) took a whopping 36 SECONDS to complete! This may hint that the problem is to do with conversion.
    Anyhow, I got rather excited. The conversion went quickly. Here's the rub though, the image took 9 seconds to save using ImageIO.write, just the same as if I had never converted it. :(
    SOOOOOOOOOOOO... Why have I told you all this?
    Well, I guess I think it narrows dow the problem, but eliminates some solutions (to save people suggesting them).
    Bottom line, I still need to know why saving PNGs using ImageIO is so slow. Is there any other way to fix this, short of writing my own PNG writer, and indeed would THAT fix the issue?
    For the record, I have a piece of C code that does this in well under a second, so it can't JUST be a case of 'too much number-crunching'.
    I really would appreciate any help you can give on this. It's very frustrating.
    Thanks again. Robert Redwood.

  • How do I save a PNG file with an alpha channel in Photoshop CS5?

    I have a PNG file created in Photoshop and I need to save it with an alpha channel for web purposes. I tried 'Save for Web & Devices' and selecting the Transparent box. Then, after saving, when I select 'get info' for the file it says there is no alpha channel. I'm stumped I can't seem to create an alpha channel from within Photoshop while I'm editing. Help!

    If you save as a 24bit png with transparent checked photoshop will save the png with transparent background (ie alpha transparency).  The png will appear transparent in a web browser.

  • JSFL SpriteSheetExporter exports png's without alpha channel.

    Hi,
    When I generate spritesheets using the JSFL SpriteSheetExporter it seems the generated png's always come with a solid background. I have found no information in the documentation on how to control this (e.i make the background transparent).
    SpriteSheetExporter.format returns  "RGBA8888", so the image appearenly has an alpha channel.
    Grateful for any information or ideas to help resolve this issue.
    Cheers!

    Esdebon,
    Thanks for the reply.
    No, the movieclip has a transparent background.
    Note that this question concerns the JSFL SpriteSheetExporter (scripting). The tutorial you refer to seem to cover the sheet exporter in the Flash IDE.

  • Motion 5, Importing a PNG, Alpha Channel Wonky

    When I import a PNG into motion the alpha map gets brighter— brighter than it looks in photoshop, preview, pixelmator, etc.
    Then in motion if I just export the project as a movie, the alpha channel values seem to return to normal in the MOV file. It's comforting to know that the final product will turn out ok, but how am I supposed to know what it will look like wihtout having to export the project everytime I want to see what it looks like. Note: I don't ever remember encountering any problems like this with Motion 4.
    Any help appreciated. Thanks.

    Very top right of the Motion interface, 4th icon from the right, check those settings.

  • BufferedImage from PNG : Alpha Channel disregaurded

    I'm trying to load a PNG with an alpha channel into a BufferedImage, and
    then sample the BufferedImage at various pixels for some operations.
    However, the alpha channel seems to get lost upon creation of the BufferedImage.
    For example, I'm using a PNG that is 100% transparent, and when I
    load it into a BufferedImage and display it on a panel all I see is the panel's background color.
    So far so good. Now, the problem. When I try to sample a pixel, the alpha is always 255 or 100% opaque
    which is clearly not right. Also, when I print out the BufferedImage's type, I get 0 which means the image
    type is "Custom". Care to shed any light as to how I can accurately sample an image with an alpha channel?
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import javax.imageio.*;
    import java.awt.image.*;
    public class PNGTest extends JFrame {
        public PNGTest() {
            setLocation(500,500);
            BufferedImage img = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
            try {
                img = ImageIO.read(new File("C:/folder/folder/myPNG.png"));
            } catch (Exception e) {
            setSize(img.getWidth(), img.getHeight());
            getContentPane().setBackground(Color.white);
            getContentPane().add(new JLabel(new ImageIcon(img)));
            setVisible(true);
            //Sample top left pixel of image and pass it to a new color
            Color color = new Color(img.getRGB(0,0));
            //print the alpha of the color
            System.out.println(color.getAlpha());
            //print the type of the bufferedimage
            System.out.println(img.getType());
        public static void main(String[] args) {
            new PNGTest();
    }Edited by: robbie.26 on May 20, 2010 4:26 PM
    Edited by: robbie.26 on May 20, 2010 4:26 PM
    Edited by: robbie.26 on May 20, 2010 4:29 PM

    Here ya go robbie, ti seems to work for the rest of the world, but not for you:
    import java.awt.*;
    import java.awt.image.*;
    import java.net.URL;
    import javax.swing.*;
    import javax.imageio.*;
    public class JTransPix{
      JTransPix(){
        JFrame f = new JFrame("Forum Junk");
        JPanel p = new MyJPanel();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);
        f.pack();
        f.setVisible(true);
      public static void main(String[] args) {
        new JTransPix();
      class MyJPanel extends JPanel{
        BufferedImage bi = null;
        MyJPanel(){
          try{
            bi = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/commons/archive/4/47/20100130232511!PNG_transparency_demonstration_1.png"));  //here ya go--one liner
            this.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
          }catch(java.io.IOException e){
            System.out.println(e.toString());
        public void paintComponent(Graphics g){
          super.paintComponent(g);
          g.setColor(Color.BLUE);
          g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
          g.drawImage(bi,0, 0, this);
    }Please notice how the BufferedImage is declared and set to NULL, then allow ImageIO to set the type--Just as I said before. If you have any question about the PNG producing an ARGB image with ImageIO, then change the color painted onto the backgroun din the paintComponent to what ever you want and you'll see it show through.
    BTW: even in the short nobrainers--you still need to have VALID CATCH BLOCKS.
    To get what you are looking for, you can mask off the Alpha component by dividing each getRGB by 16777216 (256^3) or do a binary shift right 24 places.

  • Graphics, ImageIO, and 32-bit PNG images with alpha-channels

    I have a series of 32-bit PNG images, all with alpha channels. I'm using ImageIO.read(File) : BufferedImage to read the PNG image into memory.
    When I call graphics.drawImage( image, 0, 0, null ); I see the image drawn, however all semi-transparent pixels have a black background, only 100% transparent pixels in the source image are transparent in the drawn image.
    The Graphics2D instance I'm drawing to is obtained from a BufferStrategy instance (I'm painting onto an AWT Canvas).
    Here's my code:
    Loading the image:
    public static BufferedImage getEntityImage(String nom, String state) {
              if( _entityImages.containsKey(nom) ) return _entityImages.get( nom );
              String path = "Entities\\" + nom + "_" + state + ".png";
              try {
                   BufferedImage image = read( path );
                   if( image != null ) _entityImages.put( nom, image );
                   return image;
              } catch(IOException iex) {
                   iex.printStackTrace();
                   return null;
         private static BufferedImage read(String fileName) throws IOException {
              fileName = Program.contentPath + fileName;
              File file = new File( fileName );
              if( !file.exists() ) return null;
              return ImageIO.read( new File( fileName ) );
         }Using the image:
    Graphics2D g = (Graphics2D)_bs.getDrawGraphics();
    g.setRenderingHint( RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
    public @Override void render(RenderContext r) {
              Point p = r.v.translateWorldPointToViewportPoint( getLoc() );
              int rad = getRadius();
              int x = (int) p.x - (rad / 2);
              int y = (int) p.y - (rad / 2);
              BufferedImage image = Images.getEntityImage( getCls(), "F" );
              r.g.drawImage( image, x, y, null );
         }

    You may want to check on you system and see what ImageReaders are available, it could be ImageIO is just not picking the best one, if not, then you can use getImageReaders to get an iterator of image readers, then choose the more appropriate one.

  • Automator or Applescript using png files with alpha channel

    I have hundred of png files with alpha channel.
    I want to suppress alpha channel.
    How can i do it using Automator or Applescript ?
    Thank you very much.

    You can use the free command line image processing tool ImageMagick in your Applescripts or Automator workflows, as well as from a Terminal shell.
    You can download ImageMagick from http://www.imagemagick.org, but Cactuslab has simplified installation by putting together an installer package. It’s available at  http://cactuslab.com/imagemagick/. Download the package and double-click on it. Follow the instructions to install. It will install ImageMagick into /opt/ImageMagick and add it to your $PATH by creating a file in /etc/paths.d/. Restart your computer for the changes to take effect.
    The two ImageMagick commands we’re concerned with are “convert” and “mogrify”. Convert is more efficient for multiple and piped operations on the same image file, and mogrify is more efficient for batch processing. Generally speaking, convert will output a file separate from the input file. Unless a path is specified, mogrify will overwrite the input file with the output file. An important distinction.
    You can perform various operations on the alpha channel using arguments after either the convert or mogrify command. Two of the available arguments are:
    -alpha off - Disables the image's transparency channel. Does not delete or change the existing data, just turns off the use of that data.
    -alpha remove - Composite the image over the background color.
    Also of use are the -flatten and -background options:
    -flatten - overlay all the image layers into a final image and may be used to underlay an opaque color to remove transparency from an image.
    -background - sets the background color.
    Start off using the convert command with a single image to see the effect and adjust to your liking. Once you’ve achieved the desired outcome, then use the mogrify command to batch process the chosen images.
    Before getting into how to use Automator or Applescript in your workflow, use Terminal and the command line to see the effect on a single image. Copy one image to your ~/Desktop. In Terminal change the directory to ~/Desktop by typing the following command and pressing the Enter key:
    cd ~/Desktop
    Then choose the option you are looking for, -alpha remove for instance, type the following command and press the Enter key:
    convert input-photo.png -alpha remove output-photo.png
    You can check the alpha channel (transparency) and background in the Preview app, go View > Show Image Background from the menu bar.
    Once you’re ready to batch proces, place all the photos you want to convert with the same command into one folder. Copy the folder to your ~/Desktop. Let’s assume you’ve labeled the folder “InPhotos”. It’s prudent to manipulate copies in case something goes amiss. In that event you can copy the folder with the originals again and start over. Create a new empty folder on your ~/Desktop and call it “OutPhotos”. Let’s also assume your home directory is called “Me”. The following command will process the photos from the InPhotos folder and put them in the OutPhotos folder:
    mogrify -alpha remove -path /Users/me/Desktop/OutPhotos/ /Users/me/Desktop/InPhotos/*png
    According to Apple Technical Note TN2065:
    "when you use just a command name instead of a complete path, the shell uses a list of directories (known as your PATH) to try and find the complete path to the command. For security and portability reasons, do shell script ignores the configuration files that an interactive shell would read"
    So, you need to use the full path to to ImageMagick commands, unlike in the shell where you can just use the command name.
    To batch process using Automator, use the “Run Shell Script” action (note: retain the single space at the beginning of the last line):
    /opt/ImageMagick/bin/mogrify \
    -alpha remove \
    -path /Users/Me/Desktop/OutPhotos/ \
    /Users/Me/Desktop/InPhotos/*png
    To batch process using Script Editor (Applescript), use the “do shell script” command:
    do shell script "/opt/ImageMagick/bin/mogrify -alpha remove -path /Users/pd/Desktop/OutPhotos/ /Users/pd/Desktop/InPhotos/*png"
    Further info on ImageMagick:
    http://www.imagemagick.org/script/command-line-options.php#alpha
    http://www.imagemagick.org/Usage/masking/#remove
    http://www.imagemagick.org/index.php
    http://www.imagemagick.org/script/command-line-tools.php
    http://www.imagemagick.org/script/command-line-options.php
    Examples:
    The original PNG image:
    -alpha off:
    -alpha remove:
    -background black -flatten:
    -background blue -flatten:
    -channel alpha -evaluate Divide 2:
    -channel alpha -evaluate Divide 2 -background black -flatten:

  • Export PNG images with alpha channel from flash

    Hi,
    I have this FLA with animation and when played, the animation has alpha channel. I can’t understand why when I look in the library I see the frames without the alpha channel and also when I try to export/extract the image again the image don’t have alpha channel.
    How is it that in flash this image has alpha channel and how to get it out like that into PNG?
    Here is the link to download the FLA:
    http://download759.mediafire.com/nb749r29220g/e0636ab0ru6ouoa/Untitled-1.fla

    "when played, the animation has alpha channel"
    how are you playing the animation? control/enter in Flash, Publishing to a Web page or what?
    How can you tell that the animation has the alpha channel? What exactly are you seeing?
    What is the aniimation? a series of images, one image moving? Are teweens imvolved?
    " when I try to export/extract the image again the image don’t have alpha channel"
    How are you exporting the image? is it a single image? or a series of frames that makes up an animation?
    What was the file format of the original image? you brought that image into Flash and animated it? Now you want to export as a .png with transparency?
    Have you ever tried to export a  simple .png before so that you see and understand the dialog box that pops up during export? are you chosing "24 bit with alpha channel" in the "Colors" choice?
    For those of us who may not want to download your file, please provide a more detailed describtion of everything related to this question.
    Best wishes,
    Adninjastrator

  • .png animation files... how to import keeping alpha channel please!

    My graphics man has buit me a animation on white swirly things on his system
    and given me them as sequential files.
    On gfx without alpha I open then in quicktime, open a sequential files then export to dv.
    Now of course dv will not keep alpha channels so any help on how to take this animation alpha .png and get it into my fcp time line would be much appreciated,
    regards
    daz

    Apple Animation is a high quality video codec that can support an alpha channel.
    While there are other formats that also support alpha channel, Apple Animation is the codec of choice on the Mac because it lets us transfer files between different software packages without any hassle.
    For instance, you could export a 3D scene from Maya, manipulate it further in After Effects then drop it into the FCP Timeline, all without converting it to something else at each stage.

  • How do i create an alpha channel to place into edge animate?

    HowHow do i create an alpha channel compatible with edge animate?

    I don't use Edge, but since it is a web tool it stands to reason it would use standard web techniques, meaning it would rely on built-in transparency functions of formats like PNG and GIF, which you can easily produce by using Save for Web after creating normal transparency on a layer in Photoshop. No extra Alpha channel or otehr extra steps required. Perhaps Edge even has some stuff that does the conversion on the fly by allowing you to open a native PSD like in Dreamweaver, but beyond that I don't see what else it could/ would do - all the features it can provide are limited by standard specifications for HTML, CSS and JavaScript. There is simply no way to do something sensible with a TIFF in a browser, if you get my meaning .
    Mylenium

  • How to get premultiplied alpha in a png embedded with compression=true

    Hi there,
    I found that the [embed] tag has many undocumented features (and WHY ... WHY are they not documented?! and IS there any place where it is all thoroughly documented? Well, the one in the Flex documentation isn't really that helpful)
    So you can embed PNGs in a compressed way like JPGs with compression=true and quality=70 i.e. to save a transparent PNG with JPEG compression.
    BUT when I do that, the alpha seems to not get premultiplied, it doesn't behave like when I don't compress it. The shadows aren't dark anymore but almost lighten the areas up. When not using compression & quality, the shadow areas look like they're supposed to.
    When using a PNG compressed by the Flash IDE, it works.
    So, is there ANOTHER undocumented embed-feature which lets you control if the alpha-channel gets premultiplied or not?
    That would really help in some cases.
    Right now I'm still using the Flash IDE for that, but it would be nice to know if there is a way to make it work merely by Flex EMBED tags.

    Hi corlettk,
    Thanks for your reply. I have defined my map as Map<String, Boolean> selectedIds = new HashMap<String, Boolean>();
                selectedIds.put("123-456", true);           
                int m=123; int n=456;
                                     selectedIds.put(String.valueOf(m) + "-" + String.valueOf(n),true);
                boolean viv = selectedIds.get("String.valueOf(m)-String.valueOf(n)");
                System.out.println(viv);
                My problem is the hashmap key must be set dynamically ("123-456" is just an example) and when i get the value i should be able to pass those varibales in an expression correctly. Please let me know how can i pass an expression like the one above as a hashmap key. Please advise.

Maybe you are looking for

  • How to open a wsdl file in Weblogic Workshop 10.3? Cannot seem to do so!

    Hello, I'm new to Weblogic Workshop 10.3 & will be working with learning how to develop and use webservices using the application. I have a WSDL file which i want to use in a project but cannot seem to import or use the file as required. If I click o

  • Leopard install on ibook lost hard drive

    I tried to install leopard on my macbook and installation completed. the system restarted and the installer came back. My hard drive is no longer recognized and I cannot get the install disk out. Any ideas on how to get my hard drive back?

  • How to change apple Id for updating

    My daughter has already signed into the app store on a different user on my mac . When I go to download or update apps on my user, I cannot do this because her apple ID has saved to the app store for the whole computer. As I  do not know her password

  • Avoid marking files as modified by Git when there are no changes

    Hello, I am working on a project using Visual Studio 2013 Ultimate and Enterprise Architect 9.0 (a UML tool). I am using Git for Source Control in Visual Studio. I have set up the programs so that I can synchronize code from Enterprise Architect (EA)

  • Headphone issues

    While recording v.o., there is no sound coming out of headphones. I can't monitor what I'm recording. When I playback the track, the recorded sound now is heard in the monitors, but not through my headphones. I called Adobe customer service and they