wjbk

导航

java图片压缩

/**
     * 压缩图片并返回字节数组
     * @param file
     * @return
     * @throws Exception
     */
    private byte[] compress(File file) throws Exception {
        File temp = new File(file.getAbsolutePath());
        // scale:大小
        // outputQuality:输出质量
        Thumbnails.of(file).scale(1f).outputQuality(0.1f).toFile(temp);
        return Files.readAllBytes(temp.toPath());
    }

    /**
     * 压缩图片并返回字节数组
     * @param bytes
     * @return
     * @throws Exception
     */
    private byte[] compress(byte[] bytes, Boolean original) throws Exception {
        // scale:大小
        // outputQuality:输出质量
        if (bytes.length < 1024*1024 || Objects.equals(original, Boolean.TRUE)) {
            return bytes;
        }
        File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".jpeg");
        Thumbnails.of(new ByteArrayInputStream(bytes)).scale(1f).outputQuality(0.25f).toFile(tempFile);
        byte[] allBytes = Files.readAllBytes(tempFile.toPath());
        FileUtils.deleteQuietly(tempFile);
        return allBytes;
    }

 

posted on 2024-02-20 10:11  wjbk  阅读(38)  评论(0)    收藏  举报