简体   繁体   English

在Java动态Web项目中找不到图像

[英]Cannot find the image in the java dynamic web project

I have the following problem: 我有以下问题:

I created the servlet which should draw a dynamic graph. 我创建了应该绘制动态图的servlet。 During the drawing process it should fetch the picture from another directory and to draw it upon another image. 在绘制过程中,它应该从另一个目录中获取图片并将其绘制到另一个图像上。 Everything should work fine: 一切都应该正常工作:

try {
            BufferedImage temp = ImageIO.read(new File("image/arrow.png"));
            tempIm = temp.getScaledInstance(55, 55, Image.SCALE_SMOOTH);
        } catch (IOException e) {

            e.printStackTrace();

        }

But it prints the following: 但是它显示以下内容:

SEVERE: javax.imageio.IIOException: Can't read input file! at javax.imageio.ImageIO.read(ImageIO.java:1275) at CertificateDraw.doGet(CertificateDraw.java:36)

I tried to change the path of the File object in all possible ways it just gives the same problem even though the part of the image is still sent to the browser. 我试图以所有可能的方式更改File对象的路径,即使图像的一部分仍被发送到浏览器,它也只会带来相同的问题。 So the problem is with the ImageIO.read part - how can I find why it does not load the image?! 所以问题出在ImageIO.read部分-我如何找到为什么它不加载图像?

I am working in Eclipse - servlet is in the src folder. 我正在Eclipse中工作-servlet在src文件夹中。 The image is in "image" folder under the rot directory "WebContent". 该图像位于rot目录“ WebContent”下的“ image”文件夹中。

Relative paths in java.io.File are relative to the current working directory (CWD). java.io.File中的相对路径是相对于当前工作目录(CWD)的。 This is the folder which is currently opened when the command is given to start the Java runtime environment (in your case, the webserver). 这是在发出命令以启动Java运行时环境(在您的情况下是Web服务器)时当前打开的文件夹。 When starting the server in Eclipse, this is usually the /bin folder of the project. 在Eclipse中启动服务器时,通常是项目的/bin文件夹。 You can figure this by printing new File(".").getAbsolutePath() . 您可以通过打印new File(".").getAbsolutePath()

But you shouldn't be relying on relative paths in File at all. 但是您根本不应该依赖File中的相对路径。 The CWD is not controllable from inside the code. 不能从代码内部控制CWD。

As it's in the webcontent folder already, just get it by ServletContext#getResourceAsStream() instead. 因为它已经在webcontent文件夹中,所以只需通过ServletContext#getResourceAsStream()来获取它。

InputStream input = getServletContext().getResourceAsStream("/image/arrow.png");
BufferedImage image = ImageIO.read(input);
// ...

Note that the getServletContext() is inherited from the GenericServlet class which the HttpServlet extends from, so you don't need to provide the method yourself. 注意, getServletContext()继承自HttpServlet扩展的GenericServlet类,因此您无需自己提供方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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