package util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
public class ImageWorker {
/**
*
*
* 方法说明: 图片压缩
*
* @param imageBytes
* @param toWidth
* @param toHeight
* @return
*/
public byte[] compression(byte[] imageBytes, int toWidth, int toHeight) {
ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
BufferedImage src = null;
ByteArrayOutputStream out = null;
ImageWriter imgWrier;
imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
try {
src = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
src.getGraphics().drawImage(ImageIO.read(is), 0, 0, toWidth, toHeight, null);
out = new ByteArrayOutputStream(imageBytes.length);
imgWrier.reset();
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
imgWrier.write(null, new IIOImage(src, null, null), null);
imageBytes = out.toByteArray();
out.flush();
out.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageBytes;
}
public byte[] compression(byte[] imageBytes, int toWidth) {
ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
ByteArrayInputStream is_scale = new ByteArrayInputStream(imageBytes);
BufferedImage src = null;
ByteArrayOutputStream out = null;
ImageWriter imgWrier;
imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
try {
src = ImageIO.read(is_scale);
Double scale = (double) toWidth / (double) src.getWidth();
int toHeight = (int) (src.getHeight() * scale);
src = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
src.getGraphics().drawImage(ImageIO.read(is), 0, 0, toWidth, toHeight, null);
out = new ByteArrayOutputStream(imageBytes.length);
imgWrier.reset();
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
imgWrier.write(null, new IIOImage(src, null, null), null);
imageBytes = out.toByteArray();
out.flush();
out.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageBytes;
}
}