Java图片切割
2019-04-15 15:53发布
生成海报
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Pic = (String) request.getParameter("p");
int PointX = Integer.parseInt(request.getParameter("x"));
int PointY = Integer.parseInt(request.getParameter("y"));
int CutWidth = Integer.parseInt(request.getParameter("w"));
int CutHeight = Integer.parseInt(request.getParameter("h"));
// 图片宽度
int PicWidth = Integer.parseInt(request.getParameter("pw"));
// 图片高度
int PicHeight = Integer.parseInt(request.getParameter("ph"));
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
HttpSession session = request.getSession();
String picPath = Pic;
String path = request.getRealPath(picPath);
ServletOutputStream responseOutputStream = response.getOutputStream();
cut(path, responseOutputStream, CutWidth, CutHeight, PointX, PointY,
PicWidth, PicHeight);
// 以下关闭输入流!
responseOutputStream.flush();
responseOutputStream.close();
}
/**
* 图片切割
* @param srcImageFile 图片地址
* @param responseOutputStream servlet输出流
* @param w 切割宽度
* @param h 切割高度
* @param x1 开始x结点(left)
* @param y1 开始y结点(top)
* @param sw 图片宽度
* @param sh 图片高度
*/
public void cut(String srcImageFile,ServletOutputStream responseOutputStream, int w, int h, int x1,
int y1, int sw, int sh) {
try {
// http://localhost:8080/ImpCra/createServlet?p=Sunset.jpg&x=117&y=201&w=61&h=50&pw=300&ph=400
Image img;
ImageFilter cropFilter;
// 读取源图像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
if (sw >= w && sh >= h) {
Image image = bi.getScaledInstance(sw, sh, Image.SCALE_DEFAULT);
// 剪切起始坐标点
int x = x1;
int y = y1;
int destWidth = w; // 切片宽度
int destHeight = h; // 切片高度
// 图片比例
double pw = sw;
double ph = sh;
double m = (double) sw / pw;
double n = (double) sh / ph;
int wth = (int) (destWidth * m);
int hth = (int) (destHeight * n);
int xx = (int) (x * m);
int yy = (int) (y * n);
// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(xx, yy, wth, hth);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", responseOutputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
JavaScript 图片切割效果(带拖放、缩放效果)
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮