js将图片转换成base64

9963次阅读 718人点赞 作者: WuBin 发布时间: 2022-10-11 09:29:24
扫码到手机查看

之前有个需求是把页面绘制成图片,上传到服务器中,我使用的 html2canvas 。但是html页面当中含有图片,如果图片地址非本页面域名,在截图时就会存在跨域问题,导致截图失败。经过多方查找,发现把页面中的图片转换成base64,可以避免这个跨域问题。

JS处理base64

var strImage = strToReplace.replace(/^data:image\/[a-z]+;base64,/, "");

处理base64去掉data:image/jpeg;base64,这些内容,,得以让后台识别,否则后台是不识别的。

外链图片使用请求的方式

本方法也只适用于同源请求,比如当我使用localhost请求http://static.wubin的时候,就会提示跨域的错误

跨域请求产生错误的原因及处理方法:https://www.wubin.work/blog/articles/316

基本上这种方法只用在同源的情况下吧!

function getBase64(imgUrl) {
    window.URL = window.URL || window.webkitURL;
    var xhr = new XMLHttpRequest();
    xhr.open("get", imgUrl, true);
    xhr.responseType = "blob";
    xhr.onload = function(){
        if(this.status == 200){
            //得到一个blob对象
            var blob = this.response;
            console.log("blob", blob)
            // 至关重要
            let oFileReader = new FileReader();
            oFileReader.onloadend = function(e){
                // 此处拿到的已经是base64的图片了,可以赋值做相应的处理
                console.log(e.target.result)
            }
            oFileReader.readAsDataURL(blob);
        }
    }
    xhr.send();
}

可以简单更改下,改为promise:

function getImageBase64(imgUrl) {
        return new Promise((resolve, reject) => {
            window.URL = window.URL || window.webkitURL;
            var xhr = new XMLHttpRequest();
            xhr.open("get", imgUrl, true);
            xhr.responseType = "blob";
            xhr.onload = function(){
                if(this.status == 200){
                    //得到一个blob对象
                    var blob = this.response;
                    console.log("blob", blob)
                    // 至关重要
                    let oFileReader = new FileReader();
                    oFileReader.onloadend = function(e){
                        // 此处拿到的已经是base64的图片了,可以赋值做相应的处理
                        console.log(e.target.result);
                        resolve(e.target.result);
                    }
                    oFileReader.readAsDataURL(blob);
                }
            }
            xhr.send();
        });
    }

使用的时候:

const imgBase64 = await getImageBase64(image.src);

不要忘记,await要配合async~~

使用canvas

这种方式也不能实现跨域转化:

根据图片路径获取base64编码
/**
*
* @param url 图片路径
* @param ext 图片格式
* @param callback 结果回调
*/
function getUrlBase64(url, ext, callback) {
    var canvas = document.createElement("canvas"); //创建canvas DOM元素
    var ctx = canvas.getContext("2d");
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.src = url;
    img.onload = function () {
        //指定画板的高度,自定义,推荐使用img加载后的实际宽度
        canvas.height = 60;
        //指定画板的宽度,自定义, 推荐使用img加载后的实际宽度
        canvas.width = 85; 
        ctx.drawImage(img, 0, 0, 60, 85); //参数可自定义
        var dataURL = canvas.toDataURL("image/" + ext);
        callback.call(this, dataURL); //回掉函数获取Base64编码
        canvas = null;
    };
}

// 使用
getUrlBase64(path, ext, function (base64) {
    console.log(base64);//base64编码值
});

最最通用的方法,使用后端进行代理

使用这种方法,可以无视任何跨域的问题,但是需要发送请求~

配合axios插件:

function getImageBase64(imgsrc) {
    const GET_BASE64 = 'http://m.qdxin.cn/appc/getbase64.php';
    const URL = `${GET_BASE64}?url=${imgsrc}`;
    return axios.get(URL).then((res) => {
        const serverData = res.data;
        if (serverData.error == 0) {
          return serverData.data;
        } else {
          return false;
        }
      }).catch((err) => {
        // 请求失败
        console.log(err);
        // window.alert('抱歉,数据请求失败,请稍候重试');
        return false;
      });
}

后端转换图片PHP:

<?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\d.\/-]+\.(jpg|png|gif)/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;
// 先检测url中是否含有http或者https,如果没有添加http
if (strpos($img_url, 'http') === false) {
    $img_url = 'http:' . $img_url;
}
 
$res = array(
    'error' => 1,
    'data' => false
);

// 如果是一个有效图片
if (@getimagesize($img_url)) {
    $base64 = new ImgToBase64($img_url);
    $img_base64 = $base64->getBase64();
    // var_dump($img_base64);
    (boolean)$img_base64 && $res = array(
        'error' => 0,
        'data' => $img_base64
    );
}
$json = json_encode($res);
exit($json);

?>

推荐个自己的转换地址:http://api.wubin.work/tool/img2base64?url=填入图片的链接

以及工具链接:http://tool.wubin.work/img2base64

本地图片转base64

<!DOCTYPE html>
<html>
<head>
    <title>本地图片转base64</title>
</head>
<body>
    <input type="file" id="imgfile" method="post" enctype="multipart/form-data">
    <button type="button" onClick="ToBase64();">点我</button>
</body>
    <script type="text/javascript">
        function ToBase64() {
            // debugger
            /*转换base64*/
            var img = document.getElementById('imgfile')
            var imgFile = new FileReader();
            imgFile.readAsDataURL(img.files[0]);
        
            imgFile.onload = function () {
                var imgData = this.result; //base64数据  
                console.log(imgData);
            }
        }
    </script>
</html>
点赞 支持一下 觉得不错?客官您就稍微鼓励一下吧!
关键词: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 立即查看
交流 收藏 目录