图片转Base64编码字节数据

    /**
     * 身份证图片下载到服务器本地 并返回图片Base64编码字节数据
     */
    public String downLoad(String downLoadUrl) {
        String randomNo = getRandomNo();
        //项目文件夹下生成download文件夹
        File savePath = new File(System.getProperty("user.dir") + File.separator + "download");
        if (!savePath.exists()) {
            savePath.mkdir();
        }
        URL url = null;
        try {

            url = new URL(downLoadUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath.getPath() + File.separator + randomNo + ".jpeg"));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();


            File file = new File(savePath.getPath() + File.separator + randomNo + ".jpeg");
            Thumbnails.of(file)
                    .scale(0.5f) //图片大小(长宽)压缩 从0按照
                    .outputQuality(0.5f) //图片质量压缩比例 从0-1,越接近1质量越好
                    .toOutputStream(new FileOutputStream(savePath.getPath() + File.separator + randomNo+"1" + ".jpeg"));
            File file2 = new File(savePath.getPath() + File.separator + randomNo+"1" + ".jpeg");
            //读取图片字节数组
            InputStream ins = null;
            byte[] data = null;
            ins = new FileInputStream(file2);
            data = new byte[ins.available()];
            ins.read(data);
            ins.close();



            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            System.out.println(encoder.encode(data));

            return encoder.encode(data);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            savePath.delete();
        }
        return null;
    }




 /**
     * 获取随机流水号
     */
    public String getRandomNo() {
        String timeStr = DateUtil.getCurrentTime();
        //随机数 不小于6位数
        Random random = new Random();
        int rd = random.nextInt(899999);
        rd = rd + 100000;
        String rdStr = Integer.toString(rd);
        String randomStr = timeStr.concat(rdStr);
        return randomStr;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值