“程序包com.sun.image.codec.jpeg不存在“ 正解

问题现象

开发环境: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 "";
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值