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

Similar Messages

  • Why does exporting to jpeg or png come out blurry in Illustrator CC?

    Hello,
    I am dying to export a poster ( size 27 x 41 in) from Illustrator CC into a jpeg. The image comes out blurry and text is fuzzy and not legible.
    300 dpi, anti-aliasing optimized. Why does this happen?
    The pngs won't even save, it takes hours and shuts down?
    How can I export this crisp and clear in a format that client can use to print it form Staples or other center?
    Kind,
    Owl101

    Hi There
    I am experiencing the same issue. The jpg / png files which are exported from Illustrator CC turns out bad... and I did not want huge files (example 72dpi for web images) Can @Adobe @AdobeCare please provide assistance? I am using the Retina Mac Book Pro laptop.
    Appreciate.

  • Why does reader freeze while opening some pdf files and others open instantaneously?

    I use pdf files created from CamScanner and shared from DropBox.  In DropBox, many times (over 50%) while opening the PDF the process freezes and the error message is Adobe Reader is not responding.  If you close the program, and re-open the file, it opens fine.  I have saved these files to my computer and the same issue occurs.  The files are 100-500kb, so I do not think size is the issue.  I have reinstalled Reader (11.1.10) and there is no improvement.

    This appears to have reduced the time to load a document.  Thanks Jimb      From: Anubha Goel <[email protected]>
    To: jimb70395944 <[email protected]>
    Sent: Friday, March 20, 2015 4:37 AM
    Subject: You have been mentioned by Anubha Goel in Re: why does reader freeze while opening some pdf files and others open instantaneously? in Adobe Community
    |
    You have been mentioned
    by Anubha Goel in Re: why does reader freeze while opening some pdf files and others open instantaneously? in Adobe Community - View Anubha Goel's reference to you  Hey jimb70395944, Please try disabling protected mode under 'Edit> Preferences> Security (Enhanced)' and uncheck 'Enable Enhanced Security' option.Then, try again and let me know.  Regards,Anubha
    Participate in the conversation by replying to this email
    To stop receiving these messages whenever you are mentioned, go to your preferences and disable notifications for direct social actions. |

  • Photoshop CS3 does not recognise gif or png

    When trying to open a gif or png, I receive the message:
    "Could not complete your request because Photoshop does not recognise this type of file"
    I am running CS3 and have just added the 10.5.3 update.

    I have a similar problem that suddenly appeared. When properly working, I can save a tif file as a jpeg (or other)and the tag "tiff" will switch to "jpg" in the save description. That does not work anymore. A same example is when I save a Photoshop document as a "tif" or "jpg" or "png," the save description does not change any more to the appropriate form. Meaning, if I took a document named "Mydoc.psd" and tried to save it as a "jpg," I would scroll in the "Format" bar down to "JPEG." BUT, the title of the document will remain as "Mydco.psd." When I try to open it by double-clicking on it, Photoshop will not recognize it. I must open it thru Photoshop only.
    Got recommendations?
    Thanks anyone.

  • Why does Reader 9 not find Reader X as an update?

    When I check for updates through Reader 9 I am told that "No Updates Available". Reader X has been out for months now, so why does Adobe's own product not recognize their own update?  It is so infuriating that these kinds of basic things can never simply be problem free.

    Hello,
    Adobe Reader X in not an update to Adobe Reader 9, its an upgrade version of Adobe Reader 9
    Updates apply to the same version, for example :
    1) Latest update for Adobe Reader 9 is 9.4
    2) Latest Update for Adobe Reader 10 is 10.0.1
    Thanks
    Vikram

  • Bug in fireworks CS4 when exporting 24/32bit png with transparent alpha?

    Hi there,
    I recently upgraded to CS4 from CS3 and am quite disappointed to find that the png export facility for 24 or 32 bit png's is next to useless on my installation of Fireworks (Vista). I have a colleage who has reported the same behanviour on his mac.
    Please see this native fireworks CS4 png file and attempt to export it as 24 or 34 bit png, ensuring the canvas is transparent (it shuold be already)...
    http://www.capitalh.net/demo-bug.png
    Viewing in preview mode in CS3 would show the png with its alpha channel indicated by the chequered transparent pattern. Exporting it as such would produce the desired result > a png with a nice blended alpha channel.
    Viewing in preview mode in CS4 shows a horrible render of the image on a white background. Exporting the image produces the same result. Please see this link for confirmation:
    http://www.capitalh.net/demo-bug-export.png
    Please also see this simpler image, this time using a simple ellipse shape:
    http://www.capitalh.net/demo-bug-export-simpleshape.png
    You'll notice that it is not transparent, and the ellipse has not been anti-aliased.
    Can anyone shed some light on this behaviour?
    Exporting png's as such is something that I do daily at work, and is a basic requirement of an image editting application targetted at web design.
    Am I doing something wrong? I've been using Fireworks since 2003 so I'm inclined to think that I'm not.

    That's a bit, um, oh never mind. Would've been a rubbish joke anyway.
    Aww...pooh. I love "rubbish" jokes!
    If fireworks is unable to export a transparent png at 24bit, then why have the option?
    (granted the option is acutally implied, not given)
    Also, why the horrible rendering on preview and export?
    Transparency for 24-bit isn't an option and isn't implied. Create a FW document with a transparent canvas. Go to File>Image Preview. If you select PNG8 as your export option, then you have drop-downs for No Transparency, Index Transparency, or Alpha Transparency. PNG32 shows the checkerboard where the document is transparent. If you select PNG24, you do not have the transparency options. Transparent areas in your document are set to white, just as they are if you select the JPEG format. Try it.
    I don't know why your rendering is horrible. I'd have to see your image.
    And also, why all this confusion related to Photoshop, seems Adobe really aren't helping the issue:
    http://forums.adobe.com/thread/152434
    Possibly Adobe thought it was less confusing, as they didn't have to go into the math. However, you do see Linda Rathgeber's answer, that the Photoshop convention is...well...misleading? (I'd call it wrong, but that's just me. ) It's just one other issue to bring into alignment as Adobe works to merge the Macromedia offerings into their line.

  • Why does Reader for Android want access to my GMail?

    I was about to update Adobe Reader  on my Droid X just now and decided to review what changes were being  made to the application's permissions. Apparently now I would have to  "Allow this application to access: Your messages (read Gmail)"
    Why would Adobe Reader need access to my Gmail messages?

    This unexplained change in required privileges is totally unacceptable.
    I am only one of many who are posting in Market feedback that we will not update to this latest version until a reasonable explanation is given. 
    As with Apple's "LocationGate", a failure to communicate early, clearly and accurately will cause (is causing?) a major negative reaction among users. 
    Adobe needs to either give a credible reason for this change or roll out an update that doesn't require access to our Gmail. 
    A further reason to be concerned about this privilege request: they want to access Gmail, but make no request to access our other email accounts via "messaging".  Why just Gmail?  
    Update: their revised release note mentions access to standard email with this update, but still does not request permission to do so. This makes the Gmail privilege all that more suspicious. As for their claim this is needed to open PDF attachments, the prior version did this without Gmail access permission  
    In any case, I'm joining the update boycott until this is explained or removed. 
    Message was edited by: sylerner to improve formatting and add an update.

  • Why does AI CC 2014 "Welcome Window" contain tutorials demonstrating AI CC not 2014?

    This is REALLY confusing. I am relieved to see "smooth tool toggle" has been returned as an option for the Pencil tool in CC 2014, but the "Rebuilt Pencil Tool" video within "Welcome>New Features" is showing an old version that does NOT contain this option and the presenter is talking as if it's the greatest thing since sliced bread. How confusing is that??

    they probably didn't see the point in a new one given the paucity of new features in the current ver.

  • Why does Reader say "Failed to initialize"?

    Trying to install Reader 10 on a Windows XP SP3 system.  During installation, I'm getting an error message that reads "Installation encountered errors" and "Failed to initialize".
    I tried uninstalling older versions of Reader still on my system, but no change.  I reinstalled Reader 8 from a CD, and that doesn't make any difference, either.  I tried doing a search on "Failed to initialize" on this site, but didn't come up with anything pertinent for Reader.
    Any clues?  Thanks!

    I still don't know why Reader 10 wouldn't install, but I figured out a workaround.  Instead of downloading from Adobe's "preferred" or default site, I instead used this link as suggested in a thread for a different problem:
    http://get.adobe.com/reader/enterprise/
    Downloading from there, I was able to get it installed correctly and Reader 10 works fine.  The only thing I can figure is that whatever program Adobe's default download site uses has an incompatibility with either something on my computer or my browsers.  I'm using both Google Chrome and IE 8, and the same error message happened with both browsers while trying to use Adobe's default site.

  • Why does Reader 9 load multiple images?

    I am operating on Mac OS X 10.4.11 (Intel). I just recently downloaded Reader 9 for Intel. Ever since that, whenever I click on any PDF document the reader quickly opens a large number of other PDF documents, not stopping until the maximum number at one time is reached. Now even my older Reader 8 does the same thing. I have downloaded Reader 9 a second time, to no avail. What can I do?.........jghist

    We are getting several reports of this. Try removing your user cache with a utility like Applejack.

  • Why does reading list no longer allow offline reading?

    For as long as I've had my iPhone 4S I've used Safari's Reading List to save pages from the browser to read later (so that I don't eat up the data on my plan). It's worked just fine for months, but now, in the last couple weeks, everything I have saved on my Reading List says that it is "Not Available for Offline Reading". Is anyone else having this issue?

    Hello Tseecka,
    It sounds like you are not able to use the Offline Reading List feature on your iPhone 4S.  According to iOS 6: Which software features does my iPhone, iPad, or iPod touch support? (http://support.apple.com/kb/ht5457), your iPhone 4S does support the offline reading list feature. 
    I found an article that has steps to troubleshoot issues with the Reading List.  I recommend following the steps under the section titled "Troubleshooting Bookmarks and Reading List update or setup issues on iOS devices" in the following article:
    iCloud: Troubleshooting iCloud Bookmarks and Reading List
    http://support.apple.com/kb/ts4001
    Thank you for posting in the Apple Support Communities. 
    Best,
    Sheila M.

  • Why does Reader 11 incorrectly set the DDE Server Name?

    It appears to me that the installer is setting the DDE Server name in the registry to 'AcroviewR10' instead of the 'AcroviewR11'.
    I confirmed by upgrading from Reader 9.5.x (DDE == Acroview) to Reader 11 (as of Oct 22, 2012) and the new value in the registry (XP and 7) was AcroviewR10.
    I know there was a similiar issue when Reader 10 was released. Is there any idea when an update might come out that will fix this? I hate having to give customer's .reg files to fix these issues.
    I understand that you are new to updating this variable every release, and so it isn't a part of your checklist yet, but it would be highly appreciated if you could remember that for version 12.

    I had this working using the registry lookup this week. During testing on various machines, I found a discrepancy between the registry dde name and the dde name that acrobat would respond to.  I finally just made an array of possible names and iterated through them.
    I'm harvesting the application name from HKEY_LOCAL_MACHINE \Software\Classes\acrobat\shell\open\ddeexec\application in the registry.
    Capitalization does not seem to matter but I'll include the exact caps from my tests.
    Today :
    Acrobat XI Pro (11.0.06) shows up in the registry as AcroViewA10 but it responds to acroviewa11.
    Acrobat XI Pro (11.0.0) shows up in the registry as AcroViewA10 but it responds to acroviewa11.
    Acrobat Reader XI (11.0.06) shows up in the registry as AcroView
    R10 but it responds to acroviewr11.
    Acrobat X Reader (10.1.9) shows up in registry as AcroViewR10 and responds to acroviewr10.
    Reader 9 (9.0.0) shows up in registry as AcroViewA10 and responds to acroview. (The registry may be skewed by having Acrobat XI Pro installed on this machine.)
    Reader 7 (7.1.0) shows up in registry as AcroView and responds to acroview.
    So, I'm just brute forcing through all 5 known combinations plus 2 for version 12 on the off chance that the naming doesn't break pattern again.
    #define maxnames 7
    DIMENSION acronames (maxnames )
    acronames(1) = "acroview"
    acronames(2) = "acroviewa11"
    acronames(3) = "acroviewr11"
    acronames(4) = "acroviewa10"
    acronames(5) = "acroviewr10"
    acronames(6) = "acroviewa12"
    acronames(7) = "acroviewr12"
    loop
         AcroChanNum = DDEINITIATE(acronames(namecounter ), "Control")
         namecounter = namecounter + 1
          blah blah
    until AcroChanNum >=0

  • Why does reader announce punctuation

    Hi, i've written an exciting sci-fi novel with microsoft word 2007, using a microsoft ad on I converted my file to a pdf. When the pdf is read in adobe reader it is announcing punctuation marks like quotation marks and apostrophes. my first thought was the font, so i am using a common one times roman and it still reads funny. Everything else reads as expected. I am not sure if this has to do with reader, word, or the combination. anyone have advice on how to make a perfect pdf, is there something Im not doing in making the pdf that is not right. any advice would be helpful.

    Robert,
    I cannot say for sure, how Reader should pronounce text. I would want
    Reader to pronounce punctuation. How else could someone who could not
    see know if something was written properly. But I would admit, that it
    would be nice to have the ability to turn it off.
    Mike

  • Why does Reader require Internet access everytime?

    I am using Adobe X. Can anyone explain to me why this application must have access to the internet everytime it is opened? What are the implications if you block reader 100% of time using your firewall... other than having to do manual updates?

    Here is the link.
    http://get.adobe.com/reader/enterprise/

  • Variation on a theme - Why does Robohelp resize gifs when import from mif?

    This is a variation of other threads, in my case we still have
    an old RoboHelp (2003) because it still works. One weakness was our
    documents have many screen shots (96ppi in gif) and they were converted to
    jpeg and sized too small to be legible. We resolved this by writing a perl script that
    swapped back the original gifs and updated the references in the html to point to the gif files.
    For many years it worked, customer very happy, as in attachment.
    Now with Robohelp8 (have demo), the figures are staying as gif, and yet they are still being
    downsized. I've read other forums, but need to know the exact steps for what to do when I import,
    since I have many screenshots and could not tweak each figure to make it the real pixel size.
    (and yet when double-click the image it shows the figure clearly, see other attachment.
    There are a lot of other issues, but this is a good start, thanks.

    Hi,
    It seems to me that you quickly need to reset the size of all the images in your project. Luckily, Chashnikov has written a script to do this for you. See http://forums.adobe.com/thread/466933.
    Hope that helps.
    Greet,
    Willam

Maybe you are looking for

  • Between condition in rtf

    hi all, can i have between condition in RTF. i'm trying to use <?if:+ExpirationDate+ between StartDate and EndDate ?> but doesn't work. any idea about this? please share your experience.thx rgrds, dityo

  • Is it possible to get back to the Try block from a Catch block?

    I would like to perform validations on a config file. To do so, I have a method which will throw a MissingConfigException or an InvalidConfigException if something is missing or if something doesn't match a regex pattern. Although I have to do that w

  • Trouble Importing mp3 Files

    Hello: I've installed iLife 06 over a week ago, and played around a little with Garageband 3. By the way, I'm running Panther (10.3.9) on a Powerbook G4 laptop. I do a radio show, and so I usually record a two-hour show. For the heck of it, I wanted

  • Linking Analyzer views

    I'd like to do the following with the Analyzer:On the 1st view, the user selects his unit with a dropdown field. When he changes then to the other views (4 in total), his selected unit should be active for the tables and charts there. I can link cert

  • Converting 50fps 5.1 Audio AVCHD/MTS files to 5.1 Audio at 25fps ProRes

    I'm having a bit of a problem finding a way to convert the files from my Panasonic camcorders to edit in FCP 7. At the moment, I have been using two applications to convert the AVCHD files, Toast and ClipWrap but neither of these applications seems t