javax.imageio.IIOException:无法读取Servlet中的输入文件

时间:2017-12-12 07:15:15

标签: java servlets

我正在比较我存储在项目中的pic文件夹中的两张图像

在编译期间我得到 IOException 我尝试了之前的所有解决方案,但仍然无法正常工作 请帮我解决这个错误 在这个项目中,我正在使用servlet页面

这是我的Servlet方法

 BufferedImage imgA = null;
 BufferedImage imgB = null;
 String Filepath = new String();

File fileA = new File("pic/image2.jpg");
File fileB = new File("pic/image2.jpg");

for(int i=0 ;i<list.size();i++)
{

Filepath = list.get(i).getImagepath();
try
{

    imgA = ImageIO.read(fileA);
    imgB = ImageIO.read(fileB);
}
catch (IOException e)
{
    System.out.println(e);
}


int width1 = imgA.getWidth();
int width2 = imgB.getWidth();
int height1 = imgA.getHeight();
int height2 = imgB.getHeight();

if ((width1 != width2) || (height1 != height2))
    System.out.println("Error: Images dimensions"+
                                     " mismatch");
else
{
    long difference = 0;
    for (int y = 0; y < height1; y++)
    {
        for (int x = 0; x < width1; x++)
        {
            int rgbA = imgA.getRGB(x, y);
            int rgbB = imgB.getRGB(x, y);
            int redA = (rgbA >> 16) & 0xff;
            int greenA = (rgbA >> 8) & 0xff;
            int blueA = (rgbA) & 0xff;
            int redB = (rgbB >> 16) & 0xff;
            int greenB = (rgbB >> 8) & 0xff;
            int blueB = (rgbB) & 0xff;
            difference += Math.abs(redA - redB);
            difference += Math.abs(greenA - greenB);
            difference += Math.abs(blueA - blueB);
        }
    }

    double total_pixels = width1 * height1 * 3;

    double avg_different_pixels = difference / total_pixels;

    double percentage = (avg_different_pixels / 255) * 100;

    System.out.println("Difference Percentage-->" +
                                        percentage);

}
}

错误控制台提供

javax.imageio.IIOException: Can't read input file!
Dec 12, 2017 12:26:30 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [services.CompareImage] in context with path [/JavaCvServlet] threw exception

1 个答案:

答案 0 :(得分:1)

你应该尝试获取如下文件

File fileA = new File(getServletContext().getRealPath("pic/image2.jpg"));
File fileB = new File(getServletContext().getRealPath("pic/image2.jpg"));