图片压缩java工具类
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;
}
}
图片压缩java工具类的更多相关文章
- java工具类系列 (四.SerializationUtils)
java工具类系列 (四.SerializationUtils) SerializationUtils该类为序列化工具类,也是lang包下的工具,主要用于序列化操作 import java.io.Se ...
- Java工具类——通过配置XML验证Map
Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...
- 排名前 16 的 Java 工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- 排名前16的Java工具类
原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...
- 第一章 Java工具类目录
在这一系列博客中,主要是记录在实际开发中会常用的一些Java工具类,方便后续开发中使用. 以下的目录会随着后边具体工具类的添加而改变. 浮点数精确计算 第二章 Java浮点数精确计算 crc32将任意 ...
- java工具类之按对象中某属性排序
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang ...
- 干货:排名前16的Java工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- Java工具类:给程序增加版权信息
我们九天鸟的p2p网贷系统,基本算是开发完成了. 现在,想给后端的Java代码,增加版权信息. 手动去copy-paste,太没有技术含量. 于是,写了个Java工具类,给Java源文件 ...
- 常用高效 Java 工具类总结
一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...
随机推荐
- seq2seq聊天模型(一)
原创文章,转载请注明出处 最近完成了sqe2seq聊天模型,磕磕碰碰的遇到不少问题,最终总算是做出来了,并符合自己的预期结果. 本文目的 利用流程图,从理论方面,回顾,总结seq2seq模型, seq ...
- 最简单的babel+webpack配置
首先先介绍一下2个重要的库:core-js 和 regenerator core-js core-js 是用于 JavaScript 的组合式标准化库,它包含 es5 (e.g: object.fre ...
- 解决“cv2.error: OpenCV(3.4.2) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356:...”
主要是图片路径中“文件夹分隔符”使用的错误 将“\”改成“/”就好了 修改后的测试代码如下:x.py #导入cv模块 import cv2 as cv #读取图像,支持 bmp.jpg.png.tif ...
- OpenJudge1.5.6:整数序列的元素最大跨度值
描述 给定一个长度为n的非负整数序列,请计算序列的最大跨度值(最大跨度值 = 最大值减去最小值). 输入一共2行,第一行为序列的个数n(1 <= n <= 1000),第二行为序列的n个不 ...
- allowMultiQueries=true mybatis 要多行sql执行,一定要注意
allowMultiQueries=true 这个配置已经出现多次问题了,这次由于切换时多数据源,搞配置的同志不知道从哪里copy的配置,只换了我们的链接,我们之前配置了好多配置都丢失了,我的代码中有 ...
- JavaWeb_(SpringMVC框架)SpringMVC入门
Spring MVC又叫SpringWebMVC是一个轻量级的基于请求响应的表现层框架.它是Spring框架的一部分.SpringMVC与Struts2都可以替代原始Servlet技术. Spring ...
- ACM之路(12)—— KMP & 扩展KMP & Manacher
最近做完了kuangbin的一套关于kmp的题目(除了一道字典树的不会,因为还没学字典树所以先放放),做个总结.(kuangbin题目的链接:http://acm.hust.edu.cn/vjudge ...
- spring事务在web环境中失效的问题
今天温习一下spring事务的时候,出现了一种诡异的现象,在java环境中测试事务是可以的.然后到web下测试事务就没用了.spring.xml配置 spring-mvc.xml配置 后来百度发现是因 ...
- 数据库安装后无法访问且mysql重启报错的解决方法
数据库安装后无法访问,mysql重启报错: 或报错:MySQL is running but PID file could not be found 解决方法: 第一种方法:看磁盘是否已满:df –h ...
- 如何使用纯js实现一个带有灰色半透明背景的弹出框
原文如何使用纯js实现一个带有灰色半透明背景的弹出框 // 加入透明背景 var body = document.body;var backgroundDiv = document.createEle ...