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?
The key to whether to output pictures directly is
Close header
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