php 图片转成base64 前后台示例

test.php

<?php
$root = $_SERVER['DOCUMENT_ROOT'];
$images = array($root.'/img/img1.jpg',$root.'/img/img2.jpg',$root.'/img/img3.jpg');
foreach($images as $image){
    $payloads[] = imgToBase64($image);
}
$newline = chr(1);
echo implode($newline,$payloads);
/**
 * 获取图片的Base64编码(不支持url)
 * @date 2017-02-20 19:41:22
 * @param $img_file 传入本地图片地址
 * @return string
 */
function imgToBase64($img_file) {
    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限
        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = chunk_split(base64_encode($content)); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }
            $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
        }
        fclose($fp);
    }
    return $img_base64; //返回图片的base64
}

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
    <div id='container'></div>
    <script>
        $(function(){
            $.get('/test.php',function(data){
                splitImages(data);
            })
        })
        function splitImages(imageString){
            var imageData = imageString.split('u0001');
            var imageElement;
            for(var i = 0, len = imageData.length; i < len; i++){
                imageElement = document.createElement('img');
                imageElement.src = imageData[i];
                document.getElementById('container').appendChild(imageElement);
            }
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/kerryw/p/8897941.html