根据byte数组图片压缩

package com.example.test.demo;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * 图片压缩,图片byte数据
 *
 */
public class 图片压缩 {

 /**
  *
  * @param imgByte 图片byte数据
  * @param outputWidth 压缩后的宽度
  * @return
  * @throws Exception
  */
    public static byte[] imageCompresPicFixedWidth(byte[] imgByte, int outputWidth) throws Exception {
        if (imgByte == null || imgByte.length <= 0) {
            return null;
        }
        int newWidth, newHeight;
        Image image = ImageIO.read(new ByteArrayInputStream(imgByte));
        System.out.println(image.getWidth(null));
        System.out.println(image.getHeight(null));
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        if (image.getWidth(null) < outputWidth && image.getHeight(null) < outputWidth) {
            return imgByte;
        }

        DecimalFormat df = new DecimalFormat("0.00");
        if (image.getWidth(null) >= image.getHeight(null)) {
            newWidth = outputWidth;
            String d = df.format((float) outputWidth / imageWidth);
            float dff = Float.parseFloat(d);
            newHeight = (int) (dff * imageHeight);
        } else {
            newHeight = outputWidth;
            String d = df.format((float) outputWidth / imageHeight);
            float dff = Float.parseFloat(d);
            newWidth = (int) (dff * imageWidth);
        }

        BufferedImage buffImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        buffImg.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
        ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
        try {
            //这里可以转变图片的编码格式
            ImageIO.write(buffImg, "jpg", imageStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageStream.toByteArray();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值