JAVA按比例压缩图片

wylc123 1年前 ⋅ 426 阅读

有时候项目中会遇到前端上传图片,后台需要前端返回原图和按原图比例缩小的压缩图片,此时就需要JAVA来进行图片压缩了,赶紧上代码:

/**
     *
     * @param sourcePath 图片来源路径
     * @param thumbnailPath 压缩输出路径
     * @param width 图片宽
     * @param heigh 图片的高
     * @return
     */
    public static String thumbnailImg(String sourcePath,String thumbnailPath,int width,int heigh) {
  
        Float rate = 0.5f;          //按原图片比例压缩(默认)
        int widthdist= 255;
        int heightdist= 255;
        try {
            File srcfile = new File(sourcePath);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
               return null;
            }
            // 如果比例不为空则说明是按比例压缩
            if (rate != null && rate > 0) {
                //获得源图片的宽高存入数组中
                    //按比例缩放或扩大图片大小,将浮点型转为整型
                    widthdist = (int) (width * rate);
                    heightdist = (int) (heigh * rate);
  
            }
            // 开始读取文件并进行压缩
            java.awt.Image src = ImageIO.read(srcfile);
            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
            //绘制图像
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
            String formatName = thumbnailPath.substring(thumbnailPath.lastIndexOf(".") + 1);
            ImageIO.write(tag, formatName , new File(thumbnailPath) );
            return thumbnailPath;
        } catch (Exception ef) {
            log.info("--------------->压缩图片失败");
            ef.printStackTrace();
        }
        return null;
    }

如此java便按比例进行了图片压缩。


相关文章推荐
  • 该目录下还没有内容!

全部评论: 0

    我有话说: