java jcrop 异步上传_JCrop+ajaxUpload 图像切割上传的实例代码

先给大家展示下效果图:

851ce2b05df4f5021aecfcf9be56e913.png

页面代码

里面用户的uuid是写死的test

用户头像剪裁

test.jpg

test.jpg

+添加图片

提交

var global_api = "";

var boundx ="";//页面图片宽度

var boundy ="";//页面图片高度

var tag = false;

$(function() {

// Create variables (in this scope) to hold the API and image size

//创建变量(在这个范围)的API和图像大小

var jcrop_api,

// Grab some information about the preview pane

//获取一些信息预览窗格

$preview = $('#preview-pane'),

$pcnt = $('#preview-pane .preview-container'),

$pimg = $('#preview-pane .preview-container img'),

xsize = $pcnt.width(),

ysize = $pcnt.height();

$('#target').Jcrop({

onChange: updatePreview,

onSelect: updatePreview,

aspectRatio: xsize / ysize

},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

jcrop_api = this;

// Move the preview into the jcrop container for css positioning

//预览进入jcrop容器css定位

$preview.appendTo(jcrop_api.ui.holder);

});

function updatePreview(c)

{

if (parseInt(c.w) > 0)

global_api=c;

{

var rx = xsize / c.w;

var ry = ysize / c.h;

$pimg.css({

width: Math.round(rx * boundx) + 'px',

height: Math.round(ry * boundy) + 'px',

marginLeft: '-' + Math.round(rx * c.x) + 'px',

marginTop: '-' + Math.round(ry * c.y) + 'px'

});

}

};

//=======选择图片回显===============

$('#upload_image').change(function(event) {

// 根据这个 获取文件的 HTML5 js 对象

var files = event.target.files, file;

if (files && files.length > 0) {

// 获取目前上传的文件

file = files[0];

// 下面是关键的关键,通过这个 file 对象生成一个可用的图像 URL

// 获取 window 的 URL 工具

var URL = window.URL || window.webkitURL;

// 通过 file 生成目标 url

var imgURL = URL.createObjectURL(file);

// 用这个 URL 产生一个 将其显示出来

$('.jcrop-holder img').attr('src', imgURL);

$('.preview-container img').attr('src', imgURL);

}

});

//=============是否选择了本地图片==================

$("#upload_image").change(function(){

tag=true;

});

});

//========================================================

//======图片保存===========

function submit(){

if(tag&&global_api != ""){

ajaxFileUpload();

}else{

alert('你是不是什么事情都没干?');

}

}

//ajax文件上传

function ajaxFileUpload() {

$.ajaxFileUpload({

url: 'uploadphoto', //用于文件上传的服务器端请求地址

secureuri: false, //一般设置为false

fileElementId: 'upload_image', //文件上传空间的id属性

dataType: 'json', //返回值类型 一般设置为json

data:{x:global_api.x,y:global_api.y,w:global_api.w,h:global_api.h,pw:boundx,ph:boundy,unid:'test'}, //一同上传的数据

success: function (data){ //服务器成功响应处理函数

if(data.result){

alert('成功');

}else{

alert('失败');

}

window.location.reload();//刷新当前页面

}

}

);

}

后台代码

@ResponseBody

@RequestMapping("uploadphoto")

public Map uploadPhoto(@RequestParam("upimage") MultipartFile imageFile, HttpServletRequest request,

HttpServletResponse response) throws Exception {

Map result = new HashMap();

boolean tag =false;

String unid = request.getParameter("unid");

String x = request.getParameter("x");

String y = request.getParameter("y");

String h = request.getParameter("h");

String w = request.getParameter("w");

// 页面实际图片宽高

String pheight = request.getParameter("ph");

String pweight = request.getParameter("pw");

// 切图参数

int imageX = Integer.parseInt(x);

int imageY = Integer.parseInt(y);

int imageH = Integer.parseInt(h);

int imageW = Integer.parseInt(w);

int srcH = Integer.parseInt(pheight);

int srcW = Integer.parseInt(pweight);

String realPath = request.getSession().getServletContext().getRealPath("/");

String resourcePath = "resources/uploadImages/";

try {

if (imageFile != null) {

if (FileUploadUtil.allowUpload(imageFile.getContentType())) {

// 这里开始截取操作

byte[] b = ImageCut.imgCut(imageFile.getInputStream(), imageX, imageY, imageW, imageH, srcW, srcH);

if (b != null) {

// 存入数据库

User user = userService.selectByPrimaryKey(unid);

user.setPhoto(b);

tag = (userService.updateByPrimaryKeySelective(user)==1)?tag=true:tag;

result.put("result", tag);

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

result.put("result", tag);

return result;

}

图像切割工具类

package com.ssm.demo.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.InputStream;

import javax.imageio.ImageIO;

public class ImageCut {

/**

* 截取图片

*

* @param srcImageFile

* 原图片地址

* @param x

* 截取时的x坐标

* @param y

* 截取时的y坐标

* @param desWidth

* 截取的宽度

* @param desHeight

* 截取的高度

* @param srcWidth

* 页面图片的宽度

* @param srcHeight

* 页面图片的高度

*

*/

public static byte[] imgCut(InputStream input, int x, int y, int desWidth, int desHeight, int srcWidth,

int srcHeight) {

try {

Image img;

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);

img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));

BufferedImage tag = new BufferedImage(desWidth, desHeight, BufferedImage.TYPE_INT_RGB);

Graphics g = tag.getGraphics();

g.drawImage(img, 0, 0, null);

g.dispose();

// 输出文件

ByteArrayOutputStream out = new ByteArrayOutputStream();

ImageIO.write(tag, "JPEG", out);

return out.toByteArray();

}

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

}

以上所述是小编给大家介绍的JCrop+ajaxUpload 图像切割上传的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值