代码:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Servlet2 extends HttpServlet {
// 设定输出的类型
private static final String GIF = "image/gif;charset=GB2312";
private static final String JPG = "image/jpeg;charset=GB2312";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*String imagePath = "D:\\1234.gif";*/
String imagePath = this.getServletContext().getRealPath("/img/1234.gif");//获取真实路径
response.reset();
OutputStream output = response.getOutputStream();// 得到输出流
if (imagePath.toLowerCase().endsWith(".jpg"))// 使用编码处理文件流的情况:
{
response.setContentType(JPG);// 设定输出的类型
// 得到图片的真实路径
// 得到图片的文件流
InputStream imageIn = new FileInputStream(new File(imagePath));
// 得到输入的编码器,将文件流进行jpg格式编码
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
// 得到编码后的图片对象
BufferedImage image = decoder.decodeAsBufferedImage();
// 得到输出的编码器
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(image);// 对图片进行输出编码
imageIn.close();// 关闭文件流
}
if (imagePath.toLowerCase().endsWith(".gif"))// 不使用编码处理文件流的情况:
{
response.setContentType(GIF);
File file = new File(imagePath);
FileInputStream fis = new FileInputStream(file);
ServletOutputStream sos = response.getOutputStream();
byte[] b = new byte[1024];
int n;
int l = 0;
while ((n = fis.read(b)) != -1) {
l = l + n;
sos.write(b, 0, n);
}
response.setContentLength(l);
fis.close();
sos.close();
}
output.close();
}
}