加哥最近在写代码过程中需要将上传的图片进行自动压缩,但是又不能借助插件,下来就把代码分享给志同道合的小伙伴吧,在运行过程中一定需要注意图片路径输入正确。
public static void main(String[] args) {
try {
String inputImagePath = "D:\\500540b041a30ad044b5a19344f1b24f.png"; // 输入图片路径
String outputImagePath = "D:\\500540b041a30ad044b5a19344f1b24f.png"; // 输出图片路径
int targetSizeKB = 8; // 目标压缩大小(KB)
BufferedImage image = ImageIO.read(new File(inputImagePath));
Image compressedImage = compressImage(image, targetSizeKB);
ImageIO.write((BufferedImage) compressedImage, "jpg", new File(outputImagePath));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static Image compressImage(BufferedImage image, int targetSizeKB) {
// 计算目标图片的尺寸
long targetSizeBytes = targetSizeKB * 1024;
long originalSizeBytes = getImageSize(image);
double compressionRatio = (double) targetSizeBytes / originalSizeBytes;
int targetWidth = (int) (image.getWidth() * Math.sqrt(compressionRatio));
int targetHeight = (int) (image.getHeight() * Math.sqrt(compressionRatio));
// 使用ImageIO进行压缩
BufferedImage compressedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
compressedImage.getGraphics().drawImage(image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);
return compressedImage;
}
public static long getImageSize(BufferedImage image) {
File tempFile;
try {
tempFile = File.createTempFile("temp", ".tmp");
ImageIO.write(image, "jpg", tempFile);
long size = tempFile.length();
tempFile.delete();
return size;
} catch (IOException ex) {
ex.printStackTrace();
return 0;
}
}
public static void main(String[] args) throws IOException { // 读取图片文件 /**File input = new File("D:\\1691455935941.jpg"); BufferedImage image = ImageIO.read(input); // 压缩图片 BufferedImage compressedImage = compress(image, 0.5f); // 保存压缩后的图片 File output = new File("D:\\"); ImageIO.write(compressedImage, "jpg", output);**/ File img = new File("D:\\500540b041a30ad044b5a19344f1b24f.jpg"); System.out.println("输入的图片大小:" + img.length()/1024 + "KB"); String outputDir = "D:\\"; PicUtils.thumbnail_w_h(img, 0,0, outputDir); } public static BufferedImage compress(BufferedImage image, float quality) throws IOException { // 创建新的图片对象 BufferedImage compressedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); // 设置压缩质量 java.util.Iteratoriterator = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = iterator.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); // 压缩图片 writer.setOutput(ImageIO.createImageOutputStream(compressedImage)); writer.write(null, new IIOImage(image, null, null), param); return compressedImage; } /** * 按照指定的宽高压缩原图 * @param img * @param outputDir */ public static void thumbnail(File img, int destWidth, int destHeight,String outputDir){ System.out.println("图片压缩开始"); long startTime = System.currentTimeMillis(); try { //读取源图 BufferedImage BI = ImageIO.read(img); double srcWidth = BI.getWidth(); // 源图宽度 double srcHeight = BI.getHeight(); // 源图高度 if ((int)srcWidth >= destWidth && (int)srcHeight >= destHeight) { String imageFullName = img.getName(); String prefix = imageFullName.substring(0,imageFullName.lastIndexOf(".")); String suffix = imageFullName.substring(imageFullName.lastIndexOf(".")); String newName = prefix+suffix ; OutputStream fos =new FileOutputStream(outputDir+File.separatorChar+newName); Image image = BI.getScaledInstance(destWidth, destHeight, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.setColor(Color.RED); g.drawImage(image, 0, 0, null); //绘制处理后的图 g.dispose(); ImageIO.write(tag, "JPEG", fos); System.out.println("图片压缩结束"); long endTime = System.currentTimeMillis(); System.out.println("图片压缩共计耗时:" +(endTime-startTime)+"毫秒" ); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 按照宽高等比例缩放(缩小或放大) * @param img * @param width * @param height * @param outputDir */ public static void thumbnail_w_h(File img,int destWidth,int destHeight,String outputDir){ try { BufferedImage bi = ImageIO.read(img); double srcWidth = bi.getWidth(); // 源图宽度 double srcHeight = bi.getHeight(); // 源图高度 double scale = 1;//缩放比例因子,大于1表示放大,小于1表示缩小 if (destWidth > 0 && destHeight > 0) { //下面这个缩放比例因子取值很好理解,目标尺寸和原图尺寸的比值越大, //表示缩放的比率越小,也就代表图片变形的越小,就取影响图片变形小的比例因子 scale = destHeight/srcHeight < destWidth/srcWidth ? destHeight/srcHeight : destWidth/srcWidth; } thumbnail(img, (int)(srcWidth * scale),(int)(srcHeight * scale),outputDir); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }