How to set .TIF image to ImageIcon in java?
Asked Answered
T

3

2

Could anyone suggest me how to store .TIF formatted image to ImageIcon and add this image to list model? I tried this but gives me java.lang.NullPointerException.

  public static void main(String[] args) throws Exception {
    String path = "C:\\project\\aimages";
    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();
    DefaultListModel listModel = new DefaultListModel();
    System.out.println("listOfFiles.length="+listOfFiles.length);
    int count = 0;
    for (int i = 0; i < listOfFiles.length; i++) {
        //System.out.println("check path"+listOfFiles[i]);
        String name = listOfFiles[i].toString();
         System.out.println("name"+name);
        // load only JPEGs
        if (name.endsWith("jpg") || name.endsWith("JPG")|| name.endsWith("tif") || name.endsWith("TIF")) {
            if(name.endsWith("tif") || name.endsWith("TIF"))
            { 
                BufferedImage image = ImageIO.read(listOfFiles[i]);
           BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
              ImageIcon ii = new ImageIcon(image);
                    Image img1 = ii.getImage();
                Image newimg = img1.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
                   ImageIcon newIcon = new ImageIcon(img1);
                  listModel.add(count++, newIcon);
            }
            else
            {
              ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
              Image img1 = ii.getImage();
              Image newimg = img1.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
              ImageIcon newIcon = new ImageIcon(newimg);
             listModel.add(count++, newIcon);
            }
        }
    }
    JList p2 = new JList(listModel);

    }
     }

here i had edited my code and this is my error msg Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.(ImageIcon.java:228) at ListImage1.main(ListImage1.java:48)

Tootsy answered 9/3, 2012 at 13:0 Comment(8)
can you send the error message? Is it related with this line BufferedImage image = ImageIO.read(listOfFiles[i]); ? maybe listOfFiles[i] is pointing to a non-existing path while you expect it to point the image path, huh? debug it.Natka
Please tell us where the NPE is thrown and check what is null.Dominickdominie
Additionally: you don't use image other than for querying the dimensions, thus convertedImage would not contain any actual image information. You're missing the conversion here.Dominickdominie
well i am cheking the path it is get stored in the listofFiles[i] i am cheking like this String name = listOfFiles[i].toString(); System.out.println("name"+name); this is my error msg Exception in thread "main" java.lang.NullPointerException at ListImage1.main(ListImage1.java:47)Tootsy
@Ashish Donvir please edit your question and post your full exception stack trace and ListImage1 code.Milden
Hello please refer my edited new code i with exat error messageTootsy
Hello i had edited my code with exact error message please refer it and suggest me something.Tootsy
+1, this question added something to my knowledge today :-)Branch
G
5

If the TIFF is an application resource, probably better to convert it to JPG or PNG.

OTOH, I believe that JAI offers support for reading TIFF.

Greenes answered 9/3, 2012 at 15:14 Comment(1)
+1 for JAI link, and the Java Docs referred by me, includes a sample program.Branch
B
5

Seems like .TIF is not supported by ImageIO. Do have a look at the formats supported by ImageIO by using ImageIO.getReaderFormatNames(), when i did that I got the output as :

C:\Mine\JAVA\J2SE\classes>java TestBorder
jpg
BMP
bmp
JPG
jpeg
wbmp
png
JPEG
PNG
WBMP
GIF
gif
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at javax.swing.ImageIcon.<init>(ImageIcon.java:228)
        at TestBorder.createAndDisplayGUI(TestBorder.java:34)
        at TestBorder.access$100(TestBorder.java:6)
        at TestBorder$1.run(TestBorder.java:55)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
        at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
        at java.awt.EventQueue.access$000(EventQueue.java:101)
        at java.awt.EventQueue$3.run(EventQueue.java:666)
        at java.awt.EventQueue$3.run(EventQueue.java:664)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

And this is the program I tried it upon :

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;

public class TestBorder extends JPanel
{
    private static TestBorder testBorder;
    public TestBorder()
    {       
    }

    private static void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("FRAME");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        testBorder.setBackground(Color.BLUE);

        java.net.URL url = testBorder.getClass().getResource("/image/MARBLES.TIF");
        BufferedImage image = null;
        try
        {
             image = ImageIO.read(url);
             String[] formatNames = ImageIO.getReaderFormatNames();
             for (String s: formatNames)
                System.out.println(s);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        ImageIcon imageIcon = new ImageIcon(image);
        JLabel label = new JLabel(imageIcon);
        testBorder.add(label);

        frame.add(testBorder, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public Dimension getPreferredSize()
    {
        return (new Dimension(300, 300));
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                testBorder = new TestBorder();
                createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

Image for Question Here is the Image that I am using : MARBLES.TIF, do click MARBLES.TIF on that link.

Moreover have a look at what Java Docs have to say for this. Hopefully you might be able to find something useful there.

Branch answered 9/3, 2012 at 14:13 Comment(9)
Deleted the Image since I can only keep .jpg images on StackOverflow, so shifted that to my site for download.Branch
@mKorbel : Actually when i keep that picture on stackoverflow, they convert it to jpg automatically I guess. I will keep it again see, when you download, you can download only .jpg from that :(Branch
@AshishDonvir : I had provided a link to Java Docs at the end, do read that they have something to say about TIFF thingy.Branch
well having TIF image is not a problem i already have few images with tif format i just need to load tif image somehowTootsy
You found the link I was looking for, the 'Supported Formats' for JAI! When I arrived at the thread, lazily did a find on 'JAI' and when it wasn't (found), I thought nobody had mentioned it. ;)Greenes
hello i downloaded jai 1.1 all the files(jdk,jre,lib) then i installed them one by one. though when i am iporting this one it says such package doesnot exists import javax.media.jai.NullOpImage; import javax.media.jai.OpImage; import com.sun.media.jai.codec.SeekableStream; even its not alllowing me to use this **SeekableStream s = new 'FileSeekableStream(file); ** Ashish Donvir 19 mins agoTootsy
@AshishDonvir : As I ran through the documentation and Project History it appeared that whatever support those projects seems to provide, it has been ceased, since those projects have never been updated for last three four years. So, the best bet according to me, is to convert the images to .jpg or .png, that is supported by Java, in mostly every component of Swing, instead of using .TIFF and ran into various problems at one time or the other.Branch
Well Mr. Gagandeep i am developing my application fro the use of doctor where i must have to process tif image without converting them...Tootsy
I just found this link on stackoverflow, do check this link out. Might be it can sort things out for you.Branch
G
5

If the TIFF is an application resource, probably better to convert it to JPG or PNG.

OTOH, I believe that JAI offers support for reading TIFF.

Greenes answered 9/3, 2012 at 15:14 Comment(1)
+1 for JAI link, and the Java Docs referred by me, includes a sample program.Branch
S
2
  • ImageIcon's API says

    public ImageIcon(byte[] imageData)

    Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG. Normally this array is created by reading an image using Class.getResourceAsStream(), but the byte array may also be statically stored in a class. If the resulting image has a "comment" property that is a string, then the string is used as the description of this icon.

    Parameters: imageData - an array of pixels in an image format supported by the AWT Toolkit, such as GIF, JPEG, or (as of 1.3) PNG See Also: Toolkit.createImage(java.lang.String), getDescription(), Image.getProperty(java.lang.String, java.awt.image.ImageObserver)

there nothing such as support for tiff or raw, contents isn't displayable

  • common attribute for Icon and ImageIcon, that don't generating any error or exception,
Scutellation answered 9/3, 2012 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.