当前位置: 首页 > news >正文

【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;
}
 }

 

转载于:https://www.cnblogs.com/zhengwangzw/p/10902930.html

相关文章:

  • Nginx反向代理,负载均衡,redis session共享,keepalived高可用
  • Python进阶之路 3.5.4 循环中的else语句
  • 【更新】Stimulsoft Reports v2019.3.1发布,新增对OData v4的支持功能
  • 7天瓜分36万美妆,勇敢“晒丫”才是年轻人的生活方式
  • 宜信开源微服务任务调度平台(SIA-TASK)
  • Centos7.6安装jdk1.8
  • 原生革命--跨平台开发技术解析
  • 常用注解
  • 前端目录
  • 自助式BI分析,有什么优点
  • 使用Ajax和FormData对象实现单图片上传,多图片上传,以及和对象的综合上传
  • 微信小程序开发避坑
  • 力扣算法题—098验证二叉搜索树
  • Navicat连接MySQL8.0出现1251-Client does not support authentication protocol requested by server;
  • vue实际应用vue-router
  • hexo+github搭建个人博客
  • 【挥舞JS】JS实现继承,封装一个extends方法
  • C# 免费离线人脸识别 2.0 Demo
  • co模块的前端实现
  • Just for fun——迅速写完快速排序
  • Python代码面试必读 - Data Structures and Algorithms in Python
  • Python学习之路16-使用API
  • underscore源码剖析之整体架构
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 分类模型——Logistics Regression
  • 高度不固定时垂直居中
  • 前端性能优化--懒加载和预加载
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 一些css基础学习笔记
  • 运行时添加log4j2的appender
  • 职业生涯 一个六年开发经验的女程序员的心声。
  • FaaS 的简单实践
  • ionic异常记录
  • 阿里云服务器购买完整流程
  • #NOIP 2014# day.2 T2 寻找道路
  • #微信小程序:微信小程序常见的配置传旨
  • (3)(3.5) 遥测无线电区域条例
  • (31)对象的克隆
  • (C语言)fread与fwrite详解
  • (非本人原创)史记·柴静列传(r4笔记第65天)
  • (分布式缓存)Redis持久化
  • (附源码)springboot青少年公共卫生教育平台 毕业设计 643214
  • (附源码)springboot人体健康检测微信小程序 毕业设计 012142
  • (附源码)springboot助农电商系统 毕业设计 081919
  • (附源码)ssm户外用品商城 毕业设计 112346
  • (完整代码)R语言中利用SVM-RFE机器学习算法筛选关键因子
  • (五) 一起学 Unix 环境高级编程 (APUE) 之 进程环境
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (原創) 未来三学期想要修的课 (日記)
  • (轉貼) UML中文FAQ (OO) (UML)
  • .[hudsonL@cock.li].mkp勒索病毒数据怎么处理|数据解密恢复
  • .NET Core WebAPI中使用Log4net 日志级别分类并记录到数据库
  • .net mvc部分视图
  • .NET/C# 获取一个正在运行的进程的命令行参数