使用Jcrop.js和jQuery.form.js,用ImageIO等進行頭像上傳縮放及裁剪

來源:互聯網
上載者:User

標籤:

首先,Java代碼裡帶一個擷取ImageReader的Iterator

    /**     * 從網上摘抄的。     * 返回包含所有當前登入 ImageReader 的 Iterator,這些 ImageReader 聲稱能夠解碼指定格式。     * 參數:postFix - 包含非正式格式名稱 .(例如 "jpeg" 或 "tiff")等 。     *      * @param postFix     *            檔案的尾碼名     * @author 劉各歡     * @return     */    public Iterator<ImageReader> getImageReadersByFormatName(String postFix) {        switch (postFix) {        case "jpg":            return ImageIO.getImageReadersByFormatName("jpg");        case "jpeg":            return ImageIO.getImageReadersByFormatName("jpeg");        case "gif":            return ImageIO.getImageReadersByFormatName("gif");        case "bmp":            return ImageIO.getImageReadersByFormatName("bmp");        case "png":            return ImageIO.getImageReadersByFormatName("png");        default:            return ImageIO.getImageReadersByFormatName("jpg");        }    }





第一步,用jQuery.form.js的ajaxSubmit()提交上傳的原始圖片,對圖片進行縮放並返回等比例大小的圖片,限制返回的圖片最大尺寸為1000px X 500px


Java核心代碼如下:

/** *  * imgFileZoom:傳入一個圖片檔案輸入資料流,寫入縮放後的圖片到輸出資料流 *  * @author 劉各歡 * @param postFix * @param in * @param out * @param showHeight 網頁顯示地區的高 * @param showWidth 網頁顯示地區的寬 * @return * @throws IOException * @since  Ver 1.1 */    public Map<String,String> imgFileZoom(String postFix,InputStream in,FileOutputStream out,int showHeight,int showWidth) throws IOException{//FileInputStream is = null;        ImageInputStream iis = null;        Map<String,String> map = new HashMap<String,String>();        try {            // 讀取圖片檔案            //is = new FileInputStream(in);            // 擷取檔案的尾碼名                        System.out.println("圖片格式為:" + postFix);            /*             * 返回包含所有當前登入 ImageReader 的 Iterator,這些 ImageReader 聲稱能夠解碼指定格式。             * 參數:formatName - 包含非正式格式名稱 .(例如 "jpeg" 或 "tiff")等 。             */            Iterator<ImageReader> it = this.getImageReadersByFormatName(postFix);            ImageReader reader = it.next();            // 擷取圖片流            iis = ImageIO.createImageInputStream(in);            /*             * <p>iis:讀取源.true:只向前搜尋 </p>.將它標記為 ‘只向前搜尋’。             * 此設定意味著包含在輸入源中的映像將只按順序讀取,可能允許 reader 避免緩衝包含與以前已經讀取的映像關聯的資料的那些輸入部分。             */            reader.setInput(iis, true);            int realWidth = reader.getWidth(0);            int realHeight = reader.getHeight(0);                        double ratio = 1.0;                        if(realWidth>showWidth){            BigDecimal d1 = new BigDecimal(showWidth);            BigDecimal d2 = new BigDecimal(realWidth);            ratio = d1.divide(d2, 8,BigDecimal.ROUND_HALF_UP).doubleValue();            }else if(realHeight>showHeight){            BigDecimal d1 = new BigDecimal(showHeight);            BigDecimal d2 = new BigDecimal(showHeight);            ratio = d1.divide(d2, 8,BigDecimal.ROUND_HALF_UP).doubleValue();            }else{            ratio = 1.0;            }                        BigDecimal ratioDecimal = new BigDecimal(ratio);            BigDecimal realWidthDecimal = new BigDecimal(realWidth);            BigDecimal realHeightDecimal = new BigDecimal(realHeight);            BigDecimal outputWidthDecimal = BigDecimal.ONE;            BigDecimal outputHeightDecimal = BigDecimal.ONE;            outputWidthDecimal = realWidthDecimal.multiply(ratioDecimal);            outputHeightDecimal = realHeightDecimal.multiply(ratioDecimal);            int outputWidth = outputWidthDecimal.intValue();            int outputHeight = outputHeightDecimal.intValue();            //裝入最終轉換過的圖片的寬高            map.put("outputWidth", String.valueOf(outputWidth));            map.put("outputHeight", String.valueOf(outputHeight));                        /*             * 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象,並將 它作為一個完整的             * BufferedImage 返回。             */            BufferedImage bi = reader.read(0);                        /*             * 縮放圖片             */            Image imageSmall = bi.getScaledInstance(outputWidth, outputHeight, Image.SCALE_DEFAULT);                          BufferedImage small = new BufferedImage(outputWidth, outputHeight, BufferedImage.TYPE_INT_RGB);                        Graphics g = small.getGraphics();            g.drawImage(imageSmall, 0, 0, null); // 繪製縮小後的圖  將Image繪製到BufferedImage中            g.dispose();                                                //寫入新圖片到輸出資料流            ImageIO.write(small, postFix, out);        } finally {            if (in != null)                in.close();            if (iis != null)                iis.close();            if (out != null)                out.close();        }        return map;    }        /**     *      * updateZoomTxService:對上傳的頭像圖片進行縮放,並返回一些參數     *      * @author 劉各歡     * @param pic     * @param req     * @return     * @since  Ver 1.1     */    public Map<String,Object> uploadZoomTx(MultipartFile pic,String uid,HttpServletRequest req){//從CommonInfo中讀取上傳檔案的路徑String pathString = CommonInfo.touxiangPath+"/zoom/";String fileName = "";Map<String,Object> map = new HashMap<String,Object>();//判斷檔案是否已經被擷取到if (pic.getSize() > 0) {//user.setImage(pathString + pic.getOriginalFilename());//判斷檔案儲存體路徑是否存在File file = new File(pathString);if (!file.exists() && !file.isDirectory()) {file.mkdirs();}try {String ext=pic.getOriginalFilename().substring(pic.getOriginalFilename().lastIndexOf(".")+1,pic.getOriginalFilename().length());fileName = System.currentTimeMillis()+uid+"."+ext;//建立縮放過的檔案輸出資料流FileOutputStream fout = new FileOutputStream(pathString + fileName );map.put("imgInfo",this.imgFileZoom(ext.toLowerCase(),pic.getInputStream(),fout,500,1000));map.put("imgUrl", fileName);if(fout!=null) fout.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}return map;}


返回的參數中帶有縮放後的映像長寬資訊,在前台js處擷取到,對Jcrop進行初始化。

前台核心代碼(ajaxSubmit()及成功後的觸發):

$("#uploadTxBtn").click(function(){var option = {                      type: "post",                      success : function(data){                      zoomPicName = data['imgUrl'];                                              $("#p_img").attr("src", "../../touxiang/zoom/"+data['imgUrl']);                       $("#p_img").show();                       $("#preview_block").show();                       $("#p_img_preview").attr("src", "../../touxiang/zoom/"+data['imgUrl']);                       $("#p_img").width(data['imgInfo']['outputWidth']);                       $("#p_img").height(data['imgInfo']['outputHeight']);                                              $("#uploadZoomTx").height(parseInt(data['imgInfo']['outputHeight'])+150);                       caijian();                   }                    };                    $("#uploadZoomTx").ajaxSubmit(option);  });


Jcrop相關初始化的js代碼:

function caijian(){                  // Create variables (in this scope) to hold the API and image size  var jcrop_api, boundx, boundy;    $('#p_img').Jcrop({    onChange: updatePreview,    onSelect: updatePreview,    aspectRatio: 1,    setSelect: [0,0,100,100]  },function(){    // Use the API to get the real image size    var bounds = this.getBounds();    boundx = bounds[0];    boundy = bounds[1];        console.log(1111);    console.log(bounds);            // Store the API in the jcrop_api variable    jcrop_api = this;  });  function updatePreview(c)  {    if (parseInt(c.w) > 0)    {            console.log(c);    img_x = c.x;    img_y = c.y;    img_w = c.w;    img_h = c.h;          var rx = 100 / c.w;      var ry = 100 / c.h;      $('#p_img_preview').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'      });          }  };}


第二步:

使用者拖拽完裁剪框,點擊裁剪按鈕之後,上傳四個參數,分別是起始點的橫縱座標和裁剪地區的寬度高度,

此次過程只上傳參數,並沒有上傳圖片,後台根據參數對上一步已經縮放的圖片再次進行裁剪和縮放。

js代碼略去,後台Java核心代碼如下:

/** *  * imgFileCut:傳入一個圖片檔案輸入資料流,寫入裁減後的圖片到輸出資料流 *  * @author 劉各歡 * @param postFix * @param in * @param out * @param x * @param y * @param width * @param height * @param showHeight * @param showWidth * @throws IOException * @since  Ver 1.1 */    public void imgFileCut(String postFix,InputStream in,FileOutputStream out,int x,int y,int width,int height) throws IOException{        ImageInputStream iis = null;        try {            /*             * 返回包含所有當前登入 ImageReader 的 Iterator,這些 ImageReader 聲稱能夠解碼指定格式。             * 參數:formatName - 包含非正式格式名稱 .(例如 "jpeg" 或 "tiff")等 。             */            Iterator<ImageReader> it = getImageReadersByFormatName(postFix);            ImageReader reader = it.next();            // 擷取圖片流            iis = ImageIO.createImageInputStream(in);            /*             * <p>iis:讀取源.true:只向前搜尋 </p>.將它標記為 ‘只向前搜尋’。             * 此設定意味著包含在輸入源中的映像將只按順序讀取,可能允許 reader 避免緩衝包含與以前已經讀取的映像關聯的資料的那些輸入部分。             */            reader.setInput(iis, true);                        /*             * <p>描述如何對流進行解碼的類<p>.用於指定如何在輸入時從 Java Image I/O             * 架構的上下文中的流轉換一幅映像或一組映像。用於特定映像格式的外掛程式 將從其 ImageReader 實現的             * getDefaultReadParam 方法中返回 ImageReadParam 的執行個體。             */            ImageReadParam param = reader.getDefaultReadParam();            /*             * 圖片裁剪地區。Rectangle 指定了座標空間中的一個地區,通過 Rectangle 對象             * 的左上頂點的座標(x,y)、寬度和高度可以定義這個地區。             */            Rectangle rect = new Rectangle(x, y, width, height);            // 提供一個 BufferedImage,將其用作解碼像素資料的目標。            param.setSourceRegion(rect);                        /*             * 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象,並將 它作為一個完整的             * BufferedImage 返回。             */            BufferedImage bi = reader.read(0, param);                                                /*              * 縮放圖片              */              Image imageSmall = bi.getScaledInstance(100, 100, Image.SCALE_DEFAULT);                              BufferedImage small = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);                            Graphics g = small.getGraphics();              g.drawImage(imageSmall, 0, 0, null); // 繪製縮小後的圖  將Image繪製到BufferedImage中              g.dispose();                                                  // 儲存新圖片            ImageIO.write(small, postFix, out);        } finally {            if (in != null)                in.close();            if (iis != null)                iis.close();            if (out != null)                out.close();        }    }    public String saveTx(String zoomedImageName, String img_x, String img_y,String img_w, String img_h) {String zoomedImagePath = CommonInfo.touxiangPath+"/zoom/"+zoomedImageName;String finalImagePath = CommonInfo.touxiangPath+zoomedImageName;File zoomedImagefile = new File(zoomedImagePath);try {InputStream in = new FileInputStream(zoomedImagefile);File finalImage = new File(finalImagePath);FileOutputStream out = new FileOutputStream(finalImage);int x = new BigDecimal(img_x).intValue();int y = new BigDecimal(img_y).intValue();int w = new BigDecimal(img_w).intValue();int h = new BigDecimal(img_h).intValue();String postFix=zoomedImageName.substring(zoomedImageName.lastIndexOf(".")+1,zoomedImageName.length()).toLowerCase();this.imgFileCut(postFix, in, out, x, y, w, h);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("儲存頭像失敗");return "error";}return "success";}







Control中的主調用方法:

/** *  * updateZoomTx:對上傳的原始頭像進行等比例縮放,並返迴文件名等一些參數 *  * @author 劉各歡 * @param pic * @param req * @return * @since  Ver 1.1 */@ResponseBody@RequestMapping(value = "/uploadZoomTx.do")public Map<String,Object> updateZoomTx(MultipartFile pic,HttpServletRequest req){Map<String,Object> map = null;if(req.getSession()!=null&&req.getSession().getAttribute("curruser")!=null){String uid = "";uid = ((User)(req.getSession().getAttribute("curruser"))).getId();map =userService.uploadZoomTx(pic,uid,req);}else{map=new HashMap<String,Object>();map.put("error","error");}return map;}/** *  * saveTx: 對上一步縮放過的映像進行裁剪並縮放,存在本地硬碟 *  * @author 劉各歡 * @param zoomedImageName * @param img_x * @param img_y * @param img_w * @param img_h * @param req * @return * @since  Ver 1.1 */@ResponseBody@RequestMapping(value = "/saveTx.do")public String saveTx(String zoomedImageName,String img_x,String img_y,String img_w,String img_h,HttpServletRequest req){String re =userService.saveTx( zoomedImageName,img_x, img_y, img_w, img_h);if(req.getSession()!=null&&req.getSession().getAttribute("curruser")!=null){User user = (User)(req.getSession().getAttribute("curruser"));user.setImage(zoomedImageName);userService.saveOrUpdate(user);return "ok";}else{return "error";}}



關於利用HTML5的canvas或者flash進行截取的也想過,考慮到相容性,還是先這樣吧。

相關資源:http://download.csdn.net/detail/lgh06/8343359 免積分

預覽效果:



使用Jcrop.js和jQuery.form.js,用ImageIO等進行頭像上傳縮放及裁剪

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.