php - How to output image in base64
伊谢尔伦
伊谢尔伦 2017-05-24 11:32:19
0
1
905

That’s it. Today I wrote a PHP template for generating verification codes based on the information on the Internet:

<?php
// 获取验证码(参数:验证码个数,验证码宽度,验证码高度)
function getCode($num = 4, $width = 100, $height = 30){
    session_start();
    $authcode='';
    // 生成验证码
    for($i=0;$i<$num;$i++){
        switch(rand(0,1))
        {
            case  0:$authcode[$i]=chr(rand(48,57));break; // 数字
            case  1:$authcode[$i]=chr(rand(65,90));break; // 大写字母
            //case  2:$authcode[$i]=chr(rand(97,122));break; // 小写字母
        }
    }
    $_SESSION["AuthCode"]=$authcode;
    $image=imagecreate($width,$height); // 赋值宽度,高度
    imagecolorallocate($image,255,255,255); // 设定图片背景颜色
    // 生成干扰像素
    for($i=0;$i<80;$i++){
        $dis_color=imagecolorallocate($image,rand(0,2555),rand(0,255),rand(0,255));
        imagesetpixel($image,rand(1,$width),rand(1,$height),$dis_color);
    }
    // 打印字符到图像
    for($i=0;$i<$num;$i++){
        $char_color=imagecolorallocate($image,rand(0,2555),rand(0,255),rand(0,255));
        imagechar($image,60,($width/$num)*$i,rand(0,5),$authcode[$i],$char_color);
    }
    
    // 将图片直接输出
    header("Content-type:image/png");
    imagepng($image);//输出图像到浏览器
    imagedestroy($image);//释放资源
}
getCode();

But I don’t want him to output the image directly, but output the image in base64. How should I do it? I have tried many methods without success, unless it is necessary: ​​

$img_file = 'https://www.xxxxxxxxxx.com/authcode.php';
$img_info = getimagesize($img_file);
$img_src = "data:{$img_info['mime']};base64," . base64_encode(file_get_contents($img_file));
echo "<img src='{$img_src}' />";

How can I directly output base64 in getCode?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
淡淡烟草味

The key to whether to output pictures directly is

  1. Close header

  2. imagepng function, the second parameter sets the image saving location.

Then read the storage location to read the image and convert it to base64.

php documentation

The comments section below the document may have the answers you need

ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template