Corrupted images using ImageIO.read.

I have looked around and it seems to be a lot of confusion about the point that the corruption occurs. After trying a lot of thing I simplified it to the following code:
final BufferedImage bimg = ImageIO.read(file);
JComponent mC = new JComponent() {
public void paint(Graphics c) {
c.drawImage(bimg, 0, 0, null, null);
super.paint(c);
JFrame ff = new JFrame(file.getName());
ff.add(mC);
ff.setVisible(true);
ff.pack();
ff.setSize(800, 600);
ff.validate();Which as I understand means that the corruption happens at read time.
#Image formats:gif,jpeg
#Result:
Some read ok
Some read half ok/half corrupted (top screen ok/bottom corrupted)
Some read with overlaying corruption (ie. the image layers are out of place)
#JVM
1.4.2
Java 6 (latest as of 8/6/2007)
#IDE
RAD (IBM Eclipse)
Thank you

Consider this closed for now. Big portion of my data was corrupted on load time.
Cheers

Similar Messages

  • JPEG file reading wierd bug using ImageIO.read and buffer strategy

    OK I have a slightly (!) bizzare problem. I have a program in Java 1.5.0 /5.0 which is fundamentally using a full screen exclusive mode window to display images loaded from files using ImageIO.read(file). I am getting the graphics context of the buffer strategy used on the FSEM window, and then drawing onto that the image that I have loaded using graphics.drawImage(ImageObj, 0,0, null).
    Now ordinarily this works fine, but I have (after much head scratching) discovered that certain specific jpeg images cause me problems. If I load one of these jpeg images, then it loads in with ImageIO.read fine and I get no errors, but the program locks up on the drawImage(ImageObj, 0,0,null) command in the rendering engine. It doesn't crash, but the CPU usage goes to 100% and stays there, and the method never returns. The image is never displayed on screen obviously, as the program never gets to call bufferStrategy.show() for these images. I have to forcibly terminate the VM to get out of the program.
    Does anyone know what is going on here? Is there some extraneous meta data in the dodgy jpeg files that is doing this? I don't know what 'extras' you can have stored on a jpeg that would cause this behaviour, and I don't know what restrictions there are in the jpeg file reader in Java.
    Its not a major bother to me (now I figured out whats causing it!), as I can just resave a duff jpeg in my image editing app and it will work fine. I just don't know whether I should submit it as a bug or not, and also I thought it would be useful for others to know of this strange behaviour - if I had known about it I would have saved myself about 8 hours!
    Thanks
    Alex

    Oh I forgot to add - I am resizing the images to the screen size using
    Image.getScaledInstance(deviceBounds.width,
    deviceBounds.height,
    Image.SCALE_AREA_AVERAGING);
    and then drawing the scaled image onto the graphics context.

  • Converting images using ImageIO

    hello all,
    I am in need of help asap.
    Does anyone know how to convert images from jpg/gif to PNG format using Imageiio? I will be very grateful if u can pass this information on to me. I need to convert the images on a server side and send the png image to a mobile (j2me) client.
    Please respond to this if you have ideas on this.
    cheers
    cp

    quite simple.
    for example, you got abc.gif , want to convert to jpp
    BufferedImage bi = ImageIO.read(new File("abc.gif"));
    ImageIO.write(bi, "jpg", new File("abc.jpg"));

  • Creating a PDF from an image using Adobe Reader 9.0

    Hi, I've converted a bitmap image to Adobe PDF using Adobe Reader 9.0. I was able to open and read the file but not to modify it. The resulting file ended up being password protected. I do not have a password. I am using Adobe Acrobat X. Can you help?

    I used an application called Bloomberg (feed with investment info) from where I was offered to convert an image into a PDF to save it. The laptop on that station is loaded with Acrobat Reader 9.0.

  • JPEG image decode error with ImageIO.read() method

    Environment: Linux 64-bit, JDK 1.6.0_14 amd64, JAI 1.1.3 amd64
    When I tried to read this image http://farm4.static.flickr.com/3655/3591243423_a258d87ea6.jpg as URL or just the image 3591243423_a258d87ea6.jpg as a local file using ImageIO.read(URL), ImageIO.read(InputStream) or ImageIO.read(String), I got this exception:
    Caused by: java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match
            at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:460)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1102)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1070)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:885)
            at javax.imageio.ImageIO.read(ImageIO.java:1422)
            at javax.imageio.ImageIO.read(ImageIO.java:1326)This can be fixed by adding the jai-imageio-1.1 extension( and recent daily builds too). However, that package is not stable, with memory corruption problem from time to time indicated by this:
    *** glibc detected *** /usr/java/jdk1.6.0_13/bin/java: malloc(): memory corruption: 0x000000004d73a3a0 ***Another way to overcome this is using JAI.create("URL", url) or JAI.create("fileload", file) API, which can decode the image but unfortunately the performance is much worse than the ImageIO.read method. So I compromised by using ImageIO.read first and on exception using JAI APIs on the occasional problem image, which looks ugly.
    What would be a better way of handling this?

    Environment: Linux 64-bit, JDK 1.6.0_14 amd64, JAI 1.1.3 amd64
    When I tried to read this image http://farm4.static.flickr.com/3655/3591243423_a258d87ea6.jpg as URL or just the image 3591243423_a258d87ea6.jpg as a local file using ImageIO.read(URL), ImageIO.read(InputStream) or ImageIO.read(String), I got this exception:
    Caused by: java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match
            at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:460)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1102)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1070)
            at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:885)
            at javax.imageio.ImageIO.read(ImageIO.java:1422)
            at javax.imageio.ImageIO.read(ImageIO.java:1326)This can be fixed by adding the jai-imageio-1.1 extension( and recent daily builds too). However, that package is not stable, with memory corruption problem from time to time indicated by this:
    *** glibc detected *** /usr/java/jdk1.6.0_13/bin/java: malloc(): memory corruption: 0x000000004d73a3a0 ***Another way to overcome this is using JAI.create("URL", url) or JAI.create("fileload", file) API, which can decode the image but unfortunately the performance is much worse than the ImageIO.read method. So I compromised by using ImageIO.read first and on exception using JAI APIs on the occasional problem image, which looks ugly.
    What would be a better way of handling this?

  • How many images per sec can I get from ImageIO.read(url) ??????

    Hello,
    In my program I read images from a url...I'm wondering how many images I can get with ImageIO.read(url) per second..
    Hereby is the code that I'm using:
    import java.awt.*; //Contains all of the classes for creating user interfaces and for painting graphics and images
    import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
    import java.awt.image.*;//Provides classes for creating and modifying images
    import java.io.*;//Provides for system input and output through data streams, serialization and the file system
    import java.net.URL;
    import javax.imageio.*;//The main package of the Java Image I/O API.
    import javax.swing.*;//Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
    import java.text.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class getPic extends Component{
    private BufferedImage img;
        static int n=0;
        private URL url;
        private DateFormat dateFormat;
        private Date date;
        private String s;
        private String str1= ".jpeg";
        private String str2="C:\\Users\\";
        private String str3;
        private String str4;
          public getPic() {
         try {
                  url = new URL("http://"); //a url that gives a real-time image
                  img = ImageIO.read(url);
                } catch (IOException e) {
               System.err.println("Unable to read file");
    public void savePic(){
    try{
    n++;
    str3=str2.concat(Integer.toString(n-1));
                        str4=str3.concat(str1);
                        ImageIO.write(img, "jpeg" , new File(str4));
                    } catch(IOException e) {
                      System.err.println("Unable to output results");
    @Override
        public Dimension getPreferredSize() {
            if (img == null) {
               return new Dimension(100,100);
            } else {
               return new Dimension(img.getWidth(), img.getHeight());
        @Override
          public void paint(Graphics g) {  //http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Paint.html
            g.drawImage(img, 10, 10, null);//http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics.html
        public static void main(String[] args) throws IOException {
           JFrame f = new JFrame(" Image without processing!!");
           f.addWindowListener(new WindowAdapter(){//http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/WindowListener.html
                @Override
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
        int i=0;
        for( ; ; ){
            i++;
            getPic pi = new getPic();
            pi.savePic();
            f.add(pi);
            f.pack();  //Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
            f.setVisible(true);
         try
            Thread.sleep(1000);
            }catch (InterruptedException ie)
            System.out.println(ie.getMessage());
    }Thank you in advance for your answers
    Joan

    Finally I solved my problem(getting as many images as possible from a url infinitely) using the above code:
    import java.net.*;
    import java.io.*;
    public class UserApplication {
        private static int n=0;
        String url;
      public void UserApplication(){
        public static void main(String[] args) throws Exception {
            UserApplication app= new UserApplication();
            for(;;){
            app.urlStr();
        private void urlStr(){
            try{
                url= "http://mplamplampla/frame.php/";
                HttpURLConnection con=(HttpURLConnection) ((new URL(url).openConnection()));
                BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream("C:\\Users\\mpla\\Desktop\\" + n + ".jpeg"));
                con.setDoInput(true);
                con.setDoOutput(false);
                con.setRequestMethod("GET");
                BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                int bt = 0;
                byte[] buffer = new byte[4096];
                while ((bt = in.read(buffer, 0, 4096)) > -1) {
                  out.write(buffer, 0, bt);
                in.close();
                out.close();
                System.out.println("Image " + n + " saved");
                n++;
                } catch (Exception e) {e.printStackTrace();}
    }

  • Problem with ImageIO.read()

    I have a problem with loading picture from file to variable Image img. Function ImageIO.read(fileIn) return always null pointer (whereas fileIn!=null). I'm using j2sdk-1_4_2_0. The same problem problem is in WindowsXP SP2 and Fedora 3 64bit.
    Here is code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import java.io.*;
    public class Converter extends JPanel implements ActionListener {
    JPanel mainPanel, info1Panel,info2Panel,convertionPanel, fSizePanel,displayPanel;
    JCheckBox enableConvertion;
    JButton selectFile,doIt,close;
    JRadioButton size1,size2;
    ButtonGroup sizeGroup;
    ImageIcon imagePrev;
    JRadioButton[] convertion = new JRadioButton[2];
    Image img;
    JLabel previewLabel;
    JFileChooser fc;
    File fileIn = new File("10.jpg");
    File fileOut;
    public Converter() {
    // Tworzenie paneli
    mainPanel=new JPanel();
    mainPanel.setLayout(null);
    info1Panel=new JPanel();
    info2Panel=new JPanel();
    convertionPanel=new JPanel(new BorderLayout());
    fSizePanel=new JPanel();
    displayPanel= new JPanel();
    //Tworzenie pozostalych elementow
    enableConvertion = new JCheckBox("Enable JPG <-> PNG");
    selectFile = new JButton("Select File");
    doIt = new JButton("Do it!");
    close= new JButton("Close");
    fc = new JFileChooser();
    size1 = new JRadioButton("The same resolution");
    size2= new JRadioButton("Resize image to target size of file");
    JLabel previewLabel = new JLabel();
    ButtonGroup sizeGroup = new ButtonGroup();
    imagePrev= new ImageIcon();
    // proba ulozenia elementow na ramce
    Insets insets = mainPanel.getInsets();
    Dimension size = selectFile.getPreferredSize();
    selectFile.setBounds(15 + insets.left, 15 + insets.top,size.width, size.height);
    doIt.setBounds(15 + insets.left,15+5+ insets.top+size.height,size.width, size.height);
    close.setBounds(15+insets.left,15+2*(5+size.height)+insets.top,size.width,size.height);
    convertionPanel.setBounds(10,150,250,90);
    convertionPanel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder("Convertion"),
    BorderFactory.createEmptyBorder(0,5,5,5)));
    info1Panel.setBounds(150,10,200,140);
    info1Panel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder("Source File Information"),
    BorderFactory.createEmptyBorder(0,5,5,5)));
    info2Panel.setBounds(360,10,200,140);
    info2Panel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder("Target File Information"),
    BorderFactory.createEmptyBorder(0,5,5,5)));
    fSizePanel.setBounds(10, 250, 250, 90);
    fSizePanel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder("File size"),
    BorderFactory.createEmptyBorder(0,5,5,5)));
    fSizePanel.setLayout(new GridLayout(2,0));
    displayPanel.setBounds(270,150,290,190);
    displayPanel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder("Display"),
    BorderFactory.createEmptyBorder(0,5,5,5)));
    previewLabel.setHorizontalAlignment(JLabel.CENTER);
    previewLabel.setVerticalAlignment(JLabel.CENTER);
    previewLabel.setVerticalTextPosition(JLabel.CENTER);
    previewLabel.setHorizontalTextPosition(JLabel.CENTER);
    previewLabel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createLoweredBevelBorder(),
    BorderFactory.createEmptyBorder(5,5,5,5)));
    previewLabel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createEmptyBorder(0,0,10,0),
    previewLabel.getBorder()));
    size1.setSelected(true);
    mainPanel.add(info1Panel);
    mainPanel.add(info2Panel);
    mainPanel.add(convertionPanel);
    mainPanel.add(fSizePanel);
    mainPanel.add(displayPanel);
    //osadzamy w odpowiednich panelach elementy
    mainPanel.add(selectFile);
    mainPanel.add(doIt);
    mainPanel.add(close);
    sizeGroup.add(size1);
    sizeGroup.add(size2);
    fSizePanel.add(size1);
    fSizePanel.add(size2);
    displayPanel.add(previewLabel);
    convertionPanel.add(enableConvertion);
    selectFile.addActionListener(this);
    public void actionPerformed(ActionEvent e) {
    int returnVal = fc.showOpenDialog(Converter.this);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    File fileIn = fc.getSelectedFile();
    JFrame frame1=new JFrame();
    JOptionPane.showMessageDialog(frame1, fileIn.getName());
    if(fileIn==null)
    JFrame frame2 = new JFrame();
    JOptionPane.showMessageDialog(frame2,"FileIN==NULL");
    //############## PROBLEM IS HERE ###########################
    try
    Image img=ImageIO.read(fileIn); // HERE IS THE PROBLEM: img==NULL
    // WHERAS fileIn!=NULL
    }catch (IOException event){}
    if (img==null)
    JFrame frame2 = new JFrame();
    JOptionPane.showMessageDialog(frame2,"img==NULL");
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create a new instance of LunarPhases.
    Converter conv = new Converter();
    //Create and set up the window.
    JFrame convFrame = new JFrame("Conversion JPG <-> PNG");
    convFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    convFrame.setContentPane(conv.mainPanel);
    Insets insets = convFrame.getInsets();
    convFrame.setSize(600 + insets.left + insets.right,400+insets.top + insets.bottom);
    convFrame.setVisible(true);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    //############## PROBLEM IS HERE ###########################
    try {
    Image img=ImageIO.read(fileIn); // HERE IS THE PROBLEM: img==NULL
    // WHERAS fileIn!=NULL
    } catch (IOException event){}
    if (img==null) {
        JFrame frame2 = new JFrame();
        JOptionPane.showMessageDialog(frame2,"img==NULL");
    }1. Please use [code] tags when posting code -- it makes the code more readable.
    2. When posting code, post a minimal example program. You could have filtered
    out all the extraneous GUI code, for example. Remember: the shorter the code, the
    more likely it is a forum member will read it! Posting long runs of code only
    hurts yourself.
    3. All that being said, your problem is a simple oversight: notice that the
    variable "img" in your try block is a local variable, not the field named "img"
    than you test after the try block.
    You should have written:
    try {
        img=ImageIO.read(fileIn);
    } catch (IOException event){
        e.printStackTrace();
    }

  • Problem with ImageIO.read and ImageReader GIF becomes dark

    I am having problems with certain GIF images loading completely dark. I previously had problems with certain JPGs colors being distorted http://forum.java.sun.com/thread.jspa?threadID=713164&tstart=0. This was a problem in an old JDK.
    Here is the code:
                java.awt.image.BufferedImage bufferedImage = javax.imageio.ImageIO.read( new java.io.File("javabug.gif") );
                System.out.println( bufferedImage );
                javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("badcolors.jpg") );
                javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("badcolors.png") );BufferedImage Read is:
    BufferedImage@337838: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@119cca4 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 1536 height = 1152 #numDataElements 3 dataOff[0] = 2
    Here is the GIF
    http://www.alwaysvip.com/javabug.gif
    I am using jdk1.5.0_06
    If I use java.awt.Toolkit.getDefaultToolkit().getImage instead of ImageIO.read, the problem no longer exists.
            java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().getImage( file.toURL() );
            java.awt.MediaTracker mediaTracker = new java.awt.MediaTracker( new java.awt.Container() );
            mediaTracker.addImage( image, 0 );
            mediaTracker.waitForID( 0 );
            java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage( image.getWidth( null ), image.getHeight( null ), java.awt.image.BufferedImage.TYPE_INT_RGB );
            java.awt.Graphics g = bufferedImage.createGraphics();
            g.setColor( java.awt.Color.white );
            g.fillRect( 0, 0, image.getWidth( null ), image.getHeight( null ) );
            g.drawImage( image, 0, 0, null );
            g.dispose();
            javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("goodcolors.jpg") );
            javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("goodcolors.png") );BufferedImage Read is:
    BufferedImage@1bf216a: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 1536 height = 1152 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    Is this another bug in the JDK? Is there a possible workaround where I can still use ImageIO.read?

    I figured out the problem. It was an actual BUG in the JDK!
    The code failed with the following JDKs:
    java version "1.5.0_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)
    Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)
    java version "1.5.0_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
    Java HotSpot(TM) Client VM (build 1.5.0_03-b07, mixed mode)
    The code ran sucessful with this JDK:
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
    If you are using the ImageIO classes, I highly suggest you upgrade to the latest JDK.
    Best,
    Scott

  • Null pointer exception using ImageIO

    Hi all I'm not sure this belongs here or in the applet forum, but if don't belong here I'll move it. Anyway My question is this, I am trying to load an image into an applet before I was just doing this
    public static Image getImage(String filename){
              if (applet == null)
                  return null; // for now
             else
                  return applet.getImage(applet.getDocumentBase(), filename);
         }Since then I've discovered ImageIO and have switched to this
    public static BufferedImage getImage(String filename){
              BufferedImage img = null;
              //File image = new File(filename);
              try{
                   //img = ImageIO.read(applet.getDocumentBase().getClass().getResource(filename));
                   //img = ImageIO.read(image);
                   img = ImageIO.read(ImageHandler.getFile(filename));
              }catch(IOException e){
                   e.printStackTrace();
                   return null;
              return img;Now my problem is that this is giving me a null pointer exception, each of the 3 times I try to load up the img variable I get a NPE and I cannot figure out why. I know the file is where its supposed to be and I know it is not corrupt since it works with the other code. So my question is why am I getting an exception with the second piece of code? Any advice or suggestions are appreciated thanks in advance.

    Well that was part of the problem, thanks for that I didn't catch that at first, but now it just created a new exception in that I'm getting a illegal argument exception saying that the input == null. Here is the entire class I should have posted it in the first place sorry
    import java.applet.Applet;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class ImageHandler {
         static Applet applet = null;
         public static void setApplet(Applet applet){
              ImageHandler.applet = applet;
         public static BufferedImage getImage(String filename){
              BufferedImage img = null;
              if(applet == null){
                   System.out.println("Applet is null");//for testing
                   return null; //for now
              }else{
                   try{
                        img = ImageIO.read(applet.getDocumentBase().getClass().getResource(filename));
                   }catch(IOException e){
                        e.printStackTrace();
                        return null;
                   return img;
    }The applet gets set in another class here:
    ImageHandler.setApplet(this);so unless I'm missing something (obviously I am or I won't be here lol) the applet is not null here is the errors I get again thanks for the help you've already given anymore is appreciated.
    java.lang.IllegalArgumentException: input == null!
         at javax.imageio.ImageIO.read(Unknown Source)
         at ImageHandler.getImage(ImageHandler.java:27)
         at BackgroundImages.<init>(BackgroundImages.java:17)
         at BackGrounds.<init>(BackGrounds.java:17)
         at MainGame.init(MainGame.java:51)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)

  • ImageIo: reading and writing a jpeg corrupts the image

    Sometimes, ImageIo manages to read an image wrong. If I simply read() and write() the
    image without any transformations, the image writtten will have its colors all wrong. The
    output image format here doesn't matter.
    An example image is: http://bram.name/~brama/pics/test.jpg
    And output after reading and writing it: http://bram.name/~brama/pics/test_output.jpg
    Is the image io lib to blame, or is it a broken image? The image displays fine in other programs.
    Message was edited by:
    Bram_A

    Use this code to load the image.
    From my experience it is much more stable and also faster.
    My guess is that the problem is related to the ICC profile embeded in the JPEG.
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new URL("http://www.stack.nl/~brama/pics/imageio.jpg").openStream());
    BufferedImage image = decoder.decodeAsBufferedImage();

  • Reading colour image using raster object and getsample() method

    Hello all,
    I am trying to read a grey image using this code below and it perfectly works:
    File filename = new File("myimage.jpg");
    BufferedImage inputimage = ImageIO.read(filename);
    Raster input = inputimage.getRaster();
    double pixelvalue = input.getSample(xx, yy, 0) ; // to read pixel colour.
    Now:
    what modifications should i do to read a colour image using getsample() method.
    any help, by example if y would.
    Thanks

    The code below
    double pixelvalue = input.getSample(xx, yy, 0) ; // to read pixel colour.actually doesn't obtain the pixel color. It reads a band of the specified pixel. If you are reading a tripple band image (24-bit colored image RGB ) then you have to invoke this method three times for band 0, 1 and 2. The arrangment of them depends on the BufferedImage type.
    In reply of your question, you can use getSamples method, refer to the java API documentation of the BufferedImage class for more info.
    you can also check methods getRGB and setRGB, they used to get/set the entire pixel in range of 0x00000000 to 0x00FFFFFF ( 0x00RRGGBB of image type TYPE_INT_RGB )
    Regards,
    Mohammed M Saleem

  • Writing multiple images to one file using ImageIO

    I am having trouble saving and reading multiple images from to/from one file. Here is the best i can come up with:
    //this is utilizing an ObjectOutputStream because i need to also save some objects to the file
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\images.dat"));
    oos.writeInt(ImageTable.size());
    for(int k = 0; k  < ImageTable.size(); k++)
        ImageIO.write((BufferedImage)ImageTable.get(k), "png", oos);
        oos.flush();
    //////////////////////////read function/////////////////////////
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\images.dat"));
    int size = ois.readInt();
    for(int k = 0; k < size; k++)
        ImageTable.add(ImageIO.read(ois));
    }What it seems to do is read the first image and then place the marker at the end of the file so each consecutive calls to reading the file end up in either null, -1, or an EOF exception (bleh). Does anyone know how i can do this properly?
    The code does run and saves something, although it is hard to tell exactly what it is saving since it is all in png format, it also loads the first image properly.

    Is it possible to pack the different images in one big image?Conversely, some image formats let you store multiple images in a single image file.
    Here's a demo. My results are that I don't have a gif writer, tiff can write sequences (this
    is a well-known tiff property), I can trick (?) jpeg into stroring multiple images and I
    can't get png to work: three images go in, one comes out.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.util.List;
    public class MultiImageTest {
        public static void main(String[] args) throws IOException {
            URL url1 = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            URL url2 = new URL("http://today.java.net/jag/bio/JAG2001small.jpg");
            URL url3 = new URL("http://today.java.net/jag/Image24-small.jpeg");
            BufferedImage[] images = {ImageIO.read(url1), ImageIO.read(url2), ImageIO.read(url3)};
            display(images, "original", 0, 0);
            String[] suffixes = {"gif", "jpeg", "png", "tiff"};
            int x = 30, y = 20;
            for(int j=0; j<suffixes.length; ++j) {
                String suffix = suffixes[j];
                try {
                    writeFile(images, suffix);
                    display(readFile(suffix), suffix, x, y);
                    x += 30;
                    y += 20;
                } catch (Exception e) {
                    System.err.println(suffix + ": " + e.getMessage());
        static void writeFile(BufferedImage[] images, String suffix) throws IOException {
            Iterator ws = ImageIO.getImageWritersBySuffix(suffix);
            if (!ws.hasNext())
                throw new IOException("no writer for: " + suffix);
            ImageWriter w = (ImageWriter) ws.next();
            File file = new File("temp." + suffix);
            file.delete();
            w.setOutput(ImageIO.createImageOutputStream(file));
            if (w.canWriteSequence()) {
                System.out.println("Using writeToSequence for format " + suffix);
                w.prepareWriteSequence(null);
                for(int j=0; j<images.length; ++j)
                    w.writeToSequence(new IIOImage(images[j], null, null), null);
                w.endWriteSequence();
            } else {
                System.out.println("cross fingers for format " + suffix);
                for(int j=0; j<images.length; ++j)
                    w.write(images[j]);
        static BufferedImage[] readFile(String suffix) throws IOException {
            Iterator rs = ImageIO.getImageReadersBySuffix(suffix);
            if (!rs.hasNext())
                throw new IOException("no reader for: " + suffix);
            ImageReader r = (ImageReader) rs.next();
            File file = new File("temp." + suffix);
            if (!file.exists())
                throw new IOException("no file: " + file.getName());
            r.setInput(ImageIO.createImageInputStream(file));
            List images = new ArrayList();
            for(int j=0; true; ++j) {
                try {
                    images.add(r.read(j));
                } catch (IndexOutOfBoundsException e) {
                    break;
            return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
        static void display(BufferedImage[] images, String title, int x, int y) {
            JPanel cp = new JPanel(new GridLayout(1,0));
            for(int j=0; j<images.length; ++j)
                cp.add(new JLabel(new ImageIcon(images[j])));
            JFrame f = new JFrame(title);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(cp));
            f.pack();
            f.setLocation(x, y);
            f.setVisible(true);

  • I am trying to download Firefox 3.6 to use on my Mac OS X version 10.3.9. Three attempts and I continue to get "mounting failed" and "corrupt image". Help please?

    I am trying to download Firefox 3.6 to use on my Mac OS X version 10.3.9. Three attempts and I continue to get "mounting failed" and "corrupt image". Help please?

    Firefox 3.6 requires at least OS X 10.4, the last version of Firefox that worked on OS X 10.3.9 was Firefox 2.0.0.20 which is available from ftp://ftp.mozilla.org/pub/mozilla.org/firefox/releases/2.0.0.20/mac/

  • Tecra M11 - Card reader and corrupt images

    When I put an xD card into the Tecra M11's front slot, the pictures that it downloads are corrupted. When downloading through an external xD card reader (e.g. the camera itself) the images are okay. Here is an example of a corrupted image:
    http://www.flickr.com/photos/jasonjudge/5816195077/in/set-72157604215066892
    Here is the same image downloaded from the camera through USB:
    http://www.flickr.com/photos/jasonjudge/5856376812/in/set-72157626887798337
    Is this a Windows 7 (32 bit) driver problem (I can't find any driver updates in the awful driver website that takes me down numerous blind alleys) or could it be a hardware problem?
    Jason
    PS What is it about this forum that keeps throwing my cursor into the subject box as I'm typing in the message field?

    Hi,
    It is the Olympus xD card that came with the camera. I have never formatted it, and never had any problems using any other card reader.
    I'll try the links again for the driver. What I tend to find happens with the drivers site, is that it identifies my laptop, tells me there is a driver for hardware feature X and my OS, provides me with a link to "download this driver", and when I follow the link it takes me to a much higher level on another Toshiba site where I have to sift through hundreds of drivers for every other model of hardware, none of which are named in a way that makes it easy to identify what I need. For example, it told me there was a wireless LAN driver update recently, then sent me to the site where the drivers are named after the wireless LAN chipset, with about five different chipsets to choose from. Why does it send me to all those choices when it started out knowing everything it needed to know about my model laptop? So, I would not say it is "easy".
    I'll give it another go though.
    -- Jason

  • Using imageio to convert .gif to .jpg gives bad image

    Hi,
    I'm looking at the 1.4 javax.imageio API, and wrote a naive
    program to convert images from one format to another.
    It will read .gif, .jpg or .png and correctly write .gif and .png
    images, but when I try to write a .jpg from a .gif or .png
    the result is very black-looking - actually most of the colour
    is there but changed to a very dark level and red switched to blue
    for example. Presumably there is a reason that this doesn't work,
    or is it a bug? I would've though an exception would be thrown
    if the image types selected were incompatible.
    Also, how does one specify the JPEG quality setting?
    Thanks for any clues,
    Ed
    import javax.imageio.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.image.*;
    public class ImageTest
    public static void main(String[] argv)
    try
    File f1 = new File(argv[0]);
    BufferedImage bi = ImageIO.read(f1);
    System.out.println("Read "+f1+" OK.");
    System.out.println("Image="+bi);
    File f2 = new File(argv[1]);
    String extn = f2.getName();
    extn = extn.substring(extn.lastIndexOf('.')+1);
    ImageIO.write(bi, extn, f2);
    System.out.println("Wrote "+f2+" OK format="+extn);
    catch (Exception ex)
    ex.printStackTrace();

    Interesting, the program works correctly on Windows 2000
    and Solaris Sparc; The .jpg file creating problem only
    occurs on my Solaris x86 machine.
    Ed

Maybe you are looking for

  • Presence of multiref tag in soap response message

    We are having a problem when we try to call a web service in PI. The web services called is provided by an Axis server. We tried to use the plain HTTP protocol in the definition of the communication channel as shown here: Adapter type: SOAP Transport

  • Why can I not get the pages to Print?

    I have been trying to get my taxes to print, but the new Adobe program just keeps trying to save it over and over again.  This is really frustrating!  I have tried to send it to another program and it ends up all jumbled up.  Nothing is worth this fr

  • Google Spyware Alert!

    Hi there, Over the past few days, when searching on google, instead of going to my search results, I often go to an authentication page as apparently my search resembles a spyware something or other (I searched for things like investments, so go figu

  • Sale tax related

    Hi Experts, While releasing billing doc (VF02-Invoice no is 13099358) I am facing following error. Could you please help me on this? Because of this am not able to see accounting document. Diagnosis: No tax items exists for tax code V0 in  a GL accou

  • Change an existing report

    1) I have created a Oracle Report that takes an employee id as a parameter and display the employee details . 2)Now I have been told to create another report that has the same format only difference now is that the report should be generated for all