java圖片放大或縮小
阿新 • • 發佈:2018-11-05
package org.jimmy.autotranslate20181022.utils; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Utils { public static void zoomInImage(String srcPath, String newPath, int maxWidth, int maxHeight) throws Exception { BufferedImage bufferedImage= null; File file = new File(srcPath); bufferedImage = ImageIO.read(file); if(bufferedImage != null){ bufferedImage = zoomInImage(bufferedImage, maxWidth, maxHeight); ImageIO.write(bufferedImage, "jpg", new File(newPath)); System.out.println("生成圖片完成!"); } } private static BufferedImage zoomInImage(BufferedImage originalImage, int maxWidth, int maxHeight) { BufferedImage newImage = new BufferedImage(maxWidth, maxHeight, originalImage.getType()); Graphics g = newImage.getGraphics(); g.drawImage(originalImage,0, 0, maxWidth, maxHeight, null); g.dispose(); return newImage; } }
不需要對寬和高進行判斷,在傳參時直接給定寬高就行了.如width * 2, height * 2,width * 0.6, height * 0.6,如果寬高比例不同,圖片失真會比較大,太過放大圖片也會明顯失真.