【Java基础】图片压缩

最近有个需求,需要把图片字节码用Base64 encode之后作为请求报文的一部分调用外部服务方,服务方对图片的大小有要求,不能超过500KB,另一方面,请求报文太大,会出现如下错误:413 请求体过大

先看下现在的图片:

如果是线上的图片,我也写了个获取图片字节码,查看图片大小的小程序

public class GetImgSize {

    public static void main(String[] args) {

        String posUrl = "http://file11info.ppdai.com/4e598e3bd163405d90d8f7b7783d494d.jpg";

        byte[] a = getBy(posUrl);

        System.out.println(a.length);
    }

    private static byte[] getBy(String posUrl){
        try {
            URL url = new URL(posUrl);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            try(InputStream inputStream = url.openStream()){
                int len = 0;
                byte[] buffer = new byte[1024];
                while (-1 != (len = inputStream.read(buffer))){
                    outputStream.write(buffer, 0, len);
                }
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

压缩函数如下

public class GetImgSize {

    public static void main(String[] args) throws IOException {

        String posUrl = "http://file11info.ppdai.com/4e598e3bd163405d90d8f7b7783d494d.jpg";

        byte[] a = compress(posUrl);

        System.out.println(a.length);

        File output = new File("./duke-compressed-005.jpg");
        OutputStream out = null;
        try {
            out = new FileOutputStream(output);
            out.write(a);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out != null){
                out.flush();
                out.close();
            }
        }
    }
private static byte[] compress(String posUrl) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageOutputStream ios = null;
byte [] data = null;
ImageWriter writer = null;
try {
URL url = new URL(posUrl);
BufferedImage bufferedImage = ImageIO.read(url);

writer = ImageIO.getImageWritersByFormatName("jpg").next();

ios = ImageIO.createImageOutputStream(bos);

writer.setOutput(ios);

ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()){
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.5f);
}

writer.write(null, new IIOImage(bufferedImage, null, null), param);

data = bos.toByteArray();

return data;
} catch (Exception e) {
e.printStackTrace();
}finally {
bos.close();

if(ios != null){
ios.close();
}

if(writer != null){
writer.dispose();
}
}
return null;
}
 }

猜你喜欢

转载自www.cnblogs.com/zhengwangzw/p/10902930.html