问题现象
开发环境:jdk1.8
工具:idea、maven
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project center-strategy-facade-impl: Compilation failure: Compilation failure:
*****:程序包com.sun.image.codec.jpeg不存在
- 问题代码
FileOutputStream out=null;
try
{
//outPath文件输入绝对路径
out=new FileOutputStream(outPath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//bufferedImage
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(100, true);
encoder.encode(bufferedImage, param);
out.close();
}
catch(Exception e)
{
return false;
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
解决后代码变为
程序包com.sun.image.codec.jpeg在jdk1.7之后都不支持。使用变通方法,使用ImageIO.write方法生成图片
FileOutputStream out=null;
try
{
//outPath文件输入绝对路径
out=new FileOutputStream(outPath);
ImageIO.setUseCache(false);
ImageIO.write(bufferedImage,"jpg",out);
out.close();
}
catch(Exception e)
{
return false;
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 获取文件绝对路径
上述的outPath可以通过以下方法获取,例如outPath=getFilePath(“classpath:static/images”)+"/temp.jpg";
private String getFilePath(String filePath){
File file = null;
try {
file = ResourceUtils.getFile(filePath);
if (file==null){
return "";
}
System.err.println(file.getPath());
return file.getPath();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "";
}
}