JCrop+ajaxUpload 映像切割上傳的執行個體代碼,jcropajaxupload

來源:互聯網
上載者:User

JCrop+ajaxUpload 映像切割上傳的執行個體代碼,jcropajaxupload

先給大家展示下:

頁面代碼

裡面使用者的uuid是寫死的test

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE><html lang="en"><head><title>帳戶圖片剪裁</title><meta http-equiv="Content-type" content="text/html;charset=UTF-8" /><link rel="stylesheet" href="resources/Jcrop/css/jquery.Jcrop.css"><link rel="stylesheet" href="resources/css/photo.css"><script src="resources/js/jquery.min.js"></script><script src="resources/Jcrop/js/jquery.Jcrop.js"></script><script src="resources/js/ajaxfileupload.js"></script></head><body><div class="container"><div class="row"><div class="span12"><div class="jc-demo-box"><div class="page-header"><h1>頭像剪裁</h1></div><img src="resources/img/test.jpg" id="target" /><div id="preview-pane" ><div class="preview-container"><img src="resources/img/test.jpg" class="jcrop-preview"/></div ><div style='float:left;display:inline;'><a class='btn_addPic' href="javascript:void(0);"><span><EM>+</EM>添加圖片</span> <input id="upload_image" type="file" name="upimage" accept="image/*" class = "filePrew"/></a></div><div style='float:right;display:inline;'><a class='btn_addPic' href="javascript:void(0);" onclick='submit()'><span>提交</span> </a></div></div></div></div></div></div></body><script type="text/javascript">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變數中儲存APIjcrop_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) {// 根據這個 <input> 擷取檔案的 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 產生目標 urlvar imgURL = URL.createObjectURL(file);// 用這個 URL 產生一個 <img> 將其顯示出來$('.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, //一般設定為falsefileElementId: 'upload_image', //檔案上傳空間的id屬性dataType: 'json', //傳回值類型 一般設定為jsondata:{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();//重新整理當前頁面}});}</script></html>

後台代碼

@ResponseBody@RequestMapping("uploadphoto")public Map<String, Object> uploadPhoto(@RequestParam("upimage") MultipartFile imageFile, HttpServletRequest request,HttpServletResponse response) throws Exception {Map<String, Object> result = new HashMap<String, Object>();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 映像切割上傳的執行個體代碼,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.