Created
August 7, 2020 06:59
-
-
Save czwen/979259d57bffc331354cdc5fbdeee1bf to your computer and use it in GitHub Desktop.
thumb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ImageCompressUtil { | |
/** | |
* 强制压缩/放大图片到固定的大小 | |
* | |
* @param fileName 压缩文件("c:\\1.png") | |
* @param targetHeight | |
* @param targetWidth | |
* @return | |
*/ | |
public static BufferedImage resize(String fileName, int targetWidth, int targetHeight) { | |
BufferedImage img = null;//原图 | |
BufferedImage compressImg = null;//压缩后图 | |
int width, height; | |
try { | |
File file = new File(fileName); | |
img = ImageIO.read(file); | |
double srcHeight = img.getHeight(); | |
double srcWidth = img.getWidth(); | |
if (img.getWidth() > img.getHeight()) { | |
// 宽 | |
double scalingFactor = targetWidth / srcWidth; | |
width = targetWidth; | |
height = (int) (img.getHeight() * scalingFactor); | |
} else { | |
// 高 | |
double scalingFactor = targetWidth / srcHeight; | |
width = (int) (img.getWidth() * scalingFactor); | |
height = targetHeight; | |
} | |
compressImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); | |
compressImg.getGraphics().drawImage(img, 0, 0, width, height, null); // 绘制缩小后的图 | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return compressImg; | |
} | |
/** | |
* @param file 存放位置("c:\\1.png") | |
* @param img | |
*/ | |
public static void writeToFile(String file, BufferedImage img) { | |
try { | |
File destFile = new File(file); | |
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流 | |
ImageIO.write(img, "png", out); | |
out.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment