java处理图片压缩,或者压缩并加水印
package com.hannan.ehu.test.java;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class PictureUtils {
private static Logger log = LoggerFactory.getLogger(PictureUtils.class);
/**
* 图片压缩
* @param picSteam 图片流
* @param width 宽度
* @return
*/
public static InputStream compress(InputStream picSteam,int width){
try {
BufferedImage bufImg = ImageIO.read(picSteam);
int realWidth=bufImg.getWidth();
int realHeight=bufImg.getHeight();
int height = realHeight*width/realWidth;
if(width<realWidth){
height = realHeight;
width = realWidth;
}
BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Image scaleImage = bufImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);
// buf.getGraphics().drawImage(scaleImage,0,0,null); // 单纯压缩图片
// 加水印处理
Graphics2D graphics=buf.createGraphics();
graphics.drawImage(scaleImage,0,0,null);
graphics.setColor(Color.white);
int fontSize=20;
graphics.setFont(new Font("黑体",36,fontSize));
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
graphics.drawString("我是水印", width - (4 * fontSize), height - fontSize );
graphics.dispose();
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
imgWriter.reset();
imgWriter.setOutput(ImageIO.createImageOutputStream(bos));
imgWriter.write(null, new IIOImage(buf, null, null), imgWriteParams);
InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
inputStream.close();
return new ByteArrayInputStream(bos.toByteArray());
} catch (IOException e) {
log.error("图片压缩io异常:PictureUtils.compress<==>" + e.getMessage());
return null;
}
}
public static void main(String[] args) {
File file =new File("E:\\chromeDownload\\精美图片\\73a1854c88278518121b0e5d89b591d8.jpg");
try {
InputStream inputStream=compress(new FileInputStream(file),800);
if(inputStream!=null){
byte[] buffer = new byte[inputStream.available()];
int length=inputStream.read(buffer);
OutputStream outStream = new FileOutputStream("E:\\chromeDownload\\精美图片\\test02.jpg");
log.info("大小为:"+length);
outStream.write(buffer);
inputStream.close();
outStream.flush();
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}