執行結果:

GetCheckImage
程式碼:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import javax.imageio.ImageIO;

public class GetCheckImage extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("image/jpeg");
        createImage(response.getOutputStream());
    }

    private void createImage(OutputStream out) throws IOException {

        BufferedImage img = null;
        img = ImageIO.read(new File("C:/A.jpg"));
        img = process(img);

        // encode:
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
        param.setQuality(1.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(img);
    }

    private BufferedImage process(BufferedImage old) {
        int fontSize = 400;
        int w = old.getWidth();
        int h = old.getHeight();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = img.createGraphics();
        g2d.drawImage(old, 0, 0, null);
        g2d.setPaint(Color.RED);
        g2d.setFont(new Font("Serif", Font.BOLD, fontSize));
        String s = "Hello Loli";
        FontMetrics fm = g2d.getFontMetrics();
        int x = img.getWidth() / 2 - fm.stringWidth(s) / 2;
        int y = img.getHeight() / 2 + fontSize / 3;
        g2d.drawString(s, x, y);
        g2d.dispose();
        return img;
    }

}




    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()