JAVA Servlet create image on fly (API直接產生圖形輸出)


* 需求:呼叫API的時候直接透過java graphic api進行產生圖形後輸出
常見於動態產生圖片(浮水印/驗證圖形/)

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;

@WebServlet("/ImageCreator")
public class ImageCreator extends HttpServlet {
private static final long serialVersionUID = 1L;
  private static int FrameWidth=554;
  private static int FrameHeight=900;;
    public ImageCreator() {
        super();
     
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//response.getWriter().append("Served at: ").append(request.getContextPath());
  // set mime type as jpg image
        response.setContentType("image/jpg");
        ServletOutputStream out = response.getOutputStream();

        BufferedImage imageX = new BufferedImage(FrameWidth, FrameHeight, BufferedImage.TYPE_BYTE_INDEXED);

        Graphics2D  g= imageX.createGraphics();
       
   int width=FrameWidth-20;
   int height=FrameHeight-20;


  g.setColor(Color.black);
   g.fillRect(0, 0, FrameWidth, FrameHeight);
 

        g.dispose();


      JPEGCodec.createJPEGEncoder(out).encode(imageX);


    out.close();
}

}


See also :
張貼留言

Featured Post

如何查詢AZURE OPEN 到期日/到期點數

* Azure in Open 就跟易付卡點數一樣 兌換完了需要再一年之內用掉 否則歸零 所以並不是省著用就可以用很久 很多人忽略了這點 注意這裡教的是 OPEN點數(儲值信用點數) 如何查詢合約到期日 AZURE EA 與 AZURE CSP等合約方式 不適用 ...

Popular Posts