Saving large PNG files with ImageIO.write

I have a program that draws onto a DrawPanel (extends JPanel) which is inside of a JInternalFrame. I have used ImageIO.write to successfully save the drawing as a PNG file, but a most unexpected thing happens if the image to be saved is larger than my desktop resolution. For instance, if the DrawPanel/output image is 1200*1200 pixels in size and my desktop resolution is 1024*768, I end up with a PNG file of 1200*1200 pixels that is a tiled image of the first 1024*768 from the upper left corner of the desired image.
Here is the portion of code responsible for exporting the image:
JInternalFrame jif = desktop.getSelectedFrame(); //desktop is a JDesktopPane
DrawPanel dp = jif.getDrawPanel();
BufferedImage image = new BufferedImage(dp.getWidth(), dp.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
dp.paint(g2d);
g2d.dispose();
ImageIO.write(image, "png", targetFile);
I could very easily prevent the user from saving an image if it is bigger than the desktop resolution, but it is a necessity that large images can be saved.
Any help would be appreciated.

I've taken a look at that, on your recommendation, but I get the impression that this will filter the image and throw away information. Is this the case? The image will contain narrow lines and small text, so that woudn't be really be an option. I still want the image to be the full size it should be.
I had a go at incorporating it into my code, anyway, but I'm not really sure how to. Would I need to capture the image in some way other than with a BufferedImage?

Similar Messages

  • Png files with transparent background show black only in firefox for android

    I have a wix created site and png files with transparent backgrounds are showing with a black blackground in Firefox for Android. They show transparent in all other browsers I have tried.
    I have tried saving the file as a gif, as a smaller png, interlaced, not interlaced, png 8, png24. It still shows black in Firefox for Android.

    Hi evelswoman,
    Thank you for your question. This sounds like a good one for the web compatibility team. Currently there are some compatibility documentation for background-image here: [https://developer.mozilla.org/en-US/docs/Web/CSS/background-image] and more details on background: [https://developer.mozilla.org/en-US/docs/Web/CSS/background]
    Filling a bug with webcompat.com with an example url can go a long way as well, I hope this helps.

  • Problem with ImageIO.write

    Hello I am trying to write to file. Here is my code
        try
          File file = new File("C://images//queryX.gif");
        if (file.exists())
            {file.delete();}
          ImageIO.write(bi_new, "GIF", file);  // bi_new is my bufferedImage
        catch (IOException e)
          e.printStackTrace();
        }The file is being created but it is blank. The buffered image is fine because i am having it displayed to screen with an imageicon on a Jlabel.
    Any ideas why the file is blank?
    Cheers.

    The likely problem is that an encoder can not be found.
    First check the return value from the ImageIO.write() method. If it is false it means that an appropriate
    encoder could not be found. (This is quite likely as GIF encoders have some patenting problems and
    Im not sure if SUN has included a GIF encoder.
    Also it should not be necessary to delete the file if it already exists as the ImageIO.write method will
    overwrite it anyway.
    matfud

  • Problems with ImageIO.write()

    Well I am finding it very strange with ImageIO.write();
    Consider the following code snippet:
    BufferedImage img=ImageIO.read(new File("fw2.jpg"));
    BufferedImage img1=new BufferedImage(img.getWidth(),img.getHeight(),img.TYPE_INT_ARGB);
    for(int i=0;i<img.getHeight();i++)
    for(int j=0;j<img.getWidth();j++)
    img1.setRGB(j,i,img.getRGB(j,i));
    ImageIO.write(img1,"jpg",new File("fwinv.jpg"));
    So simply I am copying fw2.jpg to fwinv.jpg. fw2.jpg was also created
    using ImageIO.write().
    But the two files are having different pixel values.
    i.e If I read fwinv.jpg again I will get different pixel value that it was written.
    Why is this...Can any one please help me..

    Reading the written images back and displaying them in java works okay. The third image looks okay in RGB but wrong in ARGB when displayed by a native app. For more about this see reply 1 in Color problems and the linked bug report: Some Images written using JPEG Image Writer are not recognized by native applns.
    import java.awt.GridLayout;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class WriteTest {
        private JPanel getContent(BufferedImage src) throws IOException {
            File fileOne = new File("fileOne.jpg");
            ImageIO.write(src, "jpg", fileOne);
            BufferedImage image1 = ImageIO.read(fileOne);
            BufferedImage image2 = copy(image1);
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.add(new JLabel(new ImageIcon(src)));
            panel.add(new JLabel(new ImageIcon(image1)));
            panel.add(new JLabel(new ImageIcon(image2)));
            return panel;
        private BufferedImage copy(BufferedImage in) throws IOException {
            int w = in.getWidth();
            int h = in.getHeight();
            int type = BufferedImage.TYPE_INT_ARGB;   // problem in native apps
                       //BufferedImage.TYPE_INT_RGB;  // this one works okay
            BufferedImage out = new BufferedImage(w, h, type);
            for(int y = 0; y < h; y++) {
                for(int x = 0; x < w; x++) {
                    out.setRGB(x, y, in.getRGB(x, y));
            File fileTwo = new File("fileTwo.jpg");
            ImageIO.write(out, "jpg", fileTwo);
            return ImageIO.read(fileTwo);
        public static void main(String[] args) throws IOException {
            BufferedImage image = ImageIO.read(new File("images/cougar.jpg"));
            WriteTest test = new WriteTest();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getContent(image));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • 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:

  • I created a photo book in Photoshop elements 11 that contains png files with the invisible backgrounds.  When I export the book to a jpg or a pdf, the png files appear with white backgrounds.

    I created a photo book in Photoshop elements 11 that contains png files with the invisible backgrounds.  When I export the book to a jpg or a pdf, the png files appear with white backgrounds.  Any suggestions on how to fix this? 

    jpg and pdf formats don't support transparency. You need to use a format such as tif, png or psd that does.
    Cheers,
    Neale
    Insanity is hereditary, you get it from your children
    If this post or another user's post resolves the original issue, please mark the posts as correct accordingly. This helps other users with similar trouble get answers to their questions quicker. Thanks.

  • Saving large tiff files we see a lot of times the lines in the saved file that have either missing ( white) pixels or they appear as a black line across entire file or portion of it

    saving large tiff files we see a lot of times the lines in the saved file that have either missing ( white) pixels or they appear as a black line across entire file or portion of it

    Due to the current unavailability of clairvoyants and mind-readers in the forum, we respectfully request you supply sensible, complete details.
    BOILERPLATE TEXT:
    Note that this is boilerplate text.
    If you give complete and detailed information about your setup and the issue at hand,
    such as your platform (Mac or Win),
    exact versions of your OS, of Photoshop (not just "CS6", but something like CS6v.13.0.6) and of Bridge,
    your settings in Photoshop > Preference > Performance
    the type of file you were working on,
    machine specs, such as total installed RAM, scratch file HDs, total available HD space, video card specs, including total VRAM installed,
    what troubleshooting steps you have taken so far,
    what error message(s) you receive,
    if having issues opening raw files also the exact camera make and model that generated them,
    if you're having printing issues, indicate the exact make and model of your printer, paper size, image dimensions in pixels (so many pixels wide by so many pixels high). if going through a RIP, specify that too.
    A screen shot of your settings or of the image could be very helpful too,
    etc.,
    someone may be able to help you (not necessarily this poster, who is not a Windows user).
    Please read this FAQ for advice on how to ask your questions correctly for quicker and better answers:
    http://forums.adobe.com/thread/419981?tstart=0
    Thanks!

  • One of my imacs are saving all my files with a capitalized file extension?!

    one of my imacs are saving all my files with a capitalized file extension?! For example: .psd is .PSD this really suck because I keep getting to versions of all my files. Can someone please assist me in fixing this. Thanks! -derek

    Welcome to Apple Discussions!
    Did you format your hard disk on that Mac any differently?

  • Saving PNG file with transparency

    Hello!
    In my application I generate "BufferedImage"s with transparent pixels. When I try to write them using ImageIO.write() in PNG format, the transparency information is lost.
    Can anybody send me working code for this problem?
    Thanks,
    Norbi

    What are you using to view the PNG? Are you sure it is a viewer that supports PNG transparency? Internet Explorer and the previewer built into Windows do not fully support PNG transparency so maybe that's the problem. See http://entropymine.com/jason/testbed/pngtrans/ for more info. I know for a fact the following code will generate a transparent PNG. Photoshop will read the transparency correctly but IE won't.
        public static final void main(String[] args) {
            // Create a new image with an alpha channel
            BufferedImage image = new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
            // Get a Graphics2D object that interfaces to the Image
            Graphics2D g2 = image.createGraphics();
            // Draw a red circle on the image
            g2.setColor(Color.RED);
            g2.fillOval(0,0,100,100);
            try {
                // Write the image to a PNG file,
                //  the red circle will have a transparent background
                ImageIO.write(image, "png", new File(args[0]));
            } catch (IOException e) {
                e.printStackTrace();
        }Anyone know how to do the equivalent with Jimi? This:Jimi.putImage("image/png", image, args[0]); only writes the PNG with a black opaque background.

  • Saving same png file gives me image with 10x smaller size

    Hi.
    I would appriciate if someone explained me what I'm doing wrong.
    I have a png image, of 256x128 size. It has 8bits per pixel for color. Now this image's size is 97kB. I open it in photoshop, I save it as different png file, and then... this image is 7kB of size.
    Can someone tell me what's wrong, or what I'm doing wrong?
    Lucas

    Ok guys, thanks a lot for patience. Below is the main cause why I started this topic, but I still can't figure it out. I thought the loss of size is the cause, but you say it's not :/
    I'm not that skilled as you guys, so that's the primary reason why I'm here. I will be really gratefull if someone could give me a hint here, or some small help.
    To cut to the chase, I'm trying to use a program that creates graphics for older games. This program edits particular files, that have different resolutions and different number of bits per pixel. The problem I have however is the transparency and color palette, as I never had dealings with that. The problem is, that someone created before a pictures that are very smooth, and this seems to be the cause of very smart using of transparency levels, for different colors in the palete. However, I have no idea how to achieve the same effect, I tried many things, but still can't figure this out. I will try to ilustrate the problem below.
    Below is a screenshot from this application
    [img]http://img21.imageshack.us/img21/5396/41135434.png[/img]
    On the right is the picture that is the root of my question here. It has to be in the format with palette of collors in amount of 16, although I have no idea where it stores the alpha channel information, as there are 4 bits for color per pixel. Well anyways, you can see on the right top corner the palette. It basicaly has only the shades of gray in this case. I can switch now to the alpha channel mask, and this is what I get:
    [img]http://img29.imageshack.us/img29/4089/69176653.png/img]
    You can see that each of the colors in the palette has different alpha values. Now what I tried is, I exported the image, I opened it with photoshop, saved it, imported it in the program, and guess what I found in the alpha channel mask:
    [img]http://img821.imageshack.us/img821/7104/51957014.png[/img]
    All the information of the alpha channel for each color is gone!
    Here are the examples with more colors(256):
    [img]http://img853.imageshack.us/img853/2108/84834785.png[/img]
    The alpha channel mask
    [img]http://img718.imageshack.us/img718/4944/25526459.png[/img]
    And now, I do the same as before, export it, save it in photoshop, and guess what, all the info is gone again:
    [img]http://img577.imageshack.us/img577/8991/50003321.png[/img]
    Now loosing this information is not a problem, as I will be inputting different pictures, but my question is, how I can achieve the same effect in photoshop for my images that I will try to import. I would love to have as smooth edges as they are seen on those examples above.

  • System crash with large PNG file

    When I try to fullscreen Preview with a 6.8 MB PNG file, system crash definitely. After a short periode of white screen, I found myself at Login screen. All opened applications are quitted.

    PS: It's OS X 10.9, I forgot to update infomation of my registered Mac.

  • Using PNG files with transparent background - Please Help

    I just purchased Elements to do a very specific task which I can’t do in Aperture. I am a former photoshopper (V.5) and excited to be back.
    I am doing a book/scrapbook and the majority of my text will be my own handwriting. I use white paper and black ink and I scan in at the highest settings. My goal is to create my handwriting on a transparent background so I can place it in my book as I choose. For this specific project (which is very large in scope) I wanted to keep my image/file management within Aperture.
    So I import my file (of my handwriting) from Aperture and successfully saved with a transparent background. Adobe said I had to save it as a PNG file. I noticed when I saved in Photoshop there was a warning saying I had to save as a copy.
    Aperture does not see the file when I try to import it back. My interchange between aperture and photoshop is fine otherwise. This problem only seems to be with “unflattened” layered images. When I flatten the image it is recognized by Aperture, but I lose the transparent background in Photoshop.
    If anyone sees flaws here or has a suggestion to “isolate” and save my personal handwriting image files I would greatly appreciate it. Thanks!

    Would probably work best if you first export from Aperture as PSD (if possible, like Lightroom) and then save to preserve layers.
    From the PSD save as PNG24 rather than PNG8 which is better for preserving transparency.

  • 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.

  • Combining png files with Acrobat 9 Pro reduces image resolution

    Combine creates a PDF with much lower resolution than what results if I insert the png images into an existing PDF. I choose the highest resolution option I see on the Combine screen. Inserting the png files one at a time is too time-consuming for 240 of them. 

    In most word processors, and EPS file is displayed as the bitmap image that is included if one is present. Many EPS files are only vector images and in that case you simply get a place holder. Typically the image that is displayed is a bitmap just to give an idea of what is there. You might consider opening the EPS file in Illustrator and saving as a different vector format, possibly just a EMF file (or WMF). That should look fine in WORD. You could even clip it from vector viewer of the EPS file.
    If you are successful on getting the vector graphic into the PDF, you will find it can not be dealt with as a standard graphic. I am not real good with the vector graphics that get into the PDF in terms of touchup and such.

  • Pshop CC -- saving JPG & PNG file size bloat

    Saving JPGs & PNGs from Photoshop CC is creating what I can only describe as a obscene file bloat.  Just recently, what should have been a 7k jpg saved as a 1.1 mb jpg file.  PNGs which should average roughly 100-150k are coming out at 1.3mb.  If I use the "Save for Web", sometimes it gives me the proper sized images.
    I have noticed this on 2 computers --- one a mac & one windows with completely different file sets.  So it is not an issue of my OS, the original files or anything specific to one particular common item.
    FYI -- Doing the same thing with pshop cs6, I get the proper file sizes. 
    I have included a sample image here.  This image is a straight out "save" from pshop CC  -- it is 1.1mb.  However, when I saved the same image as a JPG in pshop cs6, it was 7k.
    Is anyone else experiencing this issue?

    Haven't had a PNG or JPG go wacky here in that way so far...
    I think the issue is revealed by looking in File - File Info in the Raw Data section.  I don't know why, but there are a huge number of <rdf:li> XML elements showing up there with hex values in them.  I don't know what that means, exactly, but I believe the accumulation of that metadata explains the size increase.
    Do any of the terms you see in the raw metadata mean anything to you?  Do you have 3rd party plug-ins that could be responsible for this?
    -Noel

Maybe you are looking for

  • Latest iTunes software 10.5.1 will not load.

    Software begins to download writing files.  Near completion WARNING window pops up stating iTunes must be closed to complete installation.  Doing so does nothing.  Only option available is to click "Quit Installer" on pop-up warning window which in t

  • SL install won't complete

    I have installed SL and when the install process complete my macbook restarted it has been hanging on the start up screen for over an hour. I have turned it off and left it off for a while and then started it up again but it is still hanging on the s

  • Flow For Cost Center Budget

    Hi,   i need to configure the cost center budget scenario.can anydbody provide me the details on cost center budget...process..points will be assigned. Thanks Sap Guru (He Know's Nothing)

  • Lion reload question

    I am running Lion on my MacBook Pro and it locks up several times a day. I purchased Lion from the App Store. Can I download Lion again and reinstall without having to reload all of my apps?

  • Ipod 30g Video Repair Help

    Alright, I've had my 30gb Video for about 2 years and everything worked fine until recently. About two weeks ago I left my Ipod in my car while I ran into a store (everything was working fine) and when I came back I noticed my Ipod screen was all mes