代码片-base64 图片资源与字节数组转换

1.Java>根据图片链接获取图片资源后转字节数组

    // 调用方式
    // byte[] imgBytes3 = getBytesByUrl("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2213668399,1480023379&fm=26&gp=0.jpg");
    public static byte[] getBytesByUrl(String urlPath) {
        byte[] data = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            // conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(6000);
            is = conn.getInputStream();
            if (conn.getResponseCode() == 200) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length = -1;
                try {
                    while ((length = is.read(buffer)) != -1) {
                        baos.write(buffer, 0, length);
                    }
                    baos.flush();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                data = baos.toByteArray();
                try {
                    is.close();
                    baos.close();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else{
                data=null;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if(is != null){
                    is.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            conn.disconnect();
        }
        return data;
    }

2. 文件上传资源编码转换

2.1. Vue>原生 Input 组件获取图片 Base64 编码资源

<input type="file" accept="image/*" @change="selectImg()" ref="file"/>

    此处使用 Promise 将上传图片资源 evt.target.result(Base64Data) 放全局变量

export default {
  data: function () {
    return {
      // 文件名称,文件Base64编码资源
      fileData: {
        fileName: '',
        imageBase64Data: ''
      } 
    }
  }
  methods: {
    // 选择文件
    selectImg () {
      let imgFile = this.$refs.file.files[0]
      if (!imgFile) {
        return;
      }
      this.fileData.fileName = imgFile.name
      let imageType = /^image\//;
      if (!imageType.test(imgFile.type)) {
        alert('请选择图片!')
        return;
      }
      if (imgFile.size > 5 * 1024 * 1024) {
        alert('请选择不大于5M图片!')
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(imgFile);
      //读取文件
      this.onloadFile(reader).then((result)=>{
        this.fileData.imageBase64Data = result
      })
    },
    // onload 回调结果放全局变量
    onloadFile (reader) {
      return new Promise(function(resolve, reject) {
          reader.onload = function(evt) {
              resolve(evt.target.result)
          }
      })
    }
  }
}

2.2Java>Base64 编码资源转 byte[]

    图片文件 Base64 编码示例

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL ...... MVEi//2Q==

    F12 打开浏览器控制台,查看图片资源,可以看到这些资源拥有固定的前缀;data 表示取得数据的协定名称,image/png 是数据类型名称,base64 是数据的编码方法,"base,"后面才是图片文件 base64 编码后的数据。转换二进制数组时注意要去掉前缀

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

public class Test{
    /**
     * data:image/gif;base64,base64编码的gif图片数据
     * data:image/png;base64,base64编码的png图片数据
     * data:image/jpeg;base64,base64编码的jpeg图片数据
     * data:image/x-icon;base64,base64编码的icon图片数据
     */
    public static final String IMAGE_JPEG_BASE64 = "data:image/jpeg;base64,";
    public static final String IMAGE_PNG_BASE64 = "data:image/png;base64,";
    public static final String IMAGE_GIF_BASE64 = "data:image/gif;base64,";
    public static final String IMAGE_ICON_BASE64 = "data:image/x-icon;base64,";
    
    public static void main(String args[]) throws IOException {
        String imageBase64Data = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL ...... MVEi//2Q==";
        imageBase64Data = imageBase64Data.substring(DATA_IMAGE_JPEG_BASE64.length());

        // base64Url 转 byte[] 方式一
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] imgByteData = base64Decoder.decodeBuffer(imageBase64Data);
        // byte[] 转 base64
        String base64Data = Base64.encodeBase64String(imgByteData)

        // base64Url 转 byte[] 方式二
        imgByteData = Base64.decodeBase64(imageBase64Data);
    }
}

Power By niaonao, The End

©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页