图片压缩,缩放,将File转为byte[]

2020-07-19  本文已影响0人  何佳阳
/** 判断文件是否满足正方形和小于指定大小,指定宽高度,若缩放后仍大于指定大小则

* @param file

* @param destPath

* @param minWidth

* @param maxKB

* @return

* @throws IOException

* @throws InterruptedException

*/

public static ResponseResult checkFileAndZoom(File file, String destPath, int minWidth, int maxKB) throws IOException, InterruptedException {

    ResponseResult rs = checkImageIsSquare(file, minWidth);

    if (!rs.getIsSuccess() || rs.getCode() == 1) {

        return rs;

    }

    byte[] bytes = file2byte(file);

    File destFile = new File(destPath);

    destFile.createNewFile();

    if (!destFile.getParentFile().exists()) {

        destFile.getParentFile().mkdirs();

    }

    compressPhotoByQuality(minWidth, minWidth, bytes, 1F, maxKB*1024, destPath);

    File resizeFile = new File(destPath);

    if (resizeFile.length() >= maxKB * 1024) {

        resizeFile.delete();

        ResultGenerator.error("缩放后的图片大小大于" + maxKB + "KB,请重新上传");

    }

    return ResultGenerator.success(destPath);

}

public static byte[] compressPhotoByQuality(int destWidth, int destHeight, byte[] bytes, Float quality, long maxByteLength, String destPath) throws IOException {

    if (bytes == null) {

        return bytes;

    }

    long fileSize = bytes.length;

    if (fileSize <= maxByteLength) {

        return bytes;

    } else {

        quality = quality - 0.1F;

    }

    if (quality < 0.6) {

        return bytes;

    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Thumbnails.of(new ByteArrayInputStream(bytes)).size(destWidth, destHeight).outputQuality(quality).outputFormat(destPath.substring(destPath.lastIndexOf(".") + 1)).toFile(destPath);

    //递归

    return compressPhotoByQuality(destWidth, destHeight, out.toByteArray(), quality, maxByteLength, destPath.substring(destPath.lastIndexOf(".") + 1));

}

/**

* 将文件转换成byte数组

* @param tradeFile

* @return

*/

public static byte[] file2byte(File tradeFile){

    byte[] buffer = null;

    try

    {

        FileInputStream fis = new FileInputStream(tradeFile);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        byte[] b = new byte[1024];

        int n;

        while ((n = fis.read(b)) != -1)

        {

            bos.write(b, 0, n);

        }

        fis.close();

        bos.close();

        buffer = bos.toByteArray();

    } catch (IOException e){

        e.printStackTrace();

    }

    return buffer;

}
上一篇 下一篇

猜你喜欢

热点阅读