Php Laravel图像创建代码
我从网上的某个地方复制了以下代码。它存储在一个名为captcha.php的文件中:Php Laravel图像创建代码,php,laravel,gd,Php,Laravel,Gd,我从网上的某个地方复制了以下代码。它存储在一个名为captcha.php的文件中: $md5_hash = md5(rand(0,999)); //We don't need a 32 character long string so we trim it down to 5 $security_code = substr($md5_hash, 15, 5); //Set the session to store the security code
$md5_hash = md5(rand(0,999));
//We don't need a 32 character long string so we trim it down to 5
$security_code = substr($md5_hash, 15, 5);
//Set the session to store the security code
//Set the image width and height
$width = 100;
$height = 20;
//Create the image resource
$image = ImageCreate($width, $height);
//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);
//Make the background black
ImageFill($image, 0, 0, $black);
//Add randomly generated string in white to the image
ImageString($image, 3, 30, 3, $security_code, $white);
//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image,0,0,$width-1,$height-1,$grey);
imageline($image, 0, $height/2, $width, $height/2, $grey);
imageline($image, $width/2, 0, $width/2, $height, $grey);
//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");
//Output the newly created image in jpeg format
ImageJpeg($image);
//Free up resources
ImageDestroy($image);
我需要用在拉维里。我应该给出这个php文件到
标记的src
属性的路径。当文件位于公共目录中的文件夹中时,它可以工作,但当我在路由中执行以下操作时,它不工作,并且不会创建图像。
我需要将其合并到Laravel路由中,以使用其会话::
功能
以下是插入上述代码的路由器:
Route::get('captcha', array('as'=>'captcha'), function(){
// above code
});
我不清楚您的问题,但您可以创建一个类,并使用公共方法将此代码放在该类中,例如,您可以在
app/libs
文件夹中创建一个类(在app
中创建libs
文件夹),然后在此libs
文件夹中创建类似于以下内容的类:
namespace Libs\Captcha;
class Captcha {
public function dumpCaptcha()
{
// put the captcha code here but make
// changes to the last part as given below
//Tell the browser what kind of file is come in
ob_start();
header("Content-Type: image/jpeg");
ImageJpeg($image);
$img = ob_get_clean();
ImageDestroy($image);
return base64_encode($img);
}
}
在composer.json
文件的autoload->classmap
部分的末尾添加另一个条目,如下所示:
"autoload": {
"classmap": [
// ...
"app/tests/TestCase.php",
"app/libs/captcha/Captcha.php",
]
}
Route::get('captcha', array('as'=>'captcha'), function(){
$captcha = App::make('Libs\\Captcha\\Captcha');
return View::make('view_name_here')->with('captchaImage', $captcha->dumpCaptcha());
});
然后从终端/命令提示符运行composer dump autoload
,然后在路线内使用此类,如下所示:
"autoload": {
"classmap": [
// ...
"app/tests/TestCase.php",
"app/libs/captcha/Captcha.php",
]
}
Route::get('captcha', array('as'=>'captcha'), function(){
$captcha = App::make('Libs\\Captcha\\Captcha');
return View::make('view_name_here')->with('captchaImage', $captcha->dumpCaptcha());
});
然后在您的视图中
可以使用类似的内容
<img src={{ 'data:image/jpeg;base64,' . $captchaImage }} />
将显示图像