1. 程式人生 > >java開發等比例壓縮照片,傳入byte陣列,返回byte陣列

java開發等比例壓縮照片,傳入byte陣列,返回byte陣列

    public static byte [] scaleImage(byte [] photo) {
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(photo);    //將b作為輸入流;
            BufferedImage image = ImageIO.read(in);     //將in作為輸入流,讀取圖片存入image中,而這裡in可以為ByteArrayInputStream();
            int imageWidth = image.getWidth();
            double scale = (double) 600 / imageWidth;
            int imageHeight = image.getHeight();
            int height = (int) (imageHeight * scale);
            int width = (int) (imageWidth * scale);
            AffineTransform scaleTransform = AffineTransform.getScaleInstance(scale, scale);
            AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);
            BufferedImage image1 = bilinearScaleOp.filter(image, new BufferedImage(width, height, image.getType()));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean flag = ImageIO.write(image1, "jpg", out);
            if(!flag){
                logger.info("壓縮上傳大資料抓拍照片失敗");
            }
            photo = out.toByteArray();
        } catch (Exception e) {
            logger.error("圖片壓縮出錯:", e);
            return photo;
        }
        return photo;
    }

借鑑:https://blog.csdn.net/wfs31415926/article/details/79392357/