BufferedImage 'null' with ImageIO.read(url)

Hi,
I am trying to display a JSP as an image which can be used in another JSP's img tags.
Here is how I coded image.jsp.
I observed that for 'bmp' image type, image object is 'null'. When I directly open 'bmp' image url in browser, it opens correctly.
<%@ page import = "java.io.*" %>
<%@ page import = "java.awt.image.BufferedImage"%>
<%@ page import = "javax.imageio.ImageIO"%>
<%@ page import = "javax.imageio.spi.IIORegistry"%>
<%@ page import = "java.net.URL"%>
<%@ page import = "java.net.URLEncoder"%>
<%
     try{ 
          String imgUrl = URLEncoder.encode(request.getParameter("imgUrl"));
          imgUrl = imgUrl.replaceAll("%3A",":");
          imgUrl = imgUrl.replaceAll("%2F","/");     
          imgUrl = imgUrl.replaceAll("\\+","%20");     
          String[] urlSplit = imgUrl.split("\\.");          
          String imgTyp = urlSplit[urlSplit.length-1];
          URL url = new URL(imgUrl);
          BufferedImage image = null;
          image = ImageIO.read(url);
          ByteArrayOutputStream bas = new ByteArrayOutputStream();
          ImageIO.write(image,imgTyp, bas);
          byte[] imgData = bas.toByteArray();
          response.setContentType("image/"+imgTyp);
          OutputStream o = response.getOutputStream();
          o.write(imgData);
          o.flush();
          o.close();
    catch (Exception e)
       e.printStackTrace();
    finally{
%>Any idea, why is this happening?
With regards,
Amey

Hi EJP,
Thanks for reply.
I now changed my code to this: -
<%@ page import = "java.io.*" %>
<%@ page import = "java.awt.image.BufferedImage"%>
<%@ page import = "javax.imageio.ImageIO"%>
<%@ page import = "javax.imageio.spi.IIORegistry"%>
<%@ page import = "java.net.URL"%>
<%@ page import = "java.net.URLEncoder"%>
<%@ page import = "com.sap.tc.logging.Location"%>
<%
     Location location = Location.getLocation("AmeyTestPar.imageJSP");
     try{
          String imgUrl = request.getParameter("imgUrl");
          location.fatalT("imgUrl = " + imgUrl);
          String[] urlSplit = imgUrl.split("\\.");          
          String imgTyp = urlSplit[urlSplit.length-1];
          URL url = new URL(imgUrl);
          BufferedImage bufferedImage = ImageIO.read(url);
          OutputStream outputStream = response.getOutputStream();
          response.setContentType("image/"+imgTyp);
          ImageIO.write(bufferedImage,imgTyp, outputStream);
          outputStream.flush();
          outputStream.close();
   }catch (Exception e){  
          location.fatalT("Exception in image.jsp : " + e.getMessage());
         e.printStackTrace();
%>But this is running into 'java.lang.IllegalArgumentException: im == null!" at
jvax.imageio.ImageIO.write(ImageIO.java:1413)
and
jvax.imageio.ImageIO.write(ImageIO.java:1508)
Also, I heard about use of image type plugins in package 'javax.imageio.plugins'.
I added 'jai_imageio-1.1.jar' in build path and inserted 'ImageIO.scanForPlugins()' line in code.
But this didn't help either.
With regards,
Amey

Similar Messages

  • 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();}
    }

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

  • 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

  • Problem with ImageIO.read and ImageReader JPG colors are distorted/wrong

    (Using JDK 1.5)
    ImageIO incorrectly reads some jpg images.
    I have a jpg image that, when read by the ImageIO api, all the colors become reddish.
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                javax.imageio.ImageIO.write( bi, "jpg", new java.io.File("badcolors.jpg") );
                javax.imageio.ImageIO.write( bi, "png", new java.io.File("badcolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }Why is this happening??? My guess is there is a problem with the ImageIO.read ?
    the jpg can be downloaded at http://www.alwaysvip.com/javabug.jpg
    <BufferedImage@11faace: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1ebbfde transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 1691 height = 1269 #numDataElements 3 dataOff[0] = 2>
    I have even tried creating a new buffered image but still have the same problem:
    (suggested by http://forum.java.sun.com/thread.jspa?forumID=20&threadID=665585) "Java Forums - ImageIO: scaling and then saving to JPEG yields wrong colors"
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                java.awt.image.BufferedImage out = new java.awt.image.BufferedImage( bi.getWidth(), bi.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics2D g = out.createGraphics();
                g.drawRenderedImage(bi, null);
                g.dispose();
                javax.imageio.ImageIO.write( out, "jpg", new java.io.File("badcolors.jpg") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }I have used the following which works but does not use the ImageIO api. However, I tried using the ImageIO to write and it worked for writing which leads me to believe there is a problem with the reader.
    (suggested by http://developers.sun.com/solaris/tech_topics/java/articles/awt.html "Server-Side AWT")
            try
                java.awt.Image image = new javax.swing.ImageIcon(java.awt.Toolkit.getDefaultToolkit().getImage("javabug.jpg")).getImage();
                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();
                com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder( new java.io.FileOutputStream( "goodcolors.jpg" ) );
                encoder.encode( bufferedImage );
                javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("goodiocolors.jpg") );
                javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("goodiocolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }BTW, the following does not work either:
                java.util.Iterator readers = javax.imageio.ImageIO.getImageReadersByFormatName( "jpg" );
                javax.imageio.ImageReader reader = ( javax.imageio.ImageReader ) readers.next();
                javax.imageio.stream.ImageInputStream iis = javax.imageio.ImageIO.createImageInputStream( new java.io.File("javabug.jpg") );
                reader.setInput( iis, true );
                java.awt.image.BufferedImage bufferedImage = reader.read( 0 );

    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

  • Intermittent problem with ImageIO reading BMP: Empty Region

    I am using imageIO to read in a bmp file, like this:
          ImageInputStream is = ImageIO.createImageInputStream(imgURL.openStream());
          Iterator<ImageReader> rdrs = ImageIO.getImageReaders(is);
          if (rdrs.hasNext()) {
            ImageReader r = rdrs.next();
            r.setInput(is);
            result = r.read(0);
          }(I use the same code to read in a whole bunch of images of various kinds.) In development, I got an empty image, so I added a wait:
    MediaTracker mt = new MediaTracker(new MyObserver());
        mt.addImage(iconImage, 0);
        try {
          mt.waitForID(0);
        } catch (InterruptedException e) {
        }which seemed to work fine. Except that sometimes, not always, I got a crash:
    java.lang.IllegalArgumentException: Empty region!
         at javax.imageio.ImageReader.computeRegions(Unknown Source)
         at com.sun.imageio.plugins.wbmp.WBMPImageReader.read(Unknown Source)
         at javax.imageio.ImageReader.read(Unknown Source)I got that sometimes in development, but once I produced the production version it started happening all the time!
    Anyone have an idea what's going on??

    That was very close to correct. It seems that the WBMP reader mucks up the input stream before the .ico reader can get to it. The .ico plugin, which is available at [http://www.vdburgh.net/2/f/files/ICOReader/ ] puts out a very nice error message to that effect and suggest using a fresh input stream. So this:
          ImageInputStream is = ImageIO.createImageInputStream(imgURL.openStream());
          Iterator<ImageReader> rdrs = ImageIO.getImageReaders(is);
          while (rdrs.hasNext()) {
            ImageReader r = rdrs.next();
            try {
              r.setInput(is);
              result = r.read(0);
              return result;
            } catch (IllegalArgumentException e) {
              System.out.printf("Bad Image:%s%n", e.getMessage());
              is = ImageIO.createImageInputStream(imgURL.openStream());
          }Does the trick! (So far :)

  • Why is it unable to read URL through Java Applet ?

    I have tried to read an image with ImageIO.read(URL) in JApplet. But it failed to be initialized. Please refer to TEST.java. But if I read the image in MSDOS mode, it works. Please refer to DisplayImage.java. The only difference is Applet and MSDOS mode.
    I am using WindowsXP with j2sdk1.4.1_01 installed.
    //File one: TEST.java
    //Please run in Applet mode
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.net.*;
    public class TEST extends JApplet
         BufferedImage tempimg;
         public void init()
              try
                   tempimg = ImageIO.read(new URL("http", "www.footprint.org.hk", 80, "/newsphotos/N200301270_0.jpg"));
              catch(MalformedURLException murle){}
              catch(IOException ioe){}
              JFrame f = new JFrame("ImageDisplayer");
              f.setSize(new Dimension(550,350));
              f.setVisible(true);
    //End of TEST.java
    //File two: DisplayImage.java
    //Please run in MSDOS mode
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.applet.*;
    import javax.swing.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.net.*;
    public class DisplayImage extends JApplet
         ImagePanel imagePanel;
         public static void main(String[] args) throws MalformedURLException, IOException
              DisplayImage img = new DisplayImage();
              img.init();
         public void init()
              //Display Image
              try
                   imagePanel = new ImagePanel(ImageIO.read(new URL("http", "www.footprint.org.hk", 80, "/newsphotos/N200301270_0.jpg")));
              catch(MalformedURLException murle){}
              catch(IOException ioe){}
    JFrame f = new JFrame("ImageDisplayer");
              f.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              f.getContentPane().add(imagePanel, BorderLayout.CENTER);
              f.setSize(new Dimension(550,350));
              f.setVisible(true);
    class ImagePanel extends JPanel {
    Image image;
    public ImagePanel(Image image) {
    this.image = image;
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    //Draw image at its natural size first.
    g.drawImage(image, 0, 0, this); //85x62 image
    //End of DisplayImage.java

    The security model for applets does not allow them to read from a URL unless it is on the same host the applet was loaded from. If you must do this then you must sign your applet for it to work.

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

  • I can't seem to read any file with ImageIO

    I am a rank beginner with Java, so I use a lot of code snippets I find online, and look every move up in the API docs. However, I am just trying to load a simple gif of png to use as a decoration on a panel, and it never succeeds. I successfully create a File from the file, a little image called line.gif. I use ImageIO exactly as it appears in a hundred simple examples and I get and IOException every time with the cause = "Can't read the file!". I am not even sure whether this means it can't deode the image or can't find the file.
    Here's the trivial code:
    BufferedImage img = null;
    try {
    //String formats[] = ImageIO.getReaderFormatNames();
    File imgFile = new File("line.gif");
    img = ImageIO.read(imgFile );
    The file is in the same directory as my java files, and I see that NetBeans has copied it to the build directory where my classes are being placed. I am sure I am doing something really dumb, but it looks like a blank wall. I hope you can help me because I have already spent a ridiculous amount of time on it.

    Thanks for some excellent advice. The NetBeans IDE confused me and I wasn't understanding where my working directory was, but I just found it before coming online and seeing your answer.
    I have another question at this point. Is it possible to build the images into your jar when you are ready to do put it all together, or do I have to keep them together with the code but outside the jar?

  • Performance of ImageIO.read with jpeg files

    Hi all... I'm pulling my hair out trying to get a seemingly trivial task to work fast in Java. I'm trying to read in a set of jpeg files, and all I really want out of the files (for now) is width and height. The code I'm testing is:
    for(int i = 0; i < fileList.length; i++)
    ImageInputStream iis = ImageIO.createImageInputStream(fileList);
    BufferedImage bi = ImageIO.read(iis);
    The size of the files I'm trying to read varies from between 80k and 150k. Now get this... here's a real shocker for all you jdk1.4.0 fans out there... the ImageIO.read() method takes as long as 4 seconds to read each file! I've got the standard, plain vanilla jdk1.4.0 running on Redhat 7.1, so I'm wondering if this is an issue with the native code method com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(). The reason I think this is the case is two-fold: 1) I ran -Xrunhprof on this app, and a full 20% of the cpu time is spent in that method. Another 15% is spent in sun.awt.color.CMM.cmmColorConvert(). 2) The same code ran against a directory filled with GIF files runs blazingly fast... the first image decoded takes a second or so, but the next few take milliseconds to decode.
    Is there some optimized native code jpeg readers that I perhaps didn't download? The documentation on this site, to put it bluntly, SUCKS. It's impossible to find any information without resorting to multiple searches, so I highly doubt that I've actually installed everything I should have just by downloading the one installation file for linux. (not the RPM, the one that lets you put it where you want to).
    Any hints or outright solutions to getting jpeg files to be read any faster than this? This shouldn't be rocket science... Every application I've ever seen on any platform up until now can run circles around my pitiful 2 lines of code.
    Thanks for your help!

    you see....I use the ImageReader.readAll(pageIndex, defReadParam) to read from page 'm' to 'n'. The overall performance (speed) is ok. But, the thing is, the thing pauses for some 15 secs approx to read the first page. Then on, it is QUITE fast. Now, if I need to read 500 pages, then the efficiency will be good. But for a single page? The 15 secs is be too long. Anyway I am trying to read a tiff file (which is not too resolute). Guess the first call does smells the ecnoding format to prepare for decoding, etc...But what I want to know is, is there a way to bring down this time. If not, is there any other way to read a tiff page more efficiently? Actually I need to read some pages & write them to a stream...thats all.

  • Firefox can't read any Bookmark that was imported from my PC with file extension .url. Safari reads them fine. Is there a fix, so I can use Firefox instead of Safari? Many thanks if so. I have the latest version of Firefox

    Firefox can't read any Bookmark on my Mac that was imported from my PC with file extension .url. Safari reads them all fine. Is there a fix, so I can use Firefox instead of Safari? Many thanks if so. I have the latest version of Firefox
    == URL of affected sites ==
    http://anysite.url
    == User Agent ==
    Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.22.7 (KHTML, like Gecko) Version/4.0.5 Safari/531.22.7

    Hello JF.
    I don't think that extension is supported. I believe Firefox can only read .json and .html.
    You may want to read this though:
    [http://support.mozilla.com/en-US/kb/Importing+bookmarks+and other data from Safari Importing bookmarks and other data from Safari]

  • ImageIO.read stripping alpha channel

    I've been chasing this one for the last few hours and haven't gotten anywhere.
    I've been trying to load a 32 bit bitmap (I'm using photoshop and I put a gradient on the alpha channel), and no matter what I do, I keep getting a 24 bit image from the api. I could really use some help on this one. This is the toString() of what should be a 32 bit image: BufferedImage@1f44f8a: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 72 height = 72 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    And here's the code I'm using to load the image:
    public Image Fetch(String path) throws CommonException
         BufferedImage image = null;
         try
             image = ImageIO.read(new File(path));
             System.out.println(image.toString());
         catch(IOException ex)
             Error(ex.getMessage());
            return image;
        }Thanks in advance.
    EDIT
    Here's the image I'm using: [http://img.photobucket.com/albums/v461/vaine0/thebitmap.jpg]
    Edited by: Ax.Xaein on Aug 1, 2009 2:03 AM

    I can probably help you, but you need to save the actual 32-bit bmp image on an image hosting sight so I can take a look at it.
    If the image data contained 4 channels of information, but the BMPImageReader used a destination image of only 3 channels, then you would get an IOException complaining that the source bands doesn't match the destination bands.
    And I'm pretty sure the BMPImageReader can read version 4 and version 5 bmp's (the ones that support an alpha channel).
    Are you absolutely sure you have a bmp with an alpha channel? Not many applications support writing v4 and v5 BMP's.

  • Writing JPEG with ImageIO

    Hi,
    I wanted to do this little tool that:
    1. read any type of image format supported by ImageIO
    2. scaled it down to arbitrary size
    3. wrote the image to the same format it was originally
    I got the pieces together, used ImageIO to read the image, then java.awt.image.AffineTransformOp to scale it down and finally ImageIO again to write it back (I get the ImageWriter with ImageIO.getImageWriter(ImageReader)).
    The problem I got was that AffineTransformOp on Linux (it uses native code) does not want to output anything else then ARGB images. If I read a YCbCr JPEG (the most common JPEG format) and do the AffineTransformOp, I get this ARGB image, which ImageIO will happily write back as an JPEG, but as CMYK JPEG file (which is really rare and not understood by most browsers)... which is not fine because the original was YCbCr.
    The question now is, how do I get AffineTransformOp and ImageIO to play nicely together. Either I have to get AffineTransformOp to output to an BufferedImage that has the same colormodel as that read from the file, or I have to get ImageIO to write any BufferedImage to the exact same format as the original image file.
    For the special case I stated above, I got the program to work by converting the BufferedImage I got from AffineTransformOp to a BufferedImage with RGB colormodel. This, however is not the solution because it assumes that we do not want to output ARGB... Anyway I did it whith the following code (yes, it is horrible).
    // do scaling
    BufferedImage scaled = op.filter(original, null);
    // create a new RGB color model... no alpha
    ColorModel rgbcm = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
    // get the DataBuffer from the scaled version
    DataBuffer db = scaled.getRaster().getDataBuffer();
    // and its dimensions
    int w = scaled.getRaster().getWidth();
    int h = scaled.getRaster().getHeight();
    // band masks for rgb (no alpha)
    int[] bandMasks = new int[] {0x00ff0000,0x0000ff00, 0x000000ff}
    // create new WritableRaster that has the same data, but different sample model
    WritableRaster r = Raster.createPackedRaster(db, w, h, h, bandMasks, null);
    // create a new BufferedImage with the no-alpha ColorModel and the raster
    // with no-alpha SampleModel
    BufferedImage rgbimg = new BufferedImage(rgbcm,r, scaled.isAlphaPremultiplied(), null);
    My second question is, if I have to do this, is there any simpler way?

    I just did a project similar to this actually, so you're in luck! My project was doing image compression rather than resizing, but the IO is the same. I used PixelGrabber to get the pixels, then created my new image in a BufferedImage just like you did (so you can keep all your reading and image creation the same since you seemed to use a BufferedImage also).
    Once you have your BufferedImage, it's blazingly simple. There is a JPEGCodec package that is included in the JDK. It's not compiled though. but, if you open up the ZIP file that has the sources in it (it's copied to your java home directory, called "src.zip"), you can get all the sources you needed. In that package there are 2 classes that I used: JPEGCodec and JPEGImageEncoder. It works like follows:BufferedImage bi;
    OutputStream os;
    // create and fill your buffered image and instantiate your output stream (I used a FileOutputStream for obvious reasons).
    JPEGImageEncoder jie = JPEGCodec.createJPEGEncoder(os);
    jie.encode(bi); And that's it! The package does the rest! Let me know if you have any troubles with it.

  • Jpeg encoding with imageio - pink distortion problem

    Hello, I am using the imageio classes to scale down jpg images (for thumbnails) and write them to a file. On most images, everything works perfectly. On some images, however, the resulting thumbnail image has a strange pink coloration to the whole picture. Does anyone have any ideas as to why this would happen? The code I am using is below. I thank anyone that takes the time to read this and hope someone can help.
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.IndexColorModel;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageTypeSpecifier;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
    import javax.imageio.stream.ImageOutputStream;
    public class ImageResizer
         private static final int THUMBNAIL_MAX = 120;
         private static final int SMALL_MAX = 250;
         private static final int LARGE_MAX = 575;
         private static final int LARGE_THRESHOLD = 425;
         BufferedImage inImage;
         int width;
         int height;
         private static JPEGImageWriteParam params;
         static {
              JPEGImageWriteParam params = new JPEGImageWriteParam(null);
              params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
              params.setCompressionQuality(0.8f);
              params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
              params.setDestinationType(
                   new ImageTypeSpecifier(IndexColorModel.getRGBdefault(),
                   IndexColorModel.getRGBdefault().createCompatibleSampleModel(16,16)));
         public ImageResizer(byte[] image, long id) throws IOException
              inImage = ImageIO.read(new ByteArrayInputStream(image));
              width = inImage.getWidth(null);
              height = inImage.getHeight(null);
         public void makeSmallImage (File outputFile) throws IOException {
              resizeImage(120, outputFile);
         private void resizeImage (int maxDim, File file) throws IOException {
              double scale = maxDim / (double) height;
              if (width > height) scale = maxDim / (double) width;
              int scaledWidth = (int)(scale * width);
              int scaledHeight = (int)(scale * height);
              BufferedImage outImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
              AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
              AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
              // Paint image.
              Graphics2D g2d = outImage.createGraphics();
              g2d.drawImage(inImage, op, 0, 0);
              g2d.dispose();
              // write the image out
              ImageOutputStream ios = null;
              try {
                   ios = ImageIO.createImageOutputStream(file);
                   ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("jpg").next();
                   writer.setOutput(ios);
                   writer.write(null, new IIOImage(outImage, null, null), params);
                   writer.dispose();
              catch (IOException e) {
                   System.out.println("cought IOException while writing " +
                   file.getPath());
              finally {
                   if (null != ios) ios.close();
    }

    I am having the same problem with jpegs.
    The strange thing is that this only happends with the same exact code on OS X, while it never happens on any windows machine.
    I have tried using the the ImageIO classes, and a class I got off of this board a while back; however when using this class on an OS X machine, encoding takes a really long time and gives the pink distortion.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.*;
    import com.sun.image.codec.jpeg.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.geom.*;
    public class ImageUtils {
         private static JPEGImageEncoder encoder = null;
         private static FileOutputStream fileStream = null;
         public static BufferedImage createComponentImage(Component component)
              BufferedImage image = (BufferedImage)component.createImage(component.getWidth(),component.getHeight());
              Graphics graphics = image.getGraphics();
              if(graphics != null) { component.paintAll(graphics); }
              return image;
         public static void encodeImage(BufferedImage image, File file) throws IOException
              fileStream = new FileOutputStream(file);
              JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
              encoder = JPEGCodec.createJPEGEncoder(fileStream);
              encoder.encode(image,encodeParam);
    }use it like this:
    File file = new File("ImageTest.jpg");
    image = ImageUtils.createComponentImage(imageCanvas);
    ImageUtils.encodeImage(image,file);

Maybe you are looking for

  • HT4366 ATV2

    The HDMI port on my television is broke and unfortunately it only has one.  I tried to connect the ATV2 via an HDMI to VGA cable, but when I change the input on the tv to HDMI/DVI, I get the 'No Signal' message.  I've also tried the RGB-DTV input wit

  • Custom Label Printing - Print position creeps up and across labels

    Hello I am using VS 2010 and have updated to SP4 for Crystal Reports I used the custom size option to make a label report. The built in options for label sheets do not match the labels that I have I made a label report for 3 columns and 8 rows using

  • How to supress the Volumes folder?

    A few days ago I've created a new account in my Mac and from this time now a Volumes folder appears next to Users, System, Lybray and Applications folders. Now, I'm only using one only account but the Volumes folder still appears. Is there any way to

  • Google Toolber does not work with Firefox 4

    I just downloaded Firefox 4 and Google Toolbar does not work. I removed and re-downloaded it and it still does not work. I can't even uninstall via the wrench. Is there a version of toolbar that works with Firefox 4?

  • Symtex error in program CL_RSR_RRKO_PARTITION and form CHECK_QCUBE-01-

    Hello Guru, I am getting the following error while doing any changes in a workbook in Bex analyzer: An error occured in the communication with BW server. Program error in class SAPMSSY1 method : UNCAUGHT_EXCEPTION Symtex error in program CL_RSR_RRKO_