📄 imagehandlerservlet.java
字号:
package org.sunxin.lesson.jsp.ch22;
import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import com.sun.image.codec.jpeg.*;
public class ImageHandlerServlet extends HttpServlet
{
private DataSource ds=null;
public void init() throws ServletException
{
try
{
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/bookstore");
}
catch (NamingException ex)
{
System.err.println(ex);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
conn = ds.getConnection();
pstmt = conn.prepareStatement(
"select data from uploadfile where id=?");
pstmt.setInt(1,5);
rs = pstmt.executeQuery();
if(rs.next())
{
InputStream is=rs.getBinaryStream(1);
//通过JPEG图像数据输入流创建JPEG数据流解码器。
JPEGImageDecoder jpegDecoder=JPEGCodec.createJPEGDecoder(is);
//解码当前的JPEG数据流,返回BufferedImage对象。
BufferedImage buffImg=jpegDecoder.decodeAsBufferedImage();
//得到Graphics对象,用于在BufferedImage对象上绘图和输出文字。
Graphics g=buffImg.getGraphics();
//创建ImageIcon对象,logo.gif作为水印图片。
ImageIcon imgIcon=new ImageIcon("F:/JSPLesson/logo.gif");
//得到Image对象。
Image img=imgIcon.getImage();
//将水印绘制到图片上。
g.drawImage(img,80,80,null);
//设置图形上下文的当前颜色为红色。
g.setColor(Color.RED);
//创建新的字体。
Font font = new Font("Courier New",Font.BOLD,20);
//设置图形上下文的字体为指定的字体。
g.setFont(font);
//在图片上绘制文字,文字的颜色为图形上下文的当前颜色,即红色。
g.drawString("http://www.sunxin.org",10,20);
//释放图形上下文使用的系统资源。
g.dispose();
response.setContentType("image/jpeg");
ServletOutputStream sos=response.getOutputStream();
//创建JPEG图像编码器,用于编码内存中的图像数据到JPEG数据输出流。
JPEGImageEncoder jpgEncoder=JPEGCodec.createJPEGEncoder(sos);
//编码BufferedImage对象到JPEG数据输出流。
jpgEncoder.encode(buffImg);
is.close();
sos.close();
}
}
catch (SQLException ex)
{
System.err.println(ex);
}
finally
{
if(rs!=null)
{
try
{
rs.close();
}
catch (SQLException e)
{
System.err.println(e);
}
rs = null;
}
if (pstmt != null)
{
try
{
pstmt.close();
}
catch (SQLException e)
{
System.err.println(e);
}
pstmt = null;
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException e)
{
System.err.println(e);
}
conn = null;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -