使用的是JPEGImageEncoder,它是sun.awt.image.codec包中的一个类,这个包是Java标准版中的一个内部包,可能在其他的Java版本或者不同的JDK实现中不可用。
所以使用的时候需要maven配置一下:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
<compilerArguments>
<verbose/>
<bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>
</compilerArguments>
</configuration>
</plugin>
然后才可以正常使用sun.awt.image.codec包中的类,其实不配置以上代码运行在本地是没有问题的,但是当打包的时候会打不进去。所以建议配置上面的代码。
其他不说了,直接上代码:
private static void doWithPhoto(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
String filePath = file.getPath();
BufferedImage image = null;
FileOutputStream os = null;
try {
image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
String fileExtension = filePath.substring(filePath.lastIndexOf("."));
String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.lastIndexOf("."));
os = new FileOutputStream(file.getParent() + "/compress_" + fileName + fileExtension);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(bfImage);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
其实JPEGImageEncoder已经过时了,使用ImageIO来进行图片压缩也是很方便的,
但小Z觉得还是PEGImageEncoder处理更好一点。
小Z已经将压缩图片的功能做成windows桌面应用了,以便于开发和办公。
有需要源码的小伙伴可以关注公众号,小程序内免费获得,欢迎联系技术沟通,让我们共同进步吧!!!