是這樣的,今天按著網(wǎng)路上的資料寫(xiě)了一個(gè)PHP產(chǎn)生驗(yàn)證碼的模板:
<?php
// 獲取驗(yàn)證碼(參數(shù):驗(yàn)證碼個(gè)數(shù),驗(yàn)證碼寬度,驗(yàn)證碼高度)
function getCode($num = 4, $width = 100, $height = 30){
session_start();
$authcode='';
// 生成驗(yàn)證碼
for($i=0;$i<$num;$i++){
switch(rand(0,1))
{
case 0:$authcode[$i]=chr(rand(48,57));break; // 數(shù)字
case 1:$authcode[$i]=chr(rand(65,90));break; // 大寫(xiě)字母
//case 2:$authcode[$i]=chr(rand(97,122));break; // 小寫(xiě)字母
}
}
$_SESSION["AuthCode"]=$authcode;
$image=imagecreate($width,$height); // 賦值寬度,高度
imagecolorallocate($image,255,255,255); // 設(shè)定圖片背景顏色
// 生成干擾像素
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輸出圖片,請(qǐng)問(wèn)該如何做?自己試了很多方法都不成功,除非必須這樣:
$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}' />";
請(qǐng)問(wèn)如何在getCode中就直接輸出base64呢?
小伙看你根骨奇佳,潛力無(wú)限,來(lái)學(xué)PHP伐。
是否直接輸出圖片關(guān)鍵在於
關(guān)閉 header
imagepng函數(shù), 第二個(gè)參數(shù)設(shè)定圖片儲(chǔ)存位置.
然後去讀取儲(chǔ)存位置讀取圖片, 轉(zhuǎn)換成base64.
php文檔
文檔下面的留言部分可能有你需要的答案
ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();