Laravel图像创建代码

时间:2014-02-01 12:33:52

标签: 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


    //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);

我需要在laravel中使用。我应该将此php文件的路径赋予src标记的<img>属性。当文件位于公共目录中的文件夹中时,它可以工作,但是当我在路由中执行以下操作时,它不起作用,并且不会创建任何图像。 我需要将它合并到Laravel路由中以使用其Session::功能。

以下是插入上述代码的路由器:

Route::get('captcha', array('as'=>'captcha'), function(){
    // above code 
});

1 个答案:

答案 0 :(得分:1)

我不清楚您的问题,但您可以创建一个类并使用公共方法将此代码放在该类中,例如,您可以在app/libs文件夹中创建一个类(创建{{ 1}} libs}内的文件夹,并在此app文件夹中创建一个类似于此的类:

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", ] } ,然后在您的路由中使用此类,如下所示:

composer dump-autoload

然后在你的Route::get('captcha', array('as'=>'captcha'), function(){ $captcha = App::make('Libs\\Captcha\\Captcha'); return View::make('view_name_here')->with('captchaImage', $captcha->dumpCaptcha()); }); 中你可以使用类似的东西

view

将显示图像。