package com.net.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream; import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile; import com.net.entity.ImgzipResult;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder; /**************************************
* Description:图片上传压缩工具类
* @author zhangdi
* @version 1.0
*/
public class ImageProcess {
private Logger log = Logger.getLogger(ImageProcess.class);
/**
* 上传并压缩图片
* @param myFile 上传的文件
* @param width 设置宽度
* @param height 设置高度
* @param request 网络请求
* @return 结果集合(是否成功,新路径)
*/
public ImgzipResult UploadFile(MultipartFile myFile, int width, int height, HttpServletRequest request) {
Boolean sta = false;
ImgzipResult imResult = new ImgzipResult();
InputStream is = null;
FileOutputStream fs = null;
//获得物理路径webapp所在路径
String pathRoot = request.getSession().getServletContext().getRealPath("");
/** 临时文件夹*/
String imgPath = File.separator +"img"+File.separator+ "imgTemp" + File.separator;
// String tempPath = ServletConstants.WEB_ROOT_OS_PATH + imgPath;
String tempPath = pathRoot+imgPath;
System.out.println("old-path-" + tempPath);
// String name = myFile.getOriginalFilename();
File oldFile = new File(tempPath);
if (!oldFile.exists()) {
oldFile.mkdirs();
}
/** 处理后文件夹*/
String newImaPath = File.separator +"img"+File.separator+"imgZip" + File.separator;
// String newPath = ServletConstants.WEB_ROOT_OS_PATH + newImaPath;
String newPath = pathRoot+newImaPath;
System.out.println("new-path-" + newPath);
File newFile = new File(newPath);
if (!newFile.exists()) {
newFile.mkdirs();
}
try {
/** 先存取源文件*/
is = myFile.getInputStream();
fs = new FileOutputStream(tempPath + myFile.getOriginalFilename());
//...
if (myFile.getSize() > 0) {
byte[] buffer = new byte[1024 * 1024];
int bytesum = 0;
int byteread = 0;
while ((byteread = is.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
fs.flush();
}
fs.close();
is.close();
}
//生成24位随机数作为压缩后的图片名
String randomName = UtilNet.getRandomNumberString(24);
/** 处理源文件 ,进行压缩再放置到新的文件夹*/
String oldPath = tempPath + myFile.getOriginalFilename();
String copyPath = newPath + randomName;
// 图片压缩
Boolean ys = zipWidthHeightImageFile(oldPath, copyPath, width,height, 1f);
if (ys){
imResult.setNewPath("/img/imgZip/"+randomName);
System.out.println("/img/imgZip/"+randomName);
log.info("img path====================>"+copyPath);
sta = true;
}
else{ sta = false;
}
} catch (Exception ex) {
ex.printStackTrace();
sta = false;
}
imResult.setResult(sta);
return imResult;
} /***
* 压缩制定大小图片
*
* @param oldPath 临时图片路径
* @param copyPath 压缩图片保存路径
* @param width 宽度
* @param height 高度
* @param quality 高清度
* @return
* @throws Exception
*/
private Boolean zipWidthHeightImageFile(String oldPath, String copyPath, int width, int height,
float quality) {
Boolean sta = false;
File oldFile = new File(oldPath);
File newFile = new File(copyPath);
if (oldFile == null) {
return null;
}
String newImage = null;
try {
/** 对服务器上的临时文件进行处理 */
Image srcFile = ImageIO.read(oldFile);
// int w = srcFile.getWidth(null);
// System.out.println(w);
// int h = srcFile.getHeight(null);
// System.out.println(h);
int w = srcFile.getWidth(null);
// System.out.println(w);
int h = srcFile.getHeight(null);
// System.out.println(h);
double bili;
if(width>0){
bili=width/(double)w;
height = (int) (h*bili);
}else{
if(height>0){
bili=height/(double)h;
width = (int) (w*bili);
}
} /** 宽,高设定 */
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
//String filePrex = oldFile.substring(0, oldFile.indexOf(‘.‘));
/** 压缩后的文件名 */
//newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length()); /** 压缩之后临时存放位置 */
FileOutputStream out = new FileOutputStream(newFile); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
/** 压缩质量 */
jep.setQuality(quality, true);
encoder.encode(tag, jep);
out.close();
sta = true;
} catch (Exception e) {
e.printStackTrace();
sta = false;
}
return sta;
}
}

其中需要的实体类为:

package com.net.entity;
/**
* 压缩图片返回的集合
* @author zhangdi
*
*/
public class ImgzipResult {
private boolean result;
private String newPath;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getNewPath() {
return newPath;
}
public void setNewPath(String newPath) {
this.newPath = newPath;
} }

工具类二:

  这个工具类中用到的实体类同上,如果上一个工具类不好用,可以试一试这个:

package com.net.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import javax.imageio.ImageIO; import com.net.entity.ImgzipResult;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 图片压缩工具类
*/
public class ImageZipUtil {
/**
* 等比例压缩图片文件<br> 先保存原文件,再压缩、上传
* @param oldFile 要进行压缩的文件
* @param newFile 新文件
* @param width 宽度 //设置宽度时(高度传入0,等比例缩放)
* @param height 高度 //设置高度时(宽度传入0,等比例缩放)
* @param quality 质量
* @return 返回压缩后的文件的全路径
*/
public static ImgzipResult zipImageFile(File oldFile,File newFile, int width, int height,
float quality) {
ImgzipResult imgzipResult = new ImgzipResult();
boolean bool = true;
if (oldFile == null) {
imgzipResult.setNewPath(null);
bool = false;
imgzipResult.setResult(bool);
return imgzipResult;
}
try {
/** 对服务器上的临时文件进行处理 */
Image srcFile = ImageIO.read(oldFile);
int w = srcFile.getWidth(null);
// System.out.println(w);
int h = srcFile.getHeight(null);
// System.out.println(h);
double bili;
if(width>0){
bili=width/(double)w;
height = (int) (h*bili);
}else{
if(height>0){
bili=height/(double)h;
width = (int) (w*bili);
}
}
/** 宽,高设定 */
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
//String filePrex = oldFile.getName().substring(0, oldFile.getName().indexOf('.'));
/** 压缩后的文件名 */
//newImage = filePrex + smallIcon+ oldFile.getName().substring(filePrex.length()); /** 压缩之后临时存放位置 */
FileOutputStream out = new FileOutputStream(newFile); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
/** 压缩质量 */
jep.setQuality(quality, true);
encoder.encode(tag, jep);
out.close(); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgzipResult.setNewPath(newFile.getAbsolutePath());
imgzipResult.setResult(bool);
return imgzipResult;
} /**
* 按宽度高度压缩图片文件<br> 先保存原文件,再压缩、上传
* @param oldFile 要进行压缩的文件全路径
* @param newFile 新文件
* @param width 宽度
* @param height 高度
* @param quality 质量
* @return 返回压缩后的文件的全路径
*/
public static String zipWidthHeightImageFile(File oldFile,File newFile, int width, int height,
float quality) {
if (oldFile == null) {
return null;
}
String newImage = null;
try {
System.out.println(oldFile);
/** 对服务器上的临时文件进行处理 */
Image srcFile = ImageIO.read(oldFile);
int w = srcFile.getWidth(null);
// System.out.println(w);
int h = srcFile.getHeight(null);
// System.out.println(h); /** 宽,高设定 */
BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
//String filePrex = oldFile.substring(0, oldFile.indexOf('.'));
/** 压缩后的文件名 */
//newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length()); /** 压缩之后临时存放位置 */
FileOutputStream out = new FileOutputStream(newFile); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
/** 压缩质量 */
jep.setQuality(quality, true);
encoder.encode(tag, jep);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newImage;
}
}

最新文章

  1. 主工程中合并库工程的Manifest文件
  2. MyEclipse中无法识别 sun.misc.BASE64Encoder
  3. hdu 1005 1021 递归超限 找规律 // 只要看题中n较大都是有规律的
  4. 1、iOS9 HTTP 不能正常使用的解决办法
  5. Python的基础--对象 转
  6. bzoj1853 bzoj2393
  7. Linux修改SSH连接数 重启SSH服务
  8. java导出数据Excel总结
  9. 【算法与数据结构】Java实现字符串的全排列及组合
  10. 201521123001《Java程序设计》第6周学习总结
  11. 十一、Hadoop学习笔记————数据库与数据仓库
  12. 《深入理解Bootstrap》读书笔记(一)
  13. Alpha第七天
  14. 移动端键盘密码输入框插件(jquery用于支付密码)
  15. Could not find or load main class org.apache.spark.deploy.yarn.ApplicationMaster
  16. 总结 推广app
  17. Hadoop---Exception in thread &quot;main&quot; java.lang.NullPointerException问题的解决
  18. es6数组的方法
  19. odoo12主题样式模块
  20. ios 中基本控件的定义

热门文章

  1. 数据结构实验之数组一:矩阵转置(SDUT 2130)
  2. P2051 [AHOI2009]中国象棋——DP(我是谁,我在哪,为什么)
  3. 1626:【例 2】Hankson 的趣味题
  4. Python3.5以上Celery4.2.1启动报错:ImportError: cannot import name &#39;LRUCache&#39; from &#39;kombu.utils.functional&#39;
  5. SpringBoot/SpringMVC 下载本地文件
  6. java基于jcifs.smb实现远程发送文件到服务器
  7. php+mysql模糊查询功能
  8. CodeIgniter问题:Unable to load the requested file: .php
  9. MSE, MAE, Huber loss详解
  10. Flutter 页面下拉刷新和上拉加载