1.方法一 jdk自带包
/**
*
* @param imageUrl 原图片地址
* @param outFile 新图片文件
* @param newWidth 指定宽度
* @param quality 图片质量比(<1)
*/
public static void resize(String imageUrl, File outFile, int newWidth, float quality) {
if (quality > 1) {
throw new IllegalArgumentException(
"Quality has to be between 0 and 1");
}
FileOutputStream out = null;
try {
File originalFile = new File(imageUrl);
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
//if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
/ iWidth, Image.SCALE_SMOOTH);
/*} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
newWidth, Image.SCALE_SMOOTH);
}*/
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// Soften.
float softenFactor = 0.05f;
float[] softenArray = {0, softenFactor, 0, softenFactor,
1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0};
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
// Write the jpeg to a file.
out = new FileOutputStream(outFile);
ImageIO.write(bufferedImage, "jpg", out);
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
方法二 google之Thumbnails图片等比压缩
maven之pom.xml依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
/**
* @param imageUrl 原图片url
* @param newWidth 压缩后宽度
* @param quality 图片质量(<1)
* @return
*/
public String imageZoom(String imageUrl, int newWidth, float quality) {
ImageIcon imageIcon = new ImageIcon(imageUrl);
int iconWidth = imageIcon.getIconWidth();
int iconHeight = imageIcon.getIconHeight();
try {
//压缩后图片保存地址
String imagePath = ""E:/PICTURE/4.jpg"
Integer height = (newWidth * iconHeight) / iconWidth;
Thumbnails.of(imageUrl).size(newWidth, height).outputQuality(quality).toFile(imagePath);
return imagePath;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}