我已经创建了代码但是错误说“javax.imageio.IIOException:无法读取输入文件!”。请帮忙解决。
<%@ page language="java" contentType="text/html" import="java.awt.AlphaComposite,java.awt.Color,java.awt.Font,
java.awt.Graphics,java.awt.Graphics2D,java.awt.Image,java.awt.image.BufferedImage,java.io.File,java.io.FileOutputStream,
javax.imageio.ImageIO,javax.swing.ImageIcon,com.sun.image.codec.jpeg.JPEGCodec,com.sun.image.codec.jpeg.JPEGEncodeParam,
com.sun.image.codec.jpeg.JPEGImageEncoder" %>
<%
try
{
Font font;
File _file = new File("images/1.jpg");
Image src = ImageIO.read(_file);
int width = src.getWidth(null);
int height = src.getHeight(null);
System.out.println("X = "+width+" and Y = "+height);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
g.setColor(Color.red);
g.setFont(new Font("Verdana", Font.BOLD, 20));
g.drawString("www.somelink.com", 5, height - (new Font("Arial", Font.BOLD, 20)).getSize() / 2 - 5);
g.dispose();
FileOutputStream fout = new FileOutputStream("after.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fout);
encoder.encode(image);
fout.close();
} catch (Exception ee)
{
out.println("Error Occurred : "+ee);
}
%>
我无法解决此抛出的异常。
答案 0 :(得分:0)
与控制台程序不同,Java中的Web应用程序不承担工作目录。你必须给它一个完整的路径。在JSP中,您可以使用application.getRealPath("/")
来获取应用程序的基本路径:
File _file = new File(application.getRealPath("/")+"images/1.jpg");