springboot上传图片并压缩

helei 2023-7-10 707 7/10
//压缩图片400KB以下
        int kb = 400 * 1024;
        long fileSize  = file.getSize();
        if (fileSize > 100 * 1024) {
            int smallSize = (int) (fileSize % kb == 0 ? fileSize / kb : fileSize / kb + 1);
            double size = Math.ceil(Math.sqrt(smallSize));
            log.info(String.valueOf(size));
            Image image = ImageIO.read(file.getInputStream());
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            //log.info(width+"x"+height);
            int widthSmall = (int) (width / size);
            int heightSmall = (int) (height / size);
            //log.info(widthSmall+"x"+heightSmall);
            BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
            Graphics g = buffi.getGraphics();
            g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
            g.dispose();
            //文件的名称
            String filename = file.getOriginalFilename().split("\\.")[0];
            //文件的格式
            String type = file.getOriginalFilename().split("\\.")[1];
            //将newImage写入字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(buffi,type,baos);
            //将文件储存到本地
            //ImageIO.write(buffi, "jpg", new File("H:\\work\\yz\\img\\"+filename+ (new Random().nextInt(10000) + 1)+"."+type));
            file = new MockMultipartFile(file.getOriginalFilename(), baos.toByteArray());
        }
- THE END -

helei

7月10日17:19

最后修改:2023年7月10日
0

非特殊说明,本博所有文章均为博主原创。