Java 代码处理base64的图片文件,前后台显示

4 篇文章 0 订阅

前台图片已base64格式传入,后台写入本地文件夹目录中,代码如下:

//base64 图片解析 并写入到文件夹
	public static boolean generateImage(String data, String uuid) {
	//path代表本地路径  如 "Z:\\sbsqphoto\\"  这里的“” 要加 \ 转译   
		String path=imagepath+uuid+".jpg";
        if(data == null){
            return false;
        }
       //jdk 1.6 1.7 可以 使用BASE64Decoder 但是1.8 好像没有这个方法 我是用的项目自带的解码工具类
       // BASE64Decoder decoder = new BASE64Decoder();
       //byte[] bytes = bsBase64Decoder.decodeBuffer(baseContent);
        try{
            //解密
          //base64解密
    		byte[] bytes = Encodes.decodeBase64(data);
            
            //处理数据
            for (int i = 0;i<bytes.length;++i){
                if(bytes[i]<0){
                	bytes[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

写入之后怎么在页面显示呢:一般的 我们会将base64的图片以文本的形式直接存入到数据库中,使用时可以直接取出来然后在页面的 加入就可以了,注意要加入 data:image/png;base64, 如下:
在这里插入图片描述
或者可以写一个Java获取的方法: 传入的是照片的唯一id 即照片名,然后根据地址去下载

 //从本地读取文件并返回到网页中
	
	@RequestMapping(value="/getImage")
    public void getImage(String uuid, HttpServletResponse response){
		String path="Z:\\sbsqphoto\\"+uuid+".jpg";
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            out = response.getOutputStream();
            byte[] bytes = new byte[1024 * 10];
            int len = 0;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

页面显示代码: 直接调用后台方法就可以了
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拉登的小行星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值