import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class NarrowImage {
/**
* @param im
* 原始图像
* @param resizeTimes
* 倍数,比如0.5就是缩小一半,0.98等等double类型
* @return 返回处理后的图像
*/
public BufferedImage zoomImage(String src) {
BufferedImage result = null;
try {
File srcfile = new File(src);
if (!srcfile.exists()) {
System.out.println("文件不存在");
}
BufferedImage im = ImageIO.read(srcfile);
int width = im.getWidth();
int height = im.getHeight();
float resizeTimes = 0.3f;
int toWidth = (int) (width * resizeTimes);
int toHeight = (int) (height * resizeTimes);
result = new BufferedImage(toWidth, toHeight,
BufferedImage.TYPE_INT_RGB);
result.getGraphics().drawImage(
im.getScaledInstance(toWidth, toHeight,
java.awt.Image.SCALE_SMOOTH), 0, 0, null);
} catch (Exception e) {
System.out.println("创建缩略图发生异常" + e.getMessage());
}
return result;
}
public boolean writeHighQuality(BufferedImage im, String fileFullPath) {
try {
FileOutputStream newimage = new FileOutputStream(fileFullPath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im);
jep.setQuality(0.9f, true);
encoder.encode(im, jep);
newimage.close();
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
String inputFoler = "E:\\11.jpg" ;
String outputFolder = "E:\\12.jpg";
NarrowImage narrowImage = new NarrowImage();
narrowImage.writeHighQuality(narrowImage.zoomImage(inputFoler), outputFolder);
}
}