实际开发之图片按比例压缩

import com.lufax.g.media.utils.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
* 压缩图片
* Created by shazhipeng880 on 19-10-11.
*/
@Service
public class CompressImgService {

public InputStream compressImgByWidth(InputStream inputStream, Integer width){

OutputStream os = null;
InputStream is = null;
String fileName = "1.jpg";

//保存图片到临时路径
savePic(inputStream, fileName);

//缩略后图片临时存放地址
String destination = System.getProperty("java.io.tmpdir") + File.separator + fileName;

try {
BufferedImage image = ImageIO.read(new FileInputStream(destination));

os = new FileOutputStream(destination);

//原图宽度
int srcWidth = image.getWidth();
//原图高度
int srcHeight = image.getHeight();
//缩略后宽度
int compressWidth = width.intValue();
//缩略比例
int rate = srcWidth/compressWidth;

//计算缩略后高度
int compressHeight = srcHeight/rate;

BufferedImage bufferedImage = new BufferedImage(compressWidth, compressHeight, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(image.getScaledInstance(compressWidth, compressHeight, image.SCALE_SMOOTH), 0, 0, null);

String imageType = "jpg";
ImageIO.write(bufferedImage, imageType, os);

//缩略后图片的流
is = new FileInputStream(destination);

} catch (FileNotFoundException e) {

} catch (IOException e) {

} finally {
if(null != os){
try {
os.close();
} catch (IOException e) {

}
}

//删除临时文件
deleteFile(destination);

return is;
}
}

public void savePic(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
String path = System.getProperty("java.io.tmpdir");
// 2、保存到临时文件
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流保存到本地文件

File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
int available = inputStream.available();
// 开始读取
while ((len = inputStream.read(bs)) != -1) {
os.write(bs, 0, len);
}

} catch (IOException e) {

} catch (Exception e) {

} finally {
// 完毕,关闭所有链接
if(null != inputStream){
try {
inputStream.close();
os.close();
} catch (IOException e) {

}
}
}
}

public boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}


}

猜你喜欢

转载自www.cnblogs.com/it-szp/p/11672421.html
今日推荐