当前位置: 首页 > 工具软件 > getbase > 使用案例 >

input file获取本地图片路径并转换为base64

邓英卓
2023-12-01

<template>
  <div>
    <input type="file" @change="chose">
  </div>
</template>

<script>
export default {
  methods: {
    chose(e) {
      console.log(e.target.files[0]);
      console.log(window.URL.createObjectURL(e.target.files[0]));
      var image = new Image();
      image.src = window.URL.createObjectURL(e.target.files[0]);
      //src:  blob:http://localhost:8082/9df84568-5bd8-40a6-af88-30b545bffa26
      console.log(image);
      image.onload = () => {
        console.log(this.getBase64Img(image));
        //this.getBase64Img(image)即为转换为base64格式的图片形式
      };
    },
    getBase64Img(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    }
  }
};
</script>

<style>
</style>

 类似资料: