<script id="portraitUpload" type="text/html">
<div style="padding: 10px 20px">
<form role="form" enctype="multipart/form-data" method="post">
<div class="embed-responsive embed-responsive-16by9">
<div class="embed-responsive-item pre-scrollable">
<img alt="" src="${pageContext.request.contextPath}/img/showings.jpg" id="cut-img"
class="img-responsive img-thumbnail"/>
</div>
</div>
<div class="white-divider-md"></div>
<input type="file" name="imgFile" id="fileUpload"/>
<div class="white-divider-md"></div>
<div id="alert" class="alert alert-danger hidden" role="alert"></div>
<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"/>
</form>
</div>
</script>
<div class="embed-responsive-item pre-scrollable">
$(document).ready(function () {
new PageInit().init();
});
function PageInit() {
var api = null;
var _this = this;
this.init = function () {
$("[name='upload']").on('click', this.portraitUpload)
};
this.portraitUpload = function () {
var model = $.scojs_modal({
title: '头像上传',
content: template('portraitUpload'),
onClose: refresh
}
);
model.show();
var fileUp = new FileUpload();
var portrait = $('#fileUpload');
var alert = $('#alert');
fileUp.portrait(portrait, '/file/portrait', _this.getExtraData);
portrait.on('change', _this.readURL);
portrait.on('fileuploaderror', function (event, data, msg) {
alert.removeClass('hidden').html(msg);
fileUp.fileinput('disable');
});
portrait.on('fileclear', function (event) {
alert.addClass('hidden').html();
});
portrait.on('fileloaded', function (event, file, previewId, index, reader) {
alert.addClass('hidden').html();
});
portrait.on('fileuploaded', function (event, data) {
if (!data.response.status) {
alert.html(data.response.message).removeClass('hidden');
}
})
};
this.readURL = function () {
var img = $('#cut-img');
var input = $('#fileUpload');
if (input[0].files && input[0].files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input[0].files[0]);
reader.onload = function (e) {
img.removeAttr('src');
img.attr('src', e.target.result);
img.Jcrop({
setSelect: [20, 20, 200, 200],
handleSize: 10,
aspectRatio: 1,
onSelect: updateCords
}, function () {
api = this;
});
};
if (api != undefined) {
api.destroy();
}
}
function updateCords(obj) {
$("#x").val(obj.x);
$("#y").val(obj.y);
$("#w").val(obj.w);
$("#h").val(obj.h);
}
};
this.getExtraData = function () {
return {
sw: $('.jcrop-holder').css('width'),
sh: $('.jcrop-holder').css('height'),
x: $('#x').val(),
y: $('#y').val(),
w: $('#w').val(),
h: $('#h').val()
}
}
}
portrait.on('fileuploaderror', function (event, data, msg) {
alert.removeClass('hidden').html(msg);
fileUp.fileinput('disable');
});
<div id="alert" class="alert alert-danger hidden" role="alert"></div>
portrait.on('fileclear', function (event) {
alert.addClass('hidden').html();
});
portrait.on('fileloaded', function (event, file, previewId, index, reader) {
alert.addClass('hidden').html();
});
portrait.on('fileuploaded', function (event, data) {
if (!data.response.status) {
alert.html(data.response.message).removeClass('hidden');
}
})
this.getExtraData = function () {
return {
sw: $('.jcrop-holder').css('width'),
sh: $('.jcrop-holder').css('height'),
x: $('#x').val(),
y: $('#y').val(),
w: $('#w').val(),
h: $('#h').val()
}
}
this.portrait = function (target, uploadUrl, data) {
target.fileinput({
language: 'zh', //设置语言
maxFileSize: 2048,//文件最大容量
uploadExtraData: data,//上传时除了文件以外的其他额外数据
showPreview: false,//隐藏预览
uploadAsync: true,//ajax同步
dropZoneEnabled: false,//是否显示拖拽区域
uploadUrl: uploadUrl, //上传的地址
allowedFileExtensions: ['jpg'],//接收的文件后缀
showUpload: true, //是否显示上传按钮
showCaption: true,//是否显示标题
browseClass: "btn btn-primary", //按钮样式
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
ajaxSettings: {//这个是因为我使用了SpringSecurity框架,有csrf跨域提交防御,所需需要设置这个值
beforeSend: function (xhr) {
xhr.setRequestHeader(header, token);
}
}
});
}
@ResponseBody
@RequestMapping(value = "/portrait", method = {RequestMethod.POST})
public JsonResult upload(HttpServletRequest request) throws Exception {
Integer x = Integer.parseInt(MyStringTools.checkParameter(request.getParameter("x"), "图片截取异常:X!"));
Integer y = Integer.parseInt(MyStringTools.checkParameter(request.getParameter("y"), "图片截取异常:Y!"));
Integer w = Integer.parseInt(MyStringTools.checkParameter(request.getParameter("w"), "图片截取异常:W!"));
Integer h = Integer.parseInt(MyStringTools.checkParameter(request.getParameter("h"), "图片截取异常:H!"));
String scaleWidthString = MyStringTools.checkParameter(request.getParameter("sw"), "图片截取异常:SW!");
int swIndex = scaleWidthString.indexOf("px");
Integer sw = Integer.parseInt(scaleWidthString.substring(0, swIndex));
String scaleHeightString = MyStringTools.checkParameter(request.getParameter("sh"), "图片截取异常:SH!");
int shIndex = scaleHeightString.indexOf("px");
Integer sh = Integer.parseInt(scaleHeightString.substring(0, shIndex));
//获取用户ID用于指向对应文件夹
SysUsers sysUsers = HttpTools.getSessionUser(request);
int userID = sysUsers.getUserId();
//获取文件路径
String filePath = FileTools.getPortraitPath(userID);
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
String path;
//检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
//将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest 中所有的文件名
Iterator iterator = multiRequest.getFileNames();
while (iterator.hasNext()) {
//一次遍历所有文件
MultipartFile multipartFile = multiRequest.getFile(iterator.next().toString());
if (multipartFile != null) {
String[] allowSuffix = {".jpg",".JPG"};
if (!FileTools.checkSuffix(multipartFile.getOriginalFilename(), allowSuffix)) {
throw new BusinessException("文件后缀名不符合要求!");
}
path = filePath + FileTools.getPortraitFileName(multipartFile.getOriginalFilename());
//存入硬盘
multipartFile.transferTo(new File(path));
//图片截取
if (FileTools.imgCut(path, x, y, w, h, sw, sh)) {
CompressTools compressTools = new CompressTools();
if (compressTools.simpleCompress(new File(path))) {
return JsonResult.success(FileTools.filePathToSRC(path, FileTools.IMG));
} else {
return JsonResult.error("图片压缩失败!请重新上传!");
}
} else {
return JsonResult.error("图片截取失败!请重新上传!");
}
}
}
}
return JsonResult.error("图片获取失败!请重新上传!");
}
/**
* 截图工具,根据截取的比例进行缩放裁剪
*
* @param path 图片路径
* @param zoomX 缩放后的X坐标
* @param zoomY 缩放后的Y坐标
* @param zoomW 缩放后的截取宽度
* @param zoomH 缩放后的截取高度
* @param scaleWidth 缩放后图片的宽度
* @param scaleHeight 缩放后的图片高度
* @return 是否成功
* @throws Exception 任何异常均抛出
*/
public static boolean imgCut(String path, int zoomX, int zoomY, int zoomW,
int zoomH, int scaleWidth, int scaleHeight) throws Exception {
Image img;
ImageFilter cropFilter;
BufferedImage bi = ImageIO.read(new File(path));
int fileWidth = bi.getWidth();
int fileHeight = bi.getHeight();
double scale = (double) fileWidth / (double) scaleWidth;
double realX = zoomX * scale;
double realY = zoomY * scale;
double realW = zoomW * scale;
double realH = zoomH * scale;
if (fileWidth >= realW && fileHeight >= realH) {
Image image = bi.getScaledInstance(fileWidth, fileHeight, Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter((int) realX, (int) realY, (int) realW, (int) realH);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage bufferedImage = new BufferedImage((int) realW, (int) realH, BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
//输出文件
return ImageIO.write(bufferedImage, "JPEG", new File(path));
} else {
return true;
}
}
package com.magic.rent.tools;
/**
* 知识产权声明:本文件自创建起,其内容的知识产权即归属于原作者,任何他人不可擅自复制或模仿.
* 创建者: wu 创建时间: 2016/12/15
* 类说明: 缩略图类(通用) 本java类能将jpg、bmp、png、gif图片文件,进行等比或非等比的大小转换。 具体使用方法
* 更新记录:
*/
import com.magic.rent.exception.custom.BusinessException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
public class CompressTools {
private File file; // 文件对象
private String inputDir; // 输入图路径
private String outputDir; // 输出图路径
private String inputFileName; // 输入图文件名
private String outputFileName; // 输出图文件名
private int outputWidth = 100; // 默认输出图片宽
private int outputHeight = 100; // 默认输出图片高
private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
private static Logger logger = LoggerFactory.getLogger(CompressTools.class);
public CompressTools() {
}
public CompressTools(boolean proportion) {
this.proportion = proportion;
}
/**
* 设置输入参数
*
* @param inputDir
* @param inputFileName
* @return
*/
public CompressTools setInputInfo(String inputDir, String inputFileName) {
this.inputDir = inputDir;
this.inputFileName = inputFileName;
return this;
}
/**
* 设置输出参数
*
* @param outputDir
* @param outputFileName
* @param outputHeight
* @param outputWidth
* @param proportion
* @return
*/
public CompressTools setOutputInfo(String outputDir, String outputFileName, int outputHeight, int outputWidth, boolean proportion) {
this.outputDir = outputDir;
this.outputFileName = outputFileName;
this.outputWidth = outputWidth;
this.outputHeight = outputHeight;
this.proportion = proportion;
return this;
}
// 图片处理
public boolean compress() throws Exception {
//获得源文件
file = new File(inputDir);
if (!file.exists()) {
throw new BusinessException("文件不存在!");
}
Image img = ImageIO.read(file);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
System.out.println(" can't read,retry!" + "<BR>");
return false;
} else {
int newWidth;
int newHeight;
// 判断是否是等比缩放
if (this.proportion) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
long start = System.currentTimeMillis();
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
/*
* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的
* 优先级比速度高 生成的图片质量比较好 但速度慢
*/
tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(outputDir);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
long time = System.currentTimeMillis() - start;
logger.info("[输出路径]:" + outputDir + "\t[图片名称]:" + outputFileName + "\t[压缩前大小]:" + getPicSize() + "\t[耗时]:" + time + "毫秒");
return true;
}
}
/**
* 简单压缩方法,压缩后图片将直接覆盖源文件
*
* @param images
* @return
* @throws Exception
*/
public boolean simpleCompress(File images) throws Exception {
setInputInfo(images.getPath(), images.getName());
setOutputInfo(images.getPath(), images.getName(), 300, 300, true);
return compress();
}
/**
* 获取图片大小,单位KB
*
* @return
*/
private String getPicSize() {
return file.length() / 1024 + "KB";
}
public static void main(String[] args) throws Exception {
CompressTools compressTools = new CompressTools();
compressTools.setInputInfo("/Users/wu/Downloads/background.jpg", "background.jpg");
compressTools.setOutputInfo("/Users/wu/Downloads/background2.jpg", "background2.jpg", 633, 1920, false);
compressTools.compress();
}
}
package com.magic.rent.tools;
import com.magic.rent.exception.custom.BusinessException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.util.ArrayList;
/**
* 知识产权声明:本文件自创建起,其内容的知识产权即归属于原作者,任何他人不可擅自复制或模仿.
* 创建者: wu 创建时间: 2016/11/25
* 类说明:
* 更新记录:
*/
public class FileTools {
public static final int IMG = 1;
/**
* 获取项目根目录
*
* @return 根目录
*/
public static String getWebRootPath() {
return System.getProperty("web.root");
}
/**
* 获取头像目录,若不存在则直接创建一个
*
* @param userID 用户ID
* @return
*/
public static String getPortraitPath(int userID) {
String realPath = getWebRootPath() + "img/portrait/" + userID + "/";
File file = new File(realPath);
//判断文件夹是否存在,不存在则创建一个
if (!file.exists() || !file.isDirectory()) {
if (!file.mkdirs()) {
throw new BusinessException("创建头像文件夹失败!");
}
}
return realPath;
}
/**
* 重命名头像文件
*
* @param fileName 文件名
* @return
*/
public static String getPortraitFileName(String fileName) {
// 获取文件后缀
String suffix = getSuffix(fileName);
return "portrait" + suffix;
}
/**
* 判断文件后缀是否符合要求
*
* @param fileName 文件名
* @param allowSuffix 允许的后缀集合
* @return
* @throws Exception
*/
public static boolean checkSuffix(String fileName, String[] allowSuffix) throws Exception {
String fileExtension = getSuffix(fileName);
boolean flag = false;
for (String extension : allowSuffix) {
if (fileExtension.equals(extension)) {
flag = true;
}
}
return flag;
}
public static String getSuffix(String fileName) {
return fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
}
/**
* 将文件地址转成链接地址
*
* @param filePath 文件路径
* @param fileType 文件类型
* @return
*/
public static String filePathToSRC(String filePath, int fileType) {
String href = "";
if (null != filePath && !filePath.equals("")) {
switch (fileType) {
case IMG:
if (filePath.contains("/img/")) {
int index = filePath.indexOf("/img/");
href = filePath.substring(index);
} else {
href = "";
}
return href;
}
}
return href;
}
/**
* 获取指定文件或文件路径下的所有文件清单
*
* @param fileOrPath 文件或文件路径
* @return
*/
public static ArrayList<File> getListFiles(Object fileOrPath) {
File directory;
if (fileOrPath instanceof File) {
directory = (File) fileOrPath;
} else {
directory = new File(fileOrPath.toString());
}
ArrayList<File> files = new ArrayList<File>();
if (directory.isFile()) {
files.add(directory);
return files;
} else if (directory.isDirectory()) {
File[] fileArr = directory.listFiles();
if (null != fileArr && fileArr.length != 0) {
for (File fileOne : fileArr) {
files.addAll(getListFiles(fileOne));
}
}
}
return files;
}
/**
* 截图工具,根据截取的比例进行缩放裁剪
*
* @param path 图片路径
* @param zoomX 缩放后的X坐标
* @param zoomY 缩放后的Y坐标
* @param zoomW 缩放后的截取宽度
* @param zoomH 缩放后的截取高度
* @param scaleWidth 缩放后图片的宽度
* @param scaleHeight 缩放后的图片高度
* @return 是否成功
* @throws Exception 任何异常均抛出
*/
public static boolean imgCut(String path, int zoomX, int zoomY, int zoomW,
int zoomH, int scaleWidth, int scaleHeight) throws Exception {
Image img;
ImageFilter cropFilter;
BufferedImage bi = ImageIO.read(new File(path));
int fileWidth = bi.getWidth();
int fileHeight = bi.getHeight();
double scale = (double) fileWidth / (double) scaleWidth;
double realX = zoomX * scale;
double realY = zoomY * scale;
double realW = zoomW * scale;
double realH = zoomH * scale;
if (fileWidth >= realW && fileHeight >= realH) {
Image image = bi.getScaledInstance(fileWidth, fileHeight, Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter((int) realX, (int) realY, (int) realW, (int) realH);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage bufferedImage = new BufferedImage((int) realW, (int) realH, BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
//输出文件
return ImageIO.write(bufferedImage, "JPEG", new File(path));
} else {
return true;
}
}
}
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>web.root</param-value>
</context-param>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有