?? 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 + -