php - 如何以base64输出图片

查看:937
本文介绍了php - 如何以base64输出图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

是这样的,今天按着网上的资料写了一个PHP生成验证码的模板:

<?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();

可是我不想让他直接输出图片,而是以base64输出图片,请问该如何做?自己试了很多方法都不成功,除非必须这样:

$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}' />";

请问如何在getCode中就直接输出base64呢?

解决方案

是否直接输出图片关键在于

  1. 关闭 header

  2. imagepng函数, 第二个参数设置图片保存位置.

然后去读取存储位置读取图片, 转换成base64.

php文档

文档下面的留言部分可能有你需要的答案

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

这篇关于php - 如何以base64输出图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆