最近有个需求,需要把图片字节码用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); //压缩比 不够可以设置0.05 } writer.write(null, new IIOImage(bufferedImage, null, null), param); data = bos.toByteArray(); bos.close(); ios.flush(); ios.close(); writer.dispose(); return data; } catch (Exception e) { e.printStackTrace(); }finally { bos.close(); if(ios != null){ ios.close(); } if(writer != null){ writer.dispose(); } } return null; } }
原文地址:https://www.cnblogs.com/zhengwangzw/p/10902930.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。