简体   繁体   中英

Read image from another directory

I need to open a image from another directory but the following code doesn't work when I try to put in the whole path name like /Users/Documents/image.dcm .

I am trying to open a dicom image. I am doing this so I can make GUI for this code but I am really stuck. I have tried many things but nothing really seems to work. Any suggestions will be appreciated.

/**
 * This class displays the first frame of a file from any format
 * supported by ImageIO.
 * In the case of DICOM files, stored values are displayed as
 * is, without using Value of Interest or Presentation LUTs.
 */

class Read1 {
    public static void main(String[] s) {
        try {
            //System.out.println(s[0]);
            if (s.length != 1) {
                //System.err.println("Please supply an input file");
                System.exit(1);
            }

            //URL url = Main.class.getResource(s[0]);
            ImageIO.scanForPlugins();
            final BufferedImage bi = ImageIO.read(new File(s[0]));
            if (bi == null) {
                System.err.println("read error");
                System.exit(1);
            }

            JFrame jf = new JFrame();
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            final Rectangle bounds = new Rectangle(0, 0, bi.getWidth(), bi.getHeight());
            JPanel panel = new JPanel() {
                public void paintComponent(Graphics g) {
                    Rectangle r = g.getClipBounds();
                    ((Graphics2D) g).fill(r);
                    if (bounds.intersects(r))
                        g.drawImage(bi, 0, 0, null);
                }
            };
            jf.getContentPane().add(panel);
            panel.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
            jf.pack();
            jf.setVisible(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

You can try any one

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from absolute path
ImageIO.read(new File("E:/SOFTWARE/TrainPIS/res/drawable/c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));

// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))

// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM