Read image from another directory

牧云@^-^@ 提交于 2019-11-26 23:41:48

问题


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

回答1:


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"))


来源:https://stackoverflow.com/questions/23478984/read-image-from-another-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!