1. 程式人生 > >簡單的圖片裁剪服務器

簡單的圖片裁剪服務器

() print rac extend common request comm pri com

自己寫的一個簡單的圖片服務器,可以讀取FastDFS上的圖片,根據參數進行圖片裁剪輸出到前臺

改項目可以上傳圖片到FastDFS,讀取FastDFS上存儲的圖片,前面可以增加Varnish圖片緩存服務器緩解圖片裁剪壓力

使用一個簡單的Servlet實現

package com.imgcut.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import
javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder; //測試URL //http://127.0.0.1/imgcut/imgcut?width=100&height=100&rotate=120&imgUrl=https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png public class ImgCutServlet extends HttpServlet { private static final long serialVersionUID = 1L;
private final String WIDTH = "100"; private final String HEIGHT = "100"; private final String ROTATE = "90"; private final String OUTPUTFORMAT = "png"; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); String width = request.getParameter("width"); String height = request.getParameter("height"); String imgUrl = request.getParameter("imgUrl"); String rotate = request.getParameter("rotate"); String outputFormat = request.getParameter("outputFormat"); InputStream is = null; ServletOutputStream sos = null; int code; try { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(imgUrl); code = client.executeMethod(method); if(200 == code){ is = method.getResponseBodyAsStream(); } sos = response.getOutputStream(); Builder builder = Thumbnails.of(is); //如果沒有設置寬度和高度,使用默認值 if("".equals(width) || width == null){ width = this.WIDTH; } if("".equals(height) || height == null){ height = this.HEIGHT; } builder.size(Integer.parseInt(width), Integer.parseInt(height)); //如果沒有設置旋轉,使用默認值 if("".equals(rotate) || rotate == null){ rotate = this.ROTATE; } builder.rotate(Integer.parseInt(rotate)); //設置輸出格式 if("".equals(outputFormat) || outputFormat == null){ outputFormat = this.OUTPUTFORMAT; } builder.outputFormat(outputFormat); //輸出處理後的圖片 builder.toOutputStream(sos); sos.println(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ response.getWriter().println("項目報錯,請查看日誌!"); } } }

測試效果:

簡單的圖片裁剪服務器