线上以及本地图片转base64编码

7634次阅读 493人点赞 作者: WuBin 发布时间: 2021-03-15 13:21:49
扫码到手机查看

canvas转换本地图片为base64编码

class ImgToBase64 {
  constructor(imgurl) {
    this.imgUrl = imgurl;
    this.img = null;
  }

  getBase64() {
    let base64 = '';
    this.img = new Image();
    this.img.crossOrigin = 'Anonymous';
    this.img.src = this.imgUrl;

    return new Promise((resolve, reject) => {
      // 图片加载成功,转化base64格式
      this.img.addEventListener('load', () => {
        base64 = this.toBase64();
        resolve(base64);
      });
      // 图片加载失败 抛出错误
      this.img.addEventListener('error', () => {
        reject('false');
      });
    });
  }

  toBase64() {
    let canvas = document.createElement('canvas');
    canvas.width = this.img.width;
    canvas.height = this.img.height;
    let ctx = canvas.getContext('2d');
    ctx.drawImage(this.img, 0, 0, this.img.width, this.img.height);
    let dataURL = canvas.toDataURL('image/png');
    return dataURL;
  }

}

var img = new ImgToBase64('preview-img.jpg');

img.getBase64().then((res) => {
  console.log(res);
});

使用CANVAS将本地(不能跨域!)的图片转换为base64的格式。

当图片文件是通过input[type=file]上传

<input type="file" id="upload">
<button class="btn">上传图片</button>
<textarea id="localimg-result"></textarea>

var localImg = function() {
    var $localResult = $('#localimg-result'); 

    $("#upload").change(function(){  
        var imgFile = new FileReader();
        imgFile.readAsDataURL(this.files[0]);
        imgFile.onload = function () {
            var imgData = this.result;
            $localResult.focus();
            $localResult.val(imgData);
        }
    }) ;  
}();

图片通过后台接口调用

具体请参考 http://tool.wubin.work/img2base64,请求的接口

http://tool.wubin.work/api/img2base64.php?url=填入图片的链接

网站带宽有限,可以在自己的服务器上搭建

<?php
header("Access-Control-Allow-Origin: *");
header("content:application/json;chartset=uft-8");
/**
 * 将传入图片地址转化为base64
 */
class ImgToBase64 
{
    public $url;
    public $base64;

    function __construct($url)
    {
        $this->url = $url;

        $this->checkUrl() && $this->tobase64();
        
    }

    private function checkUrl()
    {
        $pattern = '/http[s]?:\/\/[\w.-\/]+\.(jpg|png|gif|jpeg)/i';
        preg_match($pattern, $this->url, $match);
        if (!isset($match[0])) {
            $this->showError();
            return false;
        }
        $this->url = $match[0];
        return true;
    }

    private function tobase64()
    {
         $imageInfo = @getimagesize($this->url);
         if (!$imageInfo) {
             $this->showError();
             return;
         }
         $base64 = base64_encode(file_get_contents($this->url));
         // 在每个字符后分割一次字符串 分隔后再前端显示会有断行
        //  $base64 = chunk_split($base64);
         $blob = 'data:' . $imageInfo['mime'] . ';base64,';
         $this->base64 = $blob . $base64;
    }

    private function showError()
    {
        $this->base64 = false;
    }

    public function getBase64()
    {
        return $this->base64;
    }

}

// $img = 'http://statics.qdxin.cn/uploadfile/2020/1212/20201212100223404.jpg';

$img_url = isset($_GET['url']) ? $_GET['url'] : false;
$res = array(
    'error' => 1,
    'data' => false
);
if ($img_url) {
    $base64 = new ImgToBase64($img_url);
    $img_base64 = $base64->getBase64();
    (boolean)$img_base64 && $res = array(
        'error' => 0,
        'data' => $img_base64
    );
}
$json = json_encode($res);
exit($json);
?>

使用PHP方法没有任何副作用,可以跨域将非本域名下的图片文件转化为base64编码进行渲染、海报生成等操作!

具体应用可以参考我的另一篇文章:Vue+html2canvas截图空白的问题

通过input[type=file]上传图片的预览

非IE实现本地上传图片的预览

<div id="imgbox"><img></div>
<input type="file" id="upload">
<script src="http://vip.qdxin.cn/navmenu/js/jxinq111.js"></script>
//建立一個可存取到該file的url  
function getObjectURL(file) {  
  var url = null ;   
  // 针对不同的浏览器执行不同的 js 函数而已  
  if (window.createObjectURL!=undefined) { // basic  
    url = window.createObjectURL(file) ;  
  } else if (window.URL!=undefined) { // mozilla(firefox)  
    url = window.URL.createObjectURL(file) ;  
  } else if (window.webkitURL!=undefined) { // webkit or chrome  
    url = window.webkitURL.createObjectURL(file) ;  
  }  
  return url ;  
}  

$("#upload").change(function(){  
  var objUrl = getObjectURL(this.files[0]) ;  
  // console.log("objUrl = "+objUrl) ;  
  if (objUrl) {  
    $("#imgbox img").attr("src", objUrl) ;  
  }  
}) ;

相关资料

点赞 支持一下 觉得不错?客官您就稍微鼓励一下吧!
关键词:promise,resolve,base64
推荐阅读
  • uniapp实现被浏览器唤起的功能

    当用户打开h5链接时候,点击打开app若用户在已经安装过app的情况下直接打开app,若未安装过跳到应用市场下载安装这个功能在实现上主要分为两种场景,从普通浏览器唤醒以及从微信唤醒。

    9094次阅读 588人点赞 发布时间: 2022-12-14 16:34:53 立即查看
  • Vue

    盘点Vue2和Vue3的10种组件通信方式

    Vue中组件通信方式有很多,其中Vue2和Vue3实现起来也会有很多差异;本文将通过选项式API组合式API以及setup三种不同实现方式全面介绍Vue2和Vue3的组件通信方式。

    3843次阅读 286人点赞 发布时间: 2022-08-19 09:40:16 立即查看
  • JS

    几个高级前端常用的API

    推荐4个前端开发中常用的高端API,分别是MutationObserver、IntersectionObserver、getComputedstyle、getBoundingClientRect、requ...

    14071次阅读 914人点赞 发布时间: 2021-11-11 09:39:54 立即查看
  • PHP

    【正则】一些常用的正则表达式总结

    在日常开发中,正则表达式是非常有用的,正则表达式在每个语言中都是可以使用的,他就跟JSON一样,是通用的。了解一些常用的正则表达式,能大大提高你的工作效率。

    12908次阅读 442人点赞 发布时间: 2021-10-09 15:58:58 立即查看
  • 【中文】免费可商用字体下载与考证

    65款免费、可商用、无任何限制中文字体打包下载,这些字体都是经过长期验证,经得住市场考验的,让您规避被无良厂商起诉的风险。

    11469次阅读 920人点赞 发布时间: 2021-07-05 15:28:45 立即查看
  • Vue

    Vue3开发一个v-loading的自定义指令

    在vue3中实现一个自定义的指令,有助于我们简化开发,简化复用,通过一个指令的调用即可实现一些可高度复用的交互。

    15588次阅读 1244人点赞 发布时间: 2021-07-02 15:58:35 立即查看
  • JS

    关于手机上滚动穿透问题的解决

    当页面出现浮层的时候,滑动浮层的内容,正常情况下预期应该是浮层下边的内容不会滚动;然而事实并非如此。在PC上使用css即可解决,但是在手机端,情况就变的比较复杂,就需要禁止触摸事件才可以。

    14795次阅读 1205人点赞 发布时间: 2021-05-31 09:25:50 立即查看
  • Vue

    Vue+html2canvas截图空白的问题

    在使用vue做信网单页专题时,有海报生成的功能,这里推荐2个插件:一个是html2canvas,构造好DOM然后转canvas进行截图;另外使用vue-canvas-poster(这个截止到2021年3月...

    28950次阅读 2273人点赞 发布时间: 2021-03-02 09:04:51 立即查看
  • Vue

    vue-router4过度动画无效解决方案

    在初次使用vue3+vue-router4时候,先后遇到了过度动画transition进入和退出分别无效的情况,搜遍百度没没找到合适解决方法,包括vue-route4有一些API都进行了变化,以前的一些操...

    24982次阅读 1925人点赞 发布时间: 2021-02-23 13:37:20 立即查看
交流 收藏 目录