溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用imgareaselect輔助后臺(tái)實(shí)現(xiàn)圖片上傳裁剪

發(fā)布時(shí)間:2020-09-07 16:08:06 來(lái)源:腳本之家 閱讀:198 作者:hzf1993 欄目:web開(kāi)發(fā)

因?yàn)轫?xiàng)目當(dāng)中用到圖片裁剪,本來(lái)可以不用到后臺(tái)進(jìn)行裁剪的,但是要兼容萬(wàn)惡的IE瀏覽器,所以不得不使用后臺(tái)進(jìn)行裁剪。

這次使用到imgareaselect 插件獲取需要裁剪區(qū)域的坐標(biāo),再由后臺(tái)進(jìn)行裁剪操作。先上個(gè)效果圖再說(shuō)

利用imgareaselect輔助后臺(tái)實(shí)現(xiàn)圖片上傳裁剪

但是這里有一個(gè)坑就是上傳的圖片過(guò)大,可能會(huì)造成裁剪的區(qū)域跟插件中顯示的不一樣,所以得現(xiàn)在后臺(tái)對(duì)云圖片進(jìn)行壓縮在裁剪。

/** 
   * 等比例壓縮算法: 
   * 算法思想:根據(jù)壓縮基數(shù)和壓縮比來(lái)壓縮原圖,生產(chǎn)一張圖片效果最接近原圖的縮略圖 
   * @param srcURL 原圖地址 
   * @param deskURL 縮略圖地址 
   * @param comBase 壓縮基數(shù) 
   * @param scale 壓縮限制(寬/高)比例 一般用1: 
   * 當(dāng)scale>=1,縮略圖height=comBase,width按原圖寬高比例;若scale<1,縮略圖width=comBase,height按原圖寬高比例 
   * @throws Exception 
   
   */ 
  public static void saveMinPhoto(String srcURL, String deskURL, double comBase, 
      double scale) throws Exception { 
    File srcFile = new java.io.File(srcURL); 
    String ext = srcURL.substring(srcURL.lastIndexOf(".") + 1);  
    Image src = ImageIO.read(srcFile); 
    int srcHeight = src.getHeight(null); 
    int srcWidth = src.getWidth(null); 
    int deskHeight = 0;// 縮略圖高 
    int deskWidth = 0;// 縮略圖寬 
    double srcScale = (double) srcHeight / srcWidth; 
    /**縮略圖寬高算法*/ 
    if ((double) srcHeight > comBase || (double) srcWidth > comBase) { 
      if (srcScale >= scale || 1 / srcScale > scale) { 
        if (srcScale >= scale) { 
          deskHeight = (int) comBase; 
          deskWidth = srcWidth * deskHeight / srcHeight; 
        } else { 
          deskWidth = (int) comBase; 
          deskHeight = srcHeight * deskWidth / srcWidth; 
        } 
      } else { 
        if ((double) srcHeight > comBase) { 
          deskHeight = (int) comBase; 
          deskWidth = srcWidth * deskHeight / srcHeight; 
        } else { 
          deskWidth = (int) comBase; 
          deskHeight = srcHeight * deskWidth / srcWidth; 
        } 
      } 
    } else { 
      deskHeight = srcHeight; 
      deskWidth = srcWidth; 
    } 
    BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR); 
    tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); //繪制縮小后的圖 
    FileOutputStream deskImage = new FileOutputStream(deskURL); //輸出到文件流 
    ImageIO.write(tag, ext, new File(deskURL));  
    deskImage.close(); 
  } 

這就是壓縮之后在進(jìn)行裁剪了,好了上完整代碼先

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>上傳頭像</title> 
<link rel="stylesheet" href="../../statics/css/ewt/style_1.css" rel="external nofollow" type="text/css"> 
<link rel="stylesheet" href="../../statics/css/ewt/style_shangchuangtouxiang.css" rel="external nofollow" > 
<link rel="stylesheet" type="text/css" href="../../statics/css/ewt/imgareaselect-default.css" rel="external nofollow" > 
<link rel="stylesheet" href="../../statics/css/ewt/style.css" rel="external nofollow" type="text/css" /> 
<link rel="stylesheet" href="../../statics/scripts/layer/skin/default/layer.css" rel="external nofollow" > 
<script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> 
<script src="../../statics/scripts/include.js"></script> 
<script src="../../statics/scripts/template.js"></script> 
<script src="../../statics/scripts/layer/layer.js"></script> 
<script src="../../statics/scripts/cropbox.js"></script> 
<script src="../../statics/scripts/jquery.imgareaselect.pack.js"></script> 
<script src="../../statics/scripts/ajaxfileupload.js"></script> 
<script src="../../ewt/user/scripts/shangchuangtouxiang.js"></script> 
<script src="../../ewt/common/config.js"></script> 
 
</head> 
 
<body> 
<include src="../common/user_head.html"></include> 
<div class="bggg"> 
<div class="box"> 
 <div class="bos"> 
  <include src="../common/user_menu.html"></include> 
 <div class="bos_r"> 
 <div class="biaoti"> 
    <h4>上傳頭像</h4> 
   </div> 
 <div > 
    <div > 
    <div class="frame" > 
   <img id="photo" src="" /> 
  </div> 
 
  <div id="preview" > 
    <img src=""  id="smallImage"/> 
  </div>  
  </div>  
  </div> 
  <div > 
  <div class="input_XZ1"> 
  <div class="input_XZ">選擇圖片</div> 
  <input id="uplodimage" class="input_style"  name="uplodimage" type="file" onchange="uplodImage(this)"> 
  </div> 
   <input id="imgUrl" type="hidden"> 
  <input type="button" value="上傳" class="input_SC" onclick="upold();"> 
  </div> 
  <input type="hidden" id="x1" value="" /> 
  <input type="hidden" id="y1" value="" /> 
  <input type="hidden" id="x2" value="" /> 
  <input type="hidden" id="y2" value="" /> 
  <input type="hidden" id="w" value="" /> 
  <input type="hidden" id="h" value="" /> 
 
</div> 
</div> 
</div> 
 
 
</div>  
 
<include src="../common/user_footer.html"></include> 
</body> 
</html> 

js 代碼

function preview(img, selection) { 
  if (!selection.width || !selection.height) 
    return; 
   
  var scaleX = 100 / selection.width; 
  var scaleY = 100 / selection.height; 
 
  $('#preview img').css({ 
    width: Math.round(scaleX * 300), 
    height: Math.round(scaleY * 300), 
    marginLeft: -Math.round(scaleX * selection.x1), 
    marginTop: -Math.round(scaleY * selection.y1) 
  }); 
 
  $('#x1').val(selection.x1); 
  $('#y1').val(selection.y1); 
  $('#x2').val(selection.x2); 
  $('#y2').val(selection.y2); 
  $('#w').val(selection.width); 
  $('#h').val(selection.height);   
} 
 
$(function () { 
   
}); 
 
//上傳原始圖片 
function uplodImage(target) { 
  if(checkImage(target)){ 
    var url = httpUtils.rootPath+'/component/upload.do'; 
    $.ajaxFileUpload({ 
      url: url, //用于文件上傳的服務(wù)器端請(qǐng)求地址 
      secureuri: false, //是否需要安全協(xié)議,一般設(shè)置為false 
      fileElementId: 'uplodimage', //文件上傳域的ID 
      dataType: 'json', //返回值類型 一般設(shè)置為json 
      success: function (data) //服務(wù)器成功響應(yīng)處理函數(shù) 
      { 
        var filePath = data.filePath; 
        $('#photo').attr('src',httpUtils.rootPath+'/component/upload.do?action=download&filepath='+filePath); 
        $('#smallImage').attr('src',httpUtils.rootPath+'/component/upload.do?action=download&filepath='+filePath); 
        $('#imgUrl').val(filePath); 
         $('#photo').imgAreaSelect({  
    aspectRatio: '1:1', 
    x1: 50, y1: 50, x2: 241, y2: 241, 
    handles: true, 
    fadeSpeed: 200, 
    onSelectChange: preview 
  }); 
  $('#x1').val("50"); 
  $('#y1').val("50"); 
  $('#x2').val("241"); 
  $('#y2').val("241"); 
  $('#w').val("191"); 
  $('#h').val("191");  
       } 
      }); 
  } 
   
} 
 
//上傳裁剪后的圖片 
function upold() { 
 
  if($('#imgUrl').val()==''){ 
    layer.alert("請(qǐng)先選擇圖片在上傳"); 
    return false; 
  } 
   
   
  $.ajax({ 
       type: "post", 
       url:httpUtils.rootPath+'/user/setHeadPicture', 
       beforeSend: function(request) { 
        request.setRequestHeader("jmtcp", header);       
      }, 
       async:false, 
       data: { 
        x:$('#x1').val(), 
        y:$('#y1').val(), 
        width: $('#w').val(), 
        imgUrl : $('#imgUrl').val(), 
        heigth: $('#h').val() 
       }, 
       dataType: "json", 
       success: function(data){ 
            if(data.code==1){ 
               
              layer.alert(data.message,function(){ 
                window.location.href = '../user/grzy.html'; 
              }); 
            }else{ 
              layer.alert(data.message); 
            } 
           } 
     }); 
} 
 
function checkImage(target) { 
  var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 
   var fileSize = 0; 
   var filepath = target.value; 
  // 為了避免轉(zhuǎn)義反斜杠出問(wèn)題,這里將對(duì)其進(jìn)行轉(zhuǎn)換 
    var re = /(\+)/g; 
    var filename = filepath.replace(re, "#"); 
    // 對(duì)路徑字符串進(jìn)行剪切截取 
    var one = filename.split("#"); 
    // 獲取數(shù)組中最后一個(gè),即文件名 
    var two = one[one.length - 1]; 
    // 再對(duì)文件名進(jìn)行截取,以取得后綴名 
    var three = two.split("."); 
    // 獲取截取的最后一個(gè)字符串,即為后綴名 
    var last = three[three.length - 1]; 
    // 添加需要判斷的后綴名類型 
    var tp = "jpg,gif,bmp,JPG,GIF,BMP,png"; 
    // 返回符合條件的后綴名在字符串中的位置 
    var rs = tp.indexOf(last); 
    // 如果返回的結(jié)果大于或等于0,說(shuō)明包含允許上傳的文件類型 
    if(rs < 0){ 
      layer.alert('您選擇的上傳文件不是有效的圖片文件'); 
      return false; 
    } 
//  if (isIE && !target.files) {  // IE瀏覽器 
//    var filePath = target.value; // 獲得上傳文件的絕對(duì)路徑 
//    var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); 
//    // GetFile(path) 方法從磁盤獲取一個(gè)文件并返回。 
//    var file = fileSystem.GetFile(filePath); 
//    fileSize = file.Size;  // 文件大小,單位:b 
//  } 
//  else {  // 非IE瀏覽器 
//    fileSize = target.files[0].size; 
//  } 
     var img1 = document.getElementById('photo');  
    //img1.dynsrc=target.value;  
    //img1.fileSize:IE , fileObj.files[0].fileSize:chrome, fileObj.files[0].size:FF  
    var fileSize = img1.fileSize || target.files[0].fileSize || target.files[0].size;   
  var size = fileSize / 1024 / 1024; 
  if (size > 5) { 
    layer.alert("圖片不能大于5M"); 
    return false; 
  } 
  return true; 
} 

后臺(tái)代碼

public class CutImageUtils { 
  public static SecureRandom rnd = new SecureRandom(); 
   
  public static String cutImage(int x, int y, int width, int height,String srcPath) throws Exception{ 
    String root = ApplicationContext.getProperty("upload_folder"); 
    String imagePath = root+srcPath; 
     FileInputStream is = null;  
     ImageInputStream iis = null;  
     String uploadFolder = null ; 
    String filepath = null ; 
    String serverName = null ; 
    uploadFolder = ApplicationContext.getProperties().getProperty("upload_folder").toString() ; 
    filepath = generateServerFolder() ; 
    serverName = generateServerName(srcPath) ; 
    File file = new File(uploadFolder + filepath);  
    if (!file.exists()) {  
      file.mkdirs(); 
    }  
    
     try { 
      // 讀取圖片文件  
      saveMinPhoto(imagePath, imagePath, 300, 0.9d); 
       //resetsize(imagePath, imagePath); 
      is = new FileInputStream(imagePath); 
      String ext = srcPath.substring(srcPath.lastIndexOf(".") + 1);  
       Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);  
       ImageReader reader = it.next();  
      // 獲取圖片流  
       iis = ImageIO.createImageInputStream(is);  
       reader.setInput(iis, true);  
       ImageReadParam param = reader.getDefaultReadParam();  
       /**  
         *  
         * 圖片裁剪區(qū)域。Rectangle 指定了坐標(biāo)空間中的一個(gè)區(qū)域,通過(guò) Rectangle 對(duì)象  
         *  
         * 的左上頂點(diǎn)的坐標(biāo)(x,y)、寬度和高度可以定義這個(gè)區(qū)域。  
         */  
       Rectangle rect = new Rectangle(x, y, width, height);  
    
        // 提供一個(gè) BufferedImage,將其用作解碼像素?cái)?shù)據(jù)的目標(biāo)。  
       param.setSourceRegion(rect);  
       BufferedImage bi = reader.read(0, param);  
       // 保存新圖片  
       ImageIO.write(bi, ext, new File(uploadFolder + filepath + serverName));  
    } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      if (is != null)  
        is.close();  
      if (iis != null)  
        iis.close();  
      e.printStackTrace(); 
    }  
     return filepath + serverName ; 
  } 
 
    /** 
   *  
   * @param config 
   * @param file 
   * @param request 
   * @return 
   */ 
  public static String generateServerName(String clientPath) { 
    //按當(dāng)前時(shí)間的分鐘毫秒+3位隨機(jī)數(shù) 
    Calendar c = Calendar.getInstance(); 
    String min = get(c,Calendar.MINUTE); 
    String sec = get(c,Calendar.SECOND); 
    String mis = get(c,Calendar.MILLISECOND); 
    String rnd = random(); 
    String ext = getFileExt(getClientName(clientPath)); 
     
    return min + sec + mis + rnd + ext ; 
  } 
   
  /** 客戶端文件名 */ 
  public static String getClientName(String clientPath) { 
    if(null != clientPath){ 
      int index1 = clientPath.lastIndexOf("/"); 
      int index2 = clientPath.lastIndexOf("\\"); 
      if(index2 > index1){ 
        index1 = index2; 
      } 
      return clientPath.substring(index1+1,clientPath.length()); 
    } 
    return null; 
  } 
   
  public static String getFileExt(String fileName){ 
    if(null != fileName){ 
      int dot = fileName.lastIndexOf("."); 
      if(dot >= 0){ 
        return fileName.substring(dot); 
      } 
    } 
    return ""; 
  } 
   
  public static String random(){ 
    String value = String.valueOf(rnd.nextInt(1000)); 
    if(value.length() < 3){ 
      for(int i=value.length();i<3;i++){ 
        value = "0" + value; 
      } 
    } 
    return value; 
  } 
   
  public static String generateServerFolder() { 
    //按當(dāng)前年月日和小時(shí)生成文件路徑 
    Calendar c = Calendar.getInstance(); 
    String year = get(c,Calendar.YEAR); 
    String mon = get(c,Calendar.MONTH); 
    String day = get(c,Calendar.DAY_OF_MONTH); 
    String hour = get(c,Calendar.HOUR_OF_DAY); 
     
    return year + "/" + mon + "/" + day + "/" + hour + "/"; 
  } 
 
  public static String get(Calendar c,int field){ 
    int v = c.get(field); 
    if(field == Calendar.MONTH){ 
      v += 1; 
    } 
    String value = String.valueOf(v); 
    if(value.length() == 1){ 
      value = "0" + value; 
    } 
    return value; 
  } 
   
  /** 
   * 縮小圖片到固定長(zhǎng)高 
   * @param srcImagePath 讀取圖片路徑 
   * @param toImagePath 寫入圖片路徑 
   * @param width 縮小后圖片寬度 
   * @param height 縮小后圖片長(zhǎng)度 
   * @throws IOException 
   */ 
  public static void reduceImageByWidthHeight(String srcImagePath, String toImagePath, int width, int height) throws IOException{ 
    FileOutputStream out = null; 
    try{ 
      //讀入文件  
      File file = new File(srcImagePath);  
      String ext = srcImagePath.substring(srcImagePath.lastIndexOf(".") + 1);  
      // 構(gòu)造Image對(duì)象  
      BufferedImage src = javax.imageio.ImageIO.read(file);  
      // 縮小邊長(zhǎng)  
      BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
      // 繪制縮小后的圖片  
      tag.getGraphics().drawImage(src, 0, 0, width, height, null);  
      out = new FileOutputStream(toImagePath);  
      ImageIO.write(tag, ext, new File(toImagePath));  
    }catch(Exception e){ 
      e.printStackTrace(); 
    }finally{ 
      if(out != null){ 
        out.close();  
      } 
      out = null; 
      System.gc(); 
    } 
  } 
   
  /** 
   * 等比例壓縮算法:  
   * 算法思想:根據(jù)壓縮基數(shù)和壓縮比來(lái)壓縮原圖,生產(chǎn)一張圖片效果最接近原圖的縮略圖 
   * @param srcURL 原圖地址 
   * @param deskURL 縮略圖地址 
   * @param comBase 壓縮基數(shù) 
   * @param scale 壓縮限制(寬/高)比例 一般用1: 
   * 當(dāng)scale>=1,縮略圖height=comBase,width按原圖寬高比例;若scale<1,縮略圖width=comBase,height按原圖寬高比例 
   * @throws Exception 
   
   */ 
  public static void saveMinPhoto(String srcURL, String deskURL, double comBase, 
      double scale) throws Exception { 
    File srcFile = new java.io.File(srcURL); 
    String ext = srcURL.substring(srcURL.lastIndexOf(".") + 1);  
    Image src = ImageIO.read(srcFile); 
    int srcHeight = src.getHeight(null); 
    int srcWidth = src.getWidth(null); 
    int deskHeight = 0;// 縮略圖高 
    int deskWidth = 0;// 縮略圖寬 
    double srcScale = (double) srcHeight / srcWidth; 
    /**縮略圖寬高算法*/ 
    if ((double) srcHeight > comBase || (double) srcWidth > comBase) { 
      if (srcScale >= scale || 1 / srcScale > scale) { 
        if (srcScale >= scale) { 
          deskHeight = (int) comBase; 
          deskWidth = srcWidth * deskHeight / srcHeight; 
        } else { 
          deskWidth = (int) comBase; 
          deskHeight = srcHeight * deskWidth / srcWidth; 
        } 
      } else { 
        if ((double) srcHeight > comBase) { 
          deskHeight = (int) comBase; 
          deskWidth = srcWidth * deskHeight / srcHeight; 
        } else { 
          deskWidth = (int) comBase; 
          deskHeight = srcHeight * deskWidth / srcWidth; 
        } 
      } 
    } else { 
      deskHeight = srcHeight; 
      deskWidth = srcWidth; 
    } 
    BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR); 
    tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); //繪制縮小后的圖 
    FileOutputStream deskImage = new FileOutputStream(deskURL); //輸出到文件流 
    ImageIO.write(tag, ext, new File(deskURL));  
    deskImage.close(); 
  } 
   
   
   
  public static void main(String[] args) { 
    try { 
      String src = CutImageUtils.cutImage(11, 12, 100, 100, "2017/01/04/17/6348162d-5b50-4e7d-b414-93140498f8de.jpg"); 
      System.out.println(src); 
    } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
  } 
} 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI