/**
* 改变图片大小
*
* @param filePath 原图路径
* @param newFilePath 新图保存路径
* @param size 设置的宽度
* @throws IOException
*/
private void changeSize(String filePath, String newFilePath, int size) {
InputStream is = null;
try {
is = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedImage prevImage = null;
try {
prevImage = ImageIO.read(is);
} catch (IOException e) {
e.printStackTrace();
}
double width = prevImage.getWidth();
double height = prevImage.getHeight();
double percent = size / width;
int newHeight = Integer.parseInt((height * percent + "").substring(0, (height * percent + "").indexOf(".")));
System.out.println("设置的宽为" + size + " " + "高为" + newHeight);
try {
Thumbnails.of(filePath).size(size, newHeight).toFile(newFilePath);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 改变图片的尺寸
*
* @param newWidth, newHeight, path
* @return boolean
*/
public boolean changeSize(int newWidth, int newHeight, String path) {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(path));
//字节流转图片对象
Image bi = ImageIO.read(in);
//构建图片流
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
//绘制改变尺寸后的图
tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
//输出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//encoder.encode(tag);
ImageIO.write(tag, "PNG", out);
in.close();
out.close();
return true;
} catch (IOException e) {
return false;
}
}
补充pom.xml配置中引入依赖包
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<!-- 图片处理 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
java改变图片大小
最新推荐文章于 2024-07-14 19:55:19 发布