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 POWERSHELL

以下皆為powershell 安裝的指令 Install-Module Azure OR Install-Module Azure -AllowClobber 更新的指令 先看舊的版本 Get-Module AzureRM -ListAvaila...

Popular Posts