js图片裁剪原理(手机自由裁剪任意形状)

项目需求有个功能要实现头像,让我这个后端开发来做这个确实有点为难,结合网上大神的例子,做了个简单的功能,以备不时之需实现效果页面+js<%@pagelanguage=\"java\"import=\"

项目需求有个功能要实现头像,让我这个后端开发来做这个确实有点为难,结合网上大神的例子,做了个简单的功能,以备不时之需

实现效果

js图片裁剪原理(手机自由裁剪任意形状)

页面+js

<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"UTF-8\"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+\"://\"+request.getServerName()+\":\"+request.getServerPort()+path+\"/\";
response.setHeader(\"Pragma\",\"No-cache\");
response.setHeader(\"Cache-Control\",\"no-cache\");
%>

<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<base href=\"<%=basePath%>\">

<title>My JSP \'face.jsp\' starting page</title>

<meta http-equiv=\"pragma\" content=\"no-cache\">
<meta http-equiv=\"cache-control\" content=\"no-cache\">
<meta http-equiv=\"expires\" content=\"0\">
<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">
<meta http-equiv=\"description\" content=\"This is my page\">
<!--
<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">
-->
<%-- <link rel=\"stylesheet\" href=\"<%=basePath%>static/css/bootstrap.css\"/> --%>
<link rel=\"stylesheet\" href=\"<%=basePath%>static/css/common.css\"/>
<link rel=\"stylesheet\" href=\"<%=basePath%>static/css/jquery.Jcrop.css\"/>
<script type=\"text/javascript\" src=\"<%=basePath%>static/js/jquery-1.9.1.min.js\"></script>
<script type=\"text/javascript\" src=\"<%=basePath%>static/js/ajaxfileupload.js\"></script>
<script type=\"text/javascript\" src=\"<%=basePath%>static/js/bootstrap.js\"></script>
<script type=\"text/javascript\" src=\"<%=basePath%>static/js/jquery.json-2.4.js\" charset=\"UTF-8\"></script>
<script type=\"text/javascript\" src=\"<%=basePath%>static/js/jquery.validate.js\"></script>
<script type=\"text/javascript\" src=\"<%=basePath%>static/js/jquery.Jcrop.js\"></script>

<script type=\"text/javascript\">
/* jcrop对象,全局变量方便操作 */
var api = null;
/* 原图宽度 */
var boundx;
/* 原图高度 */
var boundy;

/* 选择图片事件 */
function readURL(URL){
var reader = new FileReader();
reader.readAsDataURL(URL.files[0]);
reader.onload = function(e){
$(\"#faceId\").removeAttr(\"src\");
$(\"#lookId\").removeAttr(\"src\");
$(\"#faceId\").attr(\"src\",e.target.result);
$(\"#lookId\").attr(\"src\",e.target.result);
$(\"#faceId\").Jcrop({
onChange: showPreview,
onSelect: showPreview,
aspectRatio: 1,
boxWidth:600
},function(){
// Use the API to get the real image size
//使用API来获得真实的图像大小
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
//jcrop_api变量中存储API
api = this;

$(\"#boundx\").val(boundx);
$(\"#boundy\").val(boundy);

});
};
/* 移除jcrop */
if (api != undefined) {
api.destroy();
}

//简单的事件处理程序,响应自onChange,onSelect事件,按照上面的Jcrop调用
function showPreview(coords){
/* 设置剪切参数 */
$(\"#x\").val(coords.x);
$(\"#y\").val(coords.y);
$(\"#w\").val(coords.w);
$(\"#h\").val(coords.h);
if(parseInt(coords.w) > 0){
//计算预览区域图片缩放的比例,通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到
var rx = $(\"#preview_box\").width() / coords.w;
var ry = $(\"#preview_box\").height() / coords.h;
$(\"#lookId\").css({
width:Math.round(rx * $(\"#faceId\").width()) + \"px\", //预览图片宽度为计算比例值与原图片宽度的乘积
height:Math.round(rx * $(\"#faceId\").height()) + \"px\", //预览图片高度为计算比例值与原图片高度的乘积
marginLeft:\"-\" + Math.round(rx * coords.x) + \"px\",
marginTop:\"-\" + Math.round(ry * coords.y) + \"px\"
});
}
}

}

</script>

</head>

<body>
<form name=\"form\" action=\"<%=basePath%>faceUpload.do\" class=\"form-horizontal\" method=\"post\" enctype=\"multipart/form-data\">
<dir></dir>
<div style=\"margin-top: 10;margin-left: 30%\">
<table>
<tr>
<td>
<span>头像:</span>
<input class=\"photo-file\" type=\"file\" name=\"imgFile\" id=\"imgFile\" onchange=\"readURL(this) \" />
</td>
<td>
<!-- -->
<img id = \"faceId\" src=\"<%=basePath%>static/img/1.jpg\" class=\"jcrop-preview\" alt=\"附件\">

<!-- 图片长宽高隐藏域 -->
<input type=\"hidden\" id=\"x\" name=\"x\" />
<input type=\"hidden\" id=\"y\" name=\"y\" />
<input type=\"hidden\" id=\"w\" name=\"w\" />
<input type=\"hidden\" id=\"h\" name=\"h\" />
<input type=\"hidden\" id=\"boundx\" name=\"boundx\" >
<input type=\"hidden\" id=\"boundy\" name=\"boundy\" >

</td>
</tr>

<tr>
<td>
<span>头像预览:</span>
</td>
<td >
<div style=\"width: 200px;height: 200px;overflow: hidden;\" id = \"preview_box\">
<img id = \"lookId\" src=\"<%=basePath%>static/img/1.jpg\" class=\"jcrop-preview\" alt=\"预览\" >
</div>
</td>
</tr>
<tr>
<td>
<span>用户名:</span><input type=\"text\" id =\"userName\" name =\"userName\">
</td>
<td >
<span>艺名:</span><input type=\"text\" id =\"artName\" name =\"artName\" >
</td>
</tr>

</table>

<div class=\"modal-footer\">
<button id=\"submit\" onclick=\"\">上传</button>
</div>
</div>
</form>
</body>
</html>

后端控制器

package com.lovo.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.lovo.utils.CutImgeUtil;
import com.lovo.utils.FileUploadCheck;

@Controller
public class FaceController {

private static Logger logger = Logger.getLogger(FaceController.class);

@RequestMapping(value = \"/faceUpload.do\",method = RequestMethod.POST)
public void faceLoginController(HttpServletRequest request,HttpServletResponse response,Model model,
@RequestParam(\"imgFile\") MultipartFile imgFile,String userName,String artName){

//剪裁图片坐标
String x = request.getParameter(\"x\");
String y = request.getParameter(\"y\");
String w = request.getParameter(\"w\");
String h = request.getParameter(\"h\");

//原始图片坐标
String boundx = request.getParameter(\"boundx\");
String boundy = request.getParameter(\"boundy\");

//切图参数
int imgeX = (int) Double.parseDouble(x);
int imgeY = (int) Double.parseDouble(y);
int imegW = (int) Double.parseDouble(w);
int imgeH = (int) Double.parseDouble(h);
int srcX = (int) Double.parseDouble(boundx);
int srcY = (int) Double.parseDouble(boundy);

//文件保存文件夹
String path = request.getSession().getServletContext().getRealPath(\"/\")+\"fileUpload\"+File.separator;
//文件重命名
Date day = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(\"yyyyMMdd\");
String newName = sdf.format(day)+System.currentTimeMillis()+\".jpg\";

try
{
//处理头像附件
if(imgFile !=null)
{
//判断是否为图片文件
if(FileUploadCheck.allowUpload(imgFile.getContentType()))
{
boolean cut = CutImgeUtil.cutImge(imgFile.getInputStream(), imgeX, imgeY, imegW, imgeH, srcX, srcY, path+newName);
if(cut)
{
//当头像剪切成功进行用户信息数据库存储
System.out.println(userName+\" \"+artName+\" \"+newName);
}

}
}

} catch (Exception e)
{
e.printStackTrace();
logger.error(\"上传失败\");
}

}
}

工具类

package com.lovo.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

public class CutImgeUtil {

private static Logger logger = Logger.getLogger(CutImgeUtil.class);

/**
* 图片剪切工具类
* @param input 图片输入流
* @param x 截取时的x坐标
* @param y 截取时的y坐标
* @param desWidth 截取的宽度
* @param desHeight 截取的高度
* @param srcWidth 页面图片的宽度
* @param srcHeight 页面图片的高度
* @param newFilePath 保存路径+文件名
* @return
*/
public static boolean cutImge(InputStream input, int x, int y, int desWidth, int desHeight, int srcWidth,int srcHeight,String newFilePath){

boolean cutFlag = true;

try
{
//图片类
Image imge ;
ImageFilter cropFilter;

//读取图片
BufferedImage bi = ImageIO.read(input);

//当剪裁大小小于原始图片大小才执行
if(srcWidth >= desWidth && srcHeight >= desHeight)
{
//获取原始图
Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
//获取新图
cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
imge = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(desWidth, desHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(imge, 0, 0, null);
g.dispose();

File out = new File(newFilePath);
// 输出文件
ImageIO.write(tag, \"JPEG\", out);
}

} catch (Exception e)
{
cutFlag = false;
e.printStackTrace();
logger.error(\"剪切失败\");
}
return cutFlag;

}
}

package com.lovo.utils;

import java.util.Arrays;
import java.util.List;

public class FileUploadCheck {

//支持的文件类型
public static final List<String> ALLOW_TYPES = Arrays.asList(\"image/jpg\",\"image/jpeg\",\"image/png\",\"image/gif\");

//校验文件类型是否是被允许的
public static boolean allowUpload(String postfix){
return ALLOW_TYPES.contains(postfix);
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/85653.html

(0)
nan
上一篇 2022-01-15
下一篇 2022-01-15

相关推荐

  • 北京环球影城vip贵宾体验限量吗(北京环球影城vip贵宾体验多少钱)

    北京环球影城马上就要开业了,由于里面项目和迪士尼乐园相比更为的刺激,很多人都想前往该地点打卡。但因这种主题公园人流量颇大,所以为了减少时间所以很多人都会选择vip贵宾体验,下面小编就和大家一起看看。北京环球影城vip贵宾

    2021-09-06
    0
  • 3dmaxvray渲染设置(vr摄像机使用方法)

    想要做出一张好的效果图优秀的灯光是必不可少的今天小欧就整理了一些干货内容带大家了解下Vray的灯光系统Vray灯光使用参数手册Vray的灯光有以下几种矩形灯、球光源、聚光灯泛光灯、光域网灯、半球灯、网格灯1、矩形灯矩形灯是在Vray中最常用的灯光可以

    2021-09-04 科技
    0
  • win10如何快速调出任务管理器(win10笔记本任务管理器快捷键)

    任务管理器,是我们用电脑经常需要唤醒的一项重要的功能,但我们通常使用的时候都是为了结束掉我们当前系统中失去响应的程序。却忽视了其它的功能,今天我们一起来看Win10系统下的任务管理器还有哪些可以发掘的宝藏吧。想唤起任务管理器键盘上按下ct

    2021-12-11 科技
    0
  • 煤矿2022年停用井下劳务工(煤矿劳务派遣工45以上清退)

    由于环境污染等问题,煤矿也开始被各种新能源所替代,煤矿市场已经不如早年,煤矿开始走下坡路,那么煤矿2022年停用井下劳务工是真的吗?煤矿劳务派遣工45以上清退的说法真实吗?下面就跟久久派小编来详细了解一下吧!煤矿2022年停用井下劳务工?推动煤矿企业在202

    2021-09-01
    0
  • 反塔力量发言人阵亡(反塔发言人是怎么死的?)

    目前阿富汗的局面依旧是不受控制,塔利班力量和反塔力量一直在交锋,不过据最新报道反塔力量发言人阵亡,那么反塔发言人是怎么死的?反塔利班力量能坚持下去吗?反塔利班力量有多大呢?下面就跟久久派小编来详细了解一下吧!反塔力量发言人阵亡据阿富汗当地媒体消息,当地时间9

    2021-09-06
    0
  • win7配置最低要求是什么(2g内存装win7卡吗)

    win7系统比vista又有了很多改进,不仅是界面变得华丽,在操作效率上面更是效果显著。有些使用XP系统的朋友就想升级为win7系统,但是不确定自己的的电脑配置达不达的到标准。对此,我给大家整理了升级win7系统所需最低配置。1、CPU

    2021-12-11 科技
    0

发表回复

登录后才能评论