栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb实现裁剪图片上传完整代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb实现裁剪图片上传完整代码

本文实例为大家分享了JavaWeb实现裁剪图片上传完整案例,供大家参考,具体内容如下

实现思路

 •使用jcrop插件手机要裁剪图片的坐标
 •将收集到的参数传递到后台,在后台使用java图形对象绘制图像进行裁剪
◦后台处理流程:
1、将上传的图片按按照比例进行压缩后上传到文件服务器,并且将压缩后的图片保存在本地临时目录中。
2、将压缩后的图片回显到页面,使用jcrop进行裁剪,手机裁剪坐标(x,y,width,height)
■@paramx 目标切片起点坐标X
■@param y 目标切片起点坐标Y
■@param width 目标切片宽度
■@param height 目标切片高度
3、后台处理裁剪裁剪,重新上传

jsp页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



  
  上传用户头像
  
  
  
  



  















后台java代码

图片上传工具类

package com.shengya.service.utils;


import com.shengya.service.ImgContants;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.base64Encoder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;


public class UploadUtils {
  // public final static String RADIOURL = "http://211.102.216.237:8011/fileServer/webapi/Attachments/bio?";
  public final static String RADIOURL = "http://192.168.1.15:8088/fileServer/webapi/Attachments/bio?";

  public final static String URL = ImgContants.IMG_UPLOAD + "/file/UpLoadImage?";
  public final static String FILEURL = ImgContants.IMG_UPLOAD + "/file/UpLoadFile?";
  public final static String VEDIOURL = ImgContants.FILE_UPLOAD + "/file/UpLoadFile?";
  public final static String CROPURL = ImgContants.IMG_UPLOAD + "/file/CropImage?";


  private static byte[] readAsByteArr(InputStream is) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      byte[] bytes = new byte[1024];
      int length = 0;
      while ((length = is.read(bytes)) != -1) {
 baos.write(bytes, 0, length);
      }
      return baos.toByteArray();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 baos.close();
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }

  
  public static String submitImage(File file) throws UnsupportedEncodingException {
    String fileName = URLEncoder.encode(file.getName(), "UTF-8");
    long fileSize = file.length();
    boolean isReSuffix = true;
    int height = 0;
    int width = 500;
    String mark = "t";
    String mode = "W";
    String url = sign(URL)
 + "&ChannelNo=muying_android"
 + "&FileName="
 + fileName
 + "&FileSize="
 + fileSize
 + "&IsReSuffix="
 + isReSuffix
 + "&Height="
 + height
 + "&Width="
 + width + "&Mark=" + mark + "&Mode=" + mode;
    System.out.println("url:" + url);
    HttpURLConnection conn = null;
    OutputStream outStream = null;
    BufferedInputStream bin = null;
    try {
      bin = new BufferedInputStream(new FileInputStream(file));
      conn = (HttpURLConnection) new URL(url)
   .openConnection();
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      // conn.setFixedLengthStreamingMode(file.length());
      conn.setRequestProperty("Content-Type",
   "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", file.length()
   + "");
      // conn.setRequestProperty("Range", "bytes="+"");
      // 设置 HttpURLConnection的字符编码
      conn.setRequestProperty("Accept-Charset", "UTF-8");
      outStream = conn.getOutputStream();

      byte[] buf = new byte[1024];
      int len = 0;
      int lenCount = 0;
      while ((len = bin.read(buf)) != -1) {
 outStream.write(buf, 0, len);//OK
 lenCount = lenCount + len;
      }
      outStream.flush();
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      } else {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (outStream != null) {
   outStream.close();
 }
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }

  
  public static String submitWebImage(MultipartFile file) throws UnsupportedEncodingException {
    String fileName = URLEncoder.encode(file.getOriginalFilename(), "UTF-8");
    long fileSize = file.getSize();
    boolean isReSuffix = true;
    int height = 0;
    int width = 500;
    String mark = "t";
    String mode = "W";
    String url = sign(URL)
 + "&ChannelNo=muying_android"
 + "&FileName="
 + fileName
 + "&FileSize="
 + fileSize
 + "&IsReSuffix="
 + isReSuffix
 + "&Height="
 + height
 + "&Width="
 + width + "&Mark=" + mark + "&Mode=" + mode;
    System.out.println("url:" + url);
    HttpURLConnection conn = null;
    OutputStream outStream = null;
    BufferedInputStream bin = null;
    try {
      bin = new BufferedInputStream(file.getInputStream());
      conn = (HttpURLConnection) new URL(url)
   .openConnection();
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      // conn.setFixedLengthStreamingMode(file.length());
      conn.setRequestProperty("Content-Type",
   "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", file.getSize()
   + "");
      // conn.setRequestProperty("Range", "bytes="+"");
      // 设置 HttpURLConnection的字符编码
      conn.setRequestProperty("Accept-Charset", "UTF-8");
      outStream = conn.getOutputStream();

      byte[] buf = new byte[1024];
      int len = 0;
      int lenCount = 0;
      while ((len = bin.read(buf)) != -1) {
 outStream.write(buf, 0, len);//OK
 lenCount = lenCount + len;
      }
      outStream.flush();
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      } else {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (outStream != null) {
   outStream.close();
 }
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }

  
  public static String submitRadio(MultipartFile file) throws Exception {
    String url = signRadio(RADIOURL);
    System.out.println("url:" + url);
    HttpURLConnection conn = null;
    OutputStream outStream = null;
    BufferedInputStream bin = null;
    try {
      bin = new BufferedInputStream(file.getInputStream());
      conn = (HttpURLConnection) new URL(url)
   .openConnection();
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setRequestProperty("Content-Type",
   "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", file.getSize()
   + "");
      conn.setRequestProperty("Accept-Charset", "UTF-8");
      outStream = conn.getOutputStream();

      byte[] buf = new byte[1024];
      int len = 0;
      int lenCount = 0;
      while ((len = bin.read(buf)) != -1) {
 outStream.write(buf, 0, len);//OK
 lenCount = lenCount + len;
      }
      outStream.flush();
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      } else {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (outStream != null) {
   outStream.close();
 }
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }

  
  public static String submitFile(String fileName, String content) throws UnsupportedEncodingException {
    //content = URLEncoder.encode(content, "UTF-8");
    fileName = URLEncoder.encode(fileName, "UTF-8");
    byte[] contentBytes = content.getBytes();
    long fileSize = contentBytes.length;
    boolean isReSuffix = true;
    int height = 0;
    int width = 500;
    String mark = "t";
    String mode = "W";
    String url = sign(FILEURL)
 + "&ChannelNo=muying_android"
 + "&FileName="
 + fileName
 + "&FileSize="
 + fileSize
 + "&IsReSuffix="
 + isReSuffix
 + "&Height="
 + height
 + "&Width="
 + width + "&Mark=" + mark + "&Mode=" + mode;
    System.out.println("url:" + url);
    HttpURLConnection conn = null;
    OutputStream outStream = null;
    BufferedInputStream bin = null;
    try {
      conn = (HttpURLConnection) new URL(url)
   .openConnection();
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      // conn.setFixedLengthStreamingMode(file.length());
      conn.setRequestProperty("Content-Type",
   "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", content.length()
   + "");
      // conn.setRequestProperty("Range", "bytes="+"");
      // 设置 HttpURLConnection的字符编码
      conn.setRequestProperty("Accept-Charset", "UTF-8");
      outStream = conn.getOutputStream();
      outStream.write(contentBytes, 0, contentBytes.length);//OK
      outStream.flush();
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      } else {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (outStream != null) {
   outStream.close();
 }
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }



  
  public static String submitFile(MultipartFile file) throws UnsupportedEncodingException {
    String fileName = URLEncoder.encode(file.getOriginalFilename(), "UTF-8");
    long fileSize = file.getSize();
    boolean isReSuffix = true;
    int height = 0;
    int width = 500;
    String mark = "t";
    String mode = "W";
    String url = sign(FILEURL)
 + "&ChannelNo=muying_android"
 + "&FileName="
 + fileName
 + "&FileSize="
 + fileSize
 + "&IsReSuffix="
 + isReSuffix
 + "&Height="
 + height
 + "&Width="
 + width + "&Mark=" + mark + "&Mode=" + mode;
    System.out.println("url:" + url);
    HttpURLConnection conn = null;
    OutputStream outStream = null;
    BufferedInputStream bin = null;
    try {
      bin = new BufferedInputStream(file.getInputStream());
      conn = (HttpURLConnection) new URL(url)
   .openConnection();
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      // conn.setFixedLengthStreamingMode(file.length());
      conn.setRequestProperty("Content-Type",
   "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", file.getSize()
   + "");
      // conn.setRequestProperty("Range", "bytes="+"");
      // 设置 HttpURLConnection的字符编码
      conn.setRequestProperty("Accept-Charset", "UTF-8");
      outStream = conn.getOutputStream();
      byte[] buf = new byte[1024];
      int len = 0;
      int lenCount = 0;
      while ((len = bin.read(buf)) != -1) {
 outStream.write(buf, 0, len);//OK
 lenCount = lenCount + len;
      }
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      } else {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (outStream != null) {
   outStream.close();
 }
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }


  private static String sign(String baseurl) throws UnsupportedEncodingException {
    long currebttime = System.currentTimeMillis();
    long timeStamp = currebttime / 1000;
    String data = "ActionName=UpLoadImage" + "&SecretKey=4b19f08dbf0adb82ce9cc7c207ec1dc9"
 + "&TimeStamp=" + timeStamp;
    String signature = hmac_sha1("4b19f08dbf0adb82ce9cc7c207ec1dc9",
 URLEncoder.encode(data, "UTF-8"));
    signature = signature.replace("%3D", "%3d");
    signature = signature.replace("%3A", "%3a");
    signature = signature.replace("%2F", "%2f");
    return baseurl + data + "&Signature=" + signature;

  }

  private static String signRadio(String url) throws Exception {
    long currebttime = System.currentTimeMillis();
    String data = "secretKey=f1b79c865c424be46183a2f0a49a0f15"
 + "&timeStamp=" + currebttime;
    System.out.println("url:" + url + data);
    System.out.println("url = " + URLEncoder.encode(url + data, "utf-8"));
    String signature = HmacSha1Util.getSignature(URLEncoder.encode(url + data, "utf-8"), "f1b79c865c424be46183a2f0a49a0f15");
    return url + data + "&signature=" + signature;

  }

  private static String hmac_sha1(String key, String datas) {
    String reString = "";
    try {
      datas = datas.replace("%3A", "%3a");
      datas = datas.replace("%2F", "%2f");
      datas = datas.replace("%3D", "%3d");
      byte[] data = key.getBytes("UTF-8");
      // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
      SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
      // 生成一个指定 Mac 算法 的 Mac 对象
      Mac mac = Mac.getInstance("HmacSHA1");
      // 用给定密钥初始化 Mac 对象
      mac.init(secretKey);
      byte[] text = datas.getBytes("UTF-8");
      // 完成 Mac 操作
      byte[] text1 = mac.doFinal(text);
      reString = new base64Encoder().encodeBuffer(text1);
      reString = URLEncoder.encode(reString, "UTF-8");
      reString = reString.replace("%0A", "");
      reString = reString.replace("%0D", "");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return reString;
  }

  
  public static String submitCutedWebImage(MultipartFile file,String fileID,String x,String y,String w,String h) throws UnsupportedEncodingException {
    String FileId=fileID;
    String[] CropWidths=new String[]{"50"};//裁剪宽度
    //List list=new List();
    //List list = new ArrayList(5);
    ArrayList listCropWidths = new ArrayList();
    listCropWidths.add("400");

//    String[] CropHeights=new String[]{"50"};//裁剪高度
    ArrayList listCropHeights = new ArrayList();
    listCropHeights.add("300");

    int CropX=Integer.parseInt(x);//裁剪x坐标
    int CropY=Integer.parseInt(y);//裁剪y坐标

//    String[] CropFixs=new String[]{"l"};//裁剪图片的标示集合
    ArrayList listCropFixs = new ArrayList();
    listCropFixs.add("l");


    String SourceSuffix="jpg";//底图后缀
    String SourceFix="";//底图标示

    
    String url = sign(CROPURL) + "FileId="
 + fileID
 + "&CropWidths="
 + listCropWidths
 + "&CropHeights="
 + listCropHeights
 + "&CropX="
 + CropX
 + "&CropY="
 + CropY + "&CropFixs=" + listCropFixs + "&SourceSuffix=" + SourceSuffix+ "&SourceFix=" + SourceFix;
    System.out.println("url:" + url);
    HttpURLConnection conn = null;
    OutputStream outStream = null;
    BufferedInputStream bin = null;
    try {
      bin = new BufferedInputStream(file.getInputStream());
      conn = (HttpURLConnection) new URL(url)
   .openConnection();
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      // conn.setFixedLengthStreamingMode(file.length());
      conn.setRequestProperty("Content-Type",
   "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", file.getSize()
   + "");
      // conn.setRequestProperty("Range", "bytes="+"");
      // 设置 HttpURLConnection的字符编码
      conn.setRequestProperty("Accept-Charset", "UTF-8");
      outStream = conn.getOutputStream();
      byte[] buf = new byte[1024];
      int len = 0;
      int lenCount = 0;
      while ((len = bin.read(buf)) != -1) {
 outStream.write(buf, 0, len);//OK
 lenCount = lenCount + len;
      }
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      } else {
 InputStream inStream = conn.getInputStream();
 byte[] data1 = readAsByteArr(inStream);
 String json = new String(data1);
 inStream.close();
 return json;
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
 if (outStream != null) {
   outStream.close();
 }
      } catch (IOException e) {
 e.printStackTrace();
      }
    }
    return null;
  }

  
  public static String submitCropImage(MultipartFile file,Integer x,Integer y,Integer w,Integer h) throws IOException {
    String folder=System.getProperty("java.io.tmpdir");
    File tempDir =new File(folder);
    //如果文件夹不存在则创建
    if (!tempDir .exists() && !tempDir .isDirectory())
    {
//      System.out.println("//不存在");
      tempDir .mkdir();
    }
    //压缩后临时文件
    String Srcpath=folder+"scaleTemp.jpg";

    //获取文件的后缀
    

    //裁剪图片
    cutImgUtils o = new cutImgUtils(x,y,w,h);
    o.setSrcpath(Srcpath);
    o.setSubpath(folder+"uptemp.jpg");
    File tempFile = o.cut("jpg");
    String s = submitImage(tempFile);
    return s;
  }


  
  public static int getImgWidth(MultipartFile file) throws IOException {
    InputStream is = null;
    BufferedImage src = null;
    int ret = -1;
    try {
      is = file.getInputStream();
      src = javax.imageio.ImageIO.read(is);
      ret = src.getWidth(null); // 得到源图宽
      is.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ret;
  }

  
  public static int getImgHeight(MultipartFile file) {
    InputStream is = null;
    BufferedImage src = null;
    int ret = -1;
    try {
      is = file.getInputStream();
      src = javax.imageio.ImageIO.read(is);
      ret = src.getHeight(null); // 得到源图高
      is.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ret;
  }

  
  public static void scale(MultipartFile file, String result, int height, int width, boolean bb) {
    try {
      double ratio = 0.0; // 缩放比例
      
//      File f = new File(srcImageFile);
      InputStream inputStream = file.getInputStream();
      BufferedImage bi = ImageIO.read(inputStream);
      Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
      // 计算比例
      if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
 if (bi.getHeight() > bi.getWidth()) {
   ratio = (new Integer(height)).doublevalue()
/ bi.getHeight();
 } else {
   ratio = (new Integer(width)).doublevalue() / bi.getWidth();
 }
 AffineTransformOp op = new AffineTransformOp(AffineTransform
     .getScaleInstance(ratio, ratio), null);
 itemp = op.filter(bi, null);
      }
      if (bb) {//补白
 BufferedImage image = new BufferedImage(width, height,
     BufferedImage.TYPE_INT_RGB);
 Graphics2D g = image.createGraphics();
 g.setColor(Color.white);
 g.fillRect(0, 0, width, height);
 if (width == itemp.getWidth(null))
   g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
itemp.getWidth(null), itemp.getHeight(null),
Color.white, null);
 else
   g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
itemp.getWidth(null), itemp.getHeight(null),
Color.white, null);
 g.dispose();
 itemp = image;
      }
      ImageIO.write((BufferedImage) itemp, "jpg", new File(result));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  public static void main(String[] args) {
    try {
      
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

图片裁剪工具类

package com.shengya.service.utils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;


public class cutImgUtils {
  // ===源图片路径名称如:c:1.jpg
  private String srcpath;

  // ===剪切图片存放路径名称。如:c:2.jpg
  private String subpath;
  public void setSrcpath(String srcpath) {
    this.srcpath = srcpath;
  }
  public void setSubpath(String subpath) {
    this.subpath = subpath;
  }
  // ===剪切点x坐标
  private int x;

  private int y;

  // ===剪切点宽度
  private int width;
  private int height;

  public cutImgUtils() {
  }

  public cutImgUtils(int x, int y, int width, int height) {
    if(x<0){
      x=0;
    }else{
      this.x = x;
    }
    if(y<0){
      y=0;
    }else{
      this.y = y;
    }
    this.width = width;
    this.height = height;
  }

  

  public File cut() throws IOException {
    FileInputStream is = null;
    ImageInputStream iis = null;
    try {
      // 读取图片文件
      is = new FileInputStream(srcpath);

      
      Iterator it = ImageIO
   .getImageReadersByFormatName("jpg");

      ImageReader reader = it.next();

      // 获取图片流
      iis = ImageIO.createImageInputStream(is);

      
      reader.setInput(iis, true);

      
      ImageReadParam param = reader.getDefaultReadParam();

      
      Rectangle rect = new Rectangle(x, y, width, height);

      // 提供一个 BufferedImage,将其用作解码像素数据的目标。
      param.setSourceRegion(rect);

      
      BufferedImage bi = reader.read(0, param);

      // 保存新图片
      ImageIO.write(bi, "jpg", new File(subpath));
      File file = new File("subpath");
      return file;
    } finally {
      if (is != null)
 is.close();
      if (iis != null)
 iis.close();
    }

  }


  public File cut(String suffix) throws IOException {
    FileInputStream is = null;
    ImageInputStream iis = null;
    try {
      // 读取图片文件
      is = new FileInputStream(srcpath);
//is = inputStream;
      
    String suffixName=null;
      if(suffix.equals("gif")){
 suffixName="gif";
      }else if(suffix.equals("png")){
 suffixName="png";
      } else{
 suffixName="jpg";
      }
      Iterator it = ImageIO
   .getImageReadersByFormatName(suffixName);
      ImageReader reader = it.next();

      // 获取图片流
      iis = ImageIO.createImageInputStream(is);

      
      reader.setInput(iis, true);

      
      ImageReadParam param = reader.getDefaultReadParam();

      

      Rectangle rect = new Rectangle(x, y, width, height);

      // 提供一个 BufferedImage,将其用作解码像素数据的目标。
      param.setSourceRegion(rect);

      
      BufferedImage bi = reader.read(0, param);

      // 保存新图片
      ImageIO.write(bi, "jpg", new File(subpath));
      File file = new File(subpath);
      return file;
    } finally {
      if (is != null)
 is.close();
      if (iis != null)
 iis.close();
    }

  }

}

遇到的问题总结:

-裁剪图片发生偏移现象
解决办法:使用压缩后的图片等比例收集裁切坐标信息
-MultipartFile 和 File之间相互转化

第一种方法: 

 MultipartFile file = xxx; 
    CommonsMultipartFile cf= (CommonsMultipartFile)file; 
    DiskFileItem fi = (DiskFileItem)cf.getFileItem();

    File f = fi.getStoreLocation();

会在项目的根目录的临时文件夹下生成一个文件;

第二种方法:

 transferTo(File dest);

会在项目中生成一个新文件;

第三种方法:  

File f = (File) xxx 强转即可。前提是要配置multipartResolver,要不然会报类型转换失败的异常。  


   
    
  

没试过;

第四种方法:

Workbook wb = Workbook.getWorkbook(xxx .getInputStream());

转换为输入流,直接读取;

第五种方法:

byte[] buffer = myfile.getBytes();

先转换为字节数组,没试过;

第六种方法:

直接转成输入流

MultipartFile file=xxx;
 is = file.getInputStream();
 src = javax.imageio.ImageIO.read(is);
 ret = src.getWidth(null); // 得到源图宽

参考资料:
jcop api:http://code.ciaoca.com/jquery/jcrop/.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/149176.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号