zoukankan      html  css  js  c++  java
  • 怎么才能将文件流或者图片转化为base64,传到前台展示

    图片转化为base64,传到前台展示

    public String getBase64(){
            String imgStr = "";
            try {
                 
            File file = new File("C:\EThinkTankFile\20180402160120431.jpg");
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()]; 
                int offset = 0; 
                int numRead = 0; 
                while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
                    offset += numRead;
                } 
                 
                if (offset != buffer.length) { 
                    throw new IOException("Could not completely read file " 
                            + file.getName()); 
                } 
                fis.close(); 
                BASE64Encoder encoder = new BASE64Encoder();
                imgStr = encoder.encode(buffer);
            } catch (Exception e) {
                e.printStackTrace();
            }
                 return "data:image/jpeg;base64,"+imgStr;
    }前台代码:<img id="picture" width="690" height="460"  src="">通过ajax 请求将后台返回的字符串 添加到src属性中去 $("#picture").attr("src","后台返回的base64字符串");

    文件流转化为base64,传到前台展示

    public static String getBase64FromInputStream(InputStream in) {
            // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
            byte[] data = null;
            // 读取图片字节数组
            try {
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = in.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
            } catch (IOException e) {
                LOGGER.error("InputStream转换成base64失败:{}", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        LOGGER.error("InputStream转换成base64失败:{}", e);
                    }
                }
            }
            //返回的字符串传到前台,添加到src属性中去,即可显示图片
            return "data:image/jpeg;base64,"+ new String(Base64.encodeBase64(data));
        }
  • 相关阅读:
    Spine(2D骨骼动画)
    UpdatePanel的用法
    Windows7下的免费虚拟机(微软官方虚拟机)
    android ViewPager具体解释
    与Scheme共舞
    Binder机制1---Binder原理介绍
    HDU 2853 Assignment(KM最大匹配好题)
    微信公众平台java开发具体解释(project代码+解析)
    怎样绕过oracle listener 监听的password设置
    IOS成长之路-Nsstring中搜索方法rangeOfString
  • 原文地址:https://www.cnblogs.com/liuqing576598117/p/9760184.html
Copyright © 2011-2022 走看看