示例#1
0
 /**
  * @return mixed
  */
 protected function makeCode()
 {
     $charset = "2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY";
     $cWidth = $this->code_width;
     //画布宽度
     $cHeight = $this->code_height;
     //画布高度
     $code = "";
     $color = ['#99c525', '#fc9721', '#8c659d', '#00afd8'];
     $img = Image::canvas($cWidth, $cHeight, '#ccc');
     for ($i = 0; $i < $this->code_num; $i++) {
         //画出干扰线
         $img->line(mt_rand(0, $cWidth), mt_rand(0, $cHeight), mt_rand(0, $cWidth), mt_rand(0, $cHeight), function ($draw) use($color) {
             $draw->color($color[array_rand($color, 1)]);
         });
         //随机取出验证码
         $code .= $charset[mt_rand(0, strlen($charset) - 1)];
         //画出验证码
         $img->text($code[$i], $this->code_width / $this->code_num * $i + 5, 25, function ($font) use($color) {
             $font->file('static/fonts/arial.ttf');
             $font->size(18);
             $font->color($color[array_rand($color, 1)]);
             $font->angle(mt_rand(-30, 30));
         });
     }
     //在session中放置code
     Session::put('code', Str::lower($code));
     $response = Response::make($img->encode('png'));
     $response->header('Content-Type', 'image/png');
     return $response;
 }
示例#2
0
 public function test2(Request $request)
 {
     $img = Image::canvas(800, 600, '#ff0000');
     // create response and add encoded image data
     $img->save(base_path() . '/public/dggggdd' . '.jpg');
     // set content-type
     // $response->header('Content-Type', 'image/png');
     // output
     return $img->response('png');
     //return captcha()->save('dd');
     //return captcha_img();
     //return Captcha::create();
     //return view('chen2');
 }
示例#3
0
 protected static function boot()
 {
     parent::boot();
     static::creating(function ($model) {
         $rules = array('photo' => 'required|image');
         $validator = Validator::make(array('photo' => $model->photo), $rules);
         if ($validator->passes()) {
             $destination_path = public_path() . '/storage/gallery/';
             $thumbnail_path = public_path() . '/storage/gallery/thumbnails/';
             $randname = str_random(10);
             $filename = $randname . '.' . $model->photo->getClientOriginalExtension();
             $retina_name = $randname . '@2x.' . $model->photo->getClientOriginalExtension();
             Image::make($model->photo->getRealPath())->save($destination_path . $filename);
             $thumbnail_img_retina = Image::make($model->photo->getRealPath())->resize(1400, null, function ($constraint) {
                 $constraint->aspectRatio();
             });
             $thumbnail_bg_retina = Image::canvas(1400, 1400, '#fff')->insert($thumbnail_img_retina, 'center')->save($thumbnail_path . $retina_name);
             $thumbnail_img = Image::make($thumbnail_path . $retina_name)->resize(700, 700, function ($constraint) {
                 $constraint->aspectRatio();
             })->save($thumbnail_path . $filename);
             $model->photo_name = $filename;
         } else {
             throw new Exception("Файлът трябва да бъде снимка.", 666);
         }
         return true;
     });
     static::deleting(function ($model) {
         $destination_path = public_path() . '/storage/gallery/';
         $thumbnail_path = public_path() . '/storage/gallery/thumbnails/';
         $photo_info = pathinfo($destination_path . $model->photo_name);
         $old_photo_retina = $destination_path . $photo_info['filename'] . '@2x.' . $photo_info['extension'];
         $old_thumb_retina = $thumbnail_path . $photo_info['filename'] . '@2x.' . $photo_info['extension'];
         File::delete($destination_path . $model->photo_name);
         File::delete($thumbnail_path . $model->photo_name);
         File::delete($old_photo_retina);
         File::delete($old_thumb_retina);
         return true;
     });
 }
示例#4
0
 public function postIndex()
 {
     if (!$this->_isValidInput(Input::all())) {
         return Redirect::to('index')->with('errors', $this->errors);
     }
     $first = Input::file('first');
     $firstText = trim(Input::get('firstText')) != '' ? trim(Input::get('firstText')) : $this->texts['first'];
     $second = Input::file('second');
     $secondText = trim(Input::get('secondText')) != '' ? trim(Input::get('secondText')) : $this->texts['second'];
     $message = Input::get('message');
     $firstName = Session::get('uid') . '_' . time() . '_' . $first->getClientOriginalName();
     $secondName = Session::get('uid') . '_' . time() . '_' . $second->getClientOriginalName();
     Input::file('first')->move($this->paths['firsts'], $firstName);
     Input::file('second')->move($this->paths['seconds'], $secondName);
     $first = Image::make($this->paths['firsts'] . '/' . $firstName)->resize(421.5, 350);
     $second = Image::make($this->paths['seconds'] . '/' . $secondName)->resize(421.5, 350);
     $ttwwooName = Session::get('uid') . '_' . time() . '_' . str_random(6) . '.jpg';
     $ttwwoo = Image::canvas(843, 403, '#ffffff')->insert($first, 0, 50, 'left')->insert($second, 421.5, 50, 'left')->text($firstText, 100, 50, 32, '#333333', 0, realpath('eagle.ttf'))->text($secondText, 522, 50, 32, '#333333', 0, realpath('eagle.ttf'))->save($this->paths['ttwwoos'] . '/' . $ttwwooName);
     $tid = $this->_saveTtwwooToUser(Cookie::get('uid'), $firstName, $firstText, $secondName, $secondText, $ttwwooName, $message);
     Session::put('tid', $tid);
     $ttwwoo = $this->_getTtwwoo($tid);
     // $this->_shareTtwwoo($ttwwoo);
     return View::make('ttwwoo.view')->with('ttwwoo', $ttwwoo);
 }
 public function doEdit()
 {
     $task = Photo::findOrFail(Input::get('id'));
     $task->title = Input::get('title');
     $task->description = Input::get('description');
     $task->category = Input::get('category');
     $filename = time() . Input::get('image');
     //->getClientOriginalName();
     //attaching the image name with the src path and save to path
     $task->path = 'uploads/' . $filename;
     //before the image is moved to the uploads folder we resize with intervention
     $background = Image::canvas(650, 650);
     $image = Input::file('image');
     $newimage = Image::make($image)->resize(650, 650, function ($c) {
         $c->aspectRatio();
         $c->upsize();
     });
     $background->insert($newimage, 'center');
     //moving the image to the uploads folder
     $savepath = 'public/uploads';
     $background->save(base_path() . '/public/uploads/' . $filename);
     $task->save();
     return Redirect::action('HomeController@home');
 }
示例#6
0
 private function saveInvoiceDesign()
 {
     $account = Auth::user()->account;
     $account->op3 = true;
     $account->save();
     if ($file = Input::file('logo') || Input::get('design') || Input::get('x')) {
         if (Auth::user()->account->isRegistered()) {
             $invoice_design = InvoiceDesign::createNew();
             $invoice_design_old = InvoiceDesign::scope()->orderBy('public_id', 'desc')->firstOrFail();
             $invoice_design->javascript = $invoice_design_old->javascript;
             $invoice_design->x = $invoice_design_old->x;
             $invoice_design->y = $invoice_design_old->y;
             $invoice_design->logo = $invoice_design_old->logo;
         } else {
             $invoice_design = InvoiceDesign::scope()->orderBy('public_id', 'desc')->firstOrFail();
         }
         if ($file = Input::file('logo')) {
             $path = Input::file('logo')->getRealPath();
             File::delete('logo/' . $account->account_key . '.jpg');
             $image = Image::make($path)->resize(200, 120, true, false);
             Image::canvas($image->width, $image->height, '#FFFFFF')->insert($image)->save($account->getLogoPath());
             $invoice_design->logo = HTML::image_data('logo/' . $account->account_key . '.jpg');
             File::delete('logo/' . $account->account_key . '.jpg');
             $invoice_design->save();
         }
         if (Input::get('x') || Input::get('y')) {
             $invoice_design->x = Input::get('x');
             $invoice_design->y = Input::get('y');
             $invoice_design->save();
         }
         if (Input::get('design')) {
             $invoice_design->javascript = Input::get('design');
             $invoice_design->save();
         }
         Session::flash('message', trans('texts.updated_settings'));
     }
     return Redirect::to('company/invoice_design');
 }
示例#7
0
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', "Main@index");
Route::post('/', "Main@store");
Route::get('/image', function () {
    $img = Image::canvas(800, 600, '#ff0000');
    return $img->response();
});
Route::get('/test', function () {
    return "Hello World";
});
// Authentication routes...
Route::get('home', ['middleware' => 'auth', 'uses' => 'Home@index']);
Route::get('auth/login', 'Auth\\AuthController@getLogin');
Route::post('auth/login', 'Auth\\AuthController@postLogin');
Route::get('auth/logout', 'Auth\\AuthController@getLogout');
// Registration routes...
Route::get('auth/register', 'Auth\\AuthController@getRegister');
Route::post('auth/register', 'Auth\\AuthController@postRegister');
Route::controllers(['password' => 'Auth\\PasswordController']);
Route::resource('image', 'imageManage');
示例#8
0
 public function validate()
 {
     if (is_null($this::where('name', '=', $this->name)->first())) {
         $destination_path = public_path() . '/storage/cover_photos/';
         $thumbnail_path = public_path() . '/storage/cover_photos/thumbnails/';
         $randname = str_random(10);
         $filename = $randname . '.' . $this->cover_photo->getClientOriginalExtension();
         $retina_name = $randname . '@2x.' . $this->cover_photo->getClientOriginalExtension();
         $cover_img_retina = Image::make($this->cover_photo->getRealPath())->resize(3840, null, function ($constraint) {
             $constraint->aspectRatio();
         })->save($destination_path . $retina_name);
         $cover_img = Image::make($destination_path . $retina_name)->resize(1920, null, function ($constraint) {
             $constraint->aspectRatio();
         })->save($destination_path . $filename);
         $thumbnail_img_retina = Image::make($this->cover_photo->getRealPath())->resize(1400, null, function ($constraint) {
             $constraint->aspectRatio();
         });
         $thumbnail_bg_retina = Image::canvas(1400, 1400, '#fff')->insert($thumbnail_img_retina, 'center')->save($thumbnail_path . $retina_name);
         $thumbnail_img = Image::make($thumbnail_path . $retina_name)->resize(700, 700, function ($constraint) {
             $constraint->aspectRatio();
         })->save($thumbnail_path . $filename);
         $this->cover_name = $filename;
         return true;
     } else {
         throw new ValidationException(null, null, null, array('name' => "Училището вече съществува."));
     }
 }
示例#9
0
 private static function __getImage($img, $type)
 {
     $client = new Client(Config::get('services.dropbox.token'), Config::get('services.dropbox.appName'));
     $fileSystem = new Filesystem(new DropboxAdapter($client, '/images/'));
     $biggerW = $biggerH = false;
     if ($img->width > $img->height) {
         $biggerW = true;
     } else {
         $biggerH = true;
     }
     $image = $w = $h = null;
     $public_path = public_path($img->path);
     //code minh
     //get image from dropbox
     if ($img->store == 'dropbox') {
         try {
             $file = $fileSystem->read($img->path);
             $public_path = $file;
         } catch (Exception $e) {
             return false;
         }
     }
     //end code
     if (in_array($type, ['with-logo', 'large-thumb'])) {
         if ($biggerW) {
             $w = 450;
         } else {
             $h = 450;
         }
     } else {
         if (in_array($type, ['thumb', 'small-thumb'])) {
             if ($type == 'thumb') {
                 if ($biggerW) {
                     $w = 150;
                 } else {
                     $h = 150;
                 }
             } else {
                 if ($biggerW) {
                     $w = 100;
                 } else {
                     $h = 100;
                 }
             }
         } else {
             if (in_array($type, ['crop', 'newcrop'])) {
                 $h = 300;
                 $w = 300;
                 if ($type == 'newcrop') {
                     $w = 600;
                 }
             }
         }
     }
     try {
         if (in_array($type, ['crop', 'newcrop'])) {
             $image = Image::make($public_path)->fit($w, $h, function ($constraint) {
                 $constraint->aspectRatio();
             });
         } else {
             $image = Image::make($public_path)->resize($w, $h, function ($constraint) {
                 $constraint->aspectRatio();
             });
         }
     } catch (Exception $e) {
         return false;
     }
     if ($type == 'with-logo') {
         if (Cache::has('mask')) {
             $mask = Cache::get('mask');
         } else {
             $mask = Configure::where('ckey', 'mask')->pluck('cvalue');
             if (empty($mask)) {
                 $mask = 'Visual Impact';
             }
             Cache::forever('mask', $mask);
         }
         $size = 50;
         $w = $image->width();
         $h = $image->height();
         $x = round($w / 2);
         $y = round($h / 2);
         $img = Image::canvas($w, $h);
         $string = wordwrap($mask, 15, '|');
         $strings = explode('|', $string);
         $line = 2;
         $i = round($y - count($strings) / 2 * ($size + $line));
         $from = $i - 20;
         foreach ($strings as $string) {
             $draw = new \ImagickDraw();
             $draw->setStrokeAntialias(true);
             $draw->setTextAntialias(true);
             $draw->setFont(public_path('assets' . DS . 'fonts' . DS . 'times.ttf'));
             $draw->setFontSize($size);
             $draw->setFillColor('rgb(0, 0, 0)');
             $draw->setFillOpacity(0.2);
             $draw->setTextAlignment(\Imagick::ALIGN_CENTER);
             $draw->setStrokeColor('#fff');
             $draw->setStrokeOpacity(0.2);
             $draw->setStrokeWidth(1);
             $dimensions = $img->getCore()->queryFontMetrics($draw, $string);
             $posy = $i + $dimensions['textHeight'] * 0.65 / 2;
             $img->getCore()->annotateImage($draw, $x, $posy, 0, $string);
             $i += $size + $line;
         }
         return $image->insert($img, 'center', $x, $y)->encode('jpg');
     }
     if ($image) {
         return $image->encode('jpg');
     }
     return false;
 }
 private function saveDetails()
 {
     $rules = array('name' => 'required');
     $user = Auth::user()->account->users()->first();
     if (Auth::user()->id === $user->id) {
         $rules['email'] = 'email|required|unique:users,email,' . $user->id . ',id';
     }
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to('company/details')->withErrors($validator)->withInput();
     } else {
         $account = Auth::user()->account;
         $account->name = trim(Input::get('name'));
         $account->id_number = trim(Input::get('id_number'));
         $account->vat_number = trim(Input::get('vat_number'));
         $account->work_email = trim(Input::get('work_email'));
         $account->work_phone = trim(Input::get('work_phone'));
         $account->address1 = trim(Input::get('address1'));
         $account->address2 = trim(Input::get('address2'));
         $account->city = trim(Input::get('city'));
         $account->state = trim(Input::get('state'));
         $account->postal_code = trim(Input::get('postal_code'));
         $account->country_id = Input::get('country_id') ? Input::get('country_id') : null;
         $account->size_id = Input::get('size_id') ? Input::get('size_id') : null;
         $account->industry_id = Input::get('industry_id') ? Input::get('industry_id') : null;
         $account->timezone_id = Input::get('timezone_id') ? Input::get('timezone_id') : null;
         $account->date_format_id = Input::get('date_format_id') ? Input::get('date_format_id') : null;
         $account->datetime_format_id = Input::get('datetime_format_id') ? Input::get('datetime_format_id') : null;
         $account->currency_id = Input::get('currency_id') ? Input::get('currency_id') : 1;
         // US Dollar
         $account->language_id = Input::get('language_id') ? Input::get('language_id') : 1;
         // English
         $account->save();
         if (Auth::user()->id === $user->id) {
             $user->first_name = trim(Input::get('first_name'));
             $user->last_name = trim(Input::get('last_name'));
             $user->username = trim(Input::get('email'));
             $user->email = trim(strtolower(Input::get('email')));
             $user->phone = trim(Input::get('phone'));
             $user->save();
         }
         /* Logo image file */
         if ($file = Input::file('logo')) {
             $path = Input::file('logo')->getRealPath();
             File::delete('logo/' . $account->account_key . '.jpg');
             $image = Image::make($path)->resize(200, 120, true, false);
             Image::canvas($image->width, $image->height, '#FFFFFF')->insert($image)->save($account->getLogoPath());
         }
         Event::fire('user.refresh');
         Session::flash('message', trans('texts.updated_settings'));
         return Redirect::to('company/details');
     }
 }
示例#11
0
<?php

HTML::macro('spacer', function ($width, $height, $alt = '') {
    $key = "img_spacer_{$width}_{$height}";
    $src = Cache::remember($key, 1440, function () use($width, $height, $alt) {
        return Image::canvas($width, $height)->encode('data-url');
    });
    return View::make('macros/html_spacer', array('width' => $width, 'height' => $height, 'alt' => $alt, 'src' => $src));
});
HTML::macro('flash', function ($syntax = null) {
    $output = '';
    foreach (array("error", "danger", "success", "warning", "info") as $type) {
        if (Session::has($type)) {
            switch ($type) {
                case 'warning':
                    $class = 'alert-warning';
                    break;
                case 'error':
                    $class = 'alert-danger';
                    break;
                default:
                    $class = 'alert-' . $type;
                    break;
            }
            $output .= View::make('macros/html_flash', array('class' => $class, 'text' => Session::get($type)));
        }
    }
    return $output;
});
HTML::macro('render_menu', function ($menulinks) {
    $html = '<ul class="nav navbar-nav">';
示例#12
0
<div class="image hullselection">

    <div id="map"></div>

    <?php 
$src = App::make("Controllers\\ImageController")->getLatestImage();
if ($src != "") {
    $image = Image::make($src);
} else {
    // fake an image
    $image = Image::canvas(800, 640);
}
?>

    <script type="text/javascript">
        // Select a hull
        require([_jsBase + 'main.js'], function(common)
        {
            require(["app/controllers/hullselection"], function(hull)
            {
                hull.setElement($("#map"));
                hull.setImage("{{$src}}");
                hull.setImageSize("{{$image->width()}}","{{$image->height()}}");
                hull.setCoordinates("{{$value}}");
                hull.setName("{{$file."__".$attribute}}");
                hull.initialize();
            });
        });

    </script>
</div>
示例#13
0
        $salted_id = $request->input('email');
        $request->session()->put('salted_id', $salted_id);
    } else {
        $salted_id = $request->session()->get('salted_id', null);
    }
    return view('emails.halloween')->with(['salted_id' => $salted_id, 'email' => false]);
}]);
Route::get('tracking', ['as' => 'tracking', function (Request $request) {
    if ($request->input('email')) {
        $salted_id = $request->input('email');
        $email = Email::where('salted_id', '=', $salted_id)->first();
        if ($email && $email->trackable) {
            $action = Action::firstOrCreate(['action' => 'opened', 'contact_id' => $email->contact->id, 'campaign_id' => $email->campaign->id, 'touch_id' => $email->touch_id]);
        }
    }
    return \Image::canvas(10, 10)->encode('gif');
}]);
Route::get('emails/{title_slug}', ['as' => 'emails', 'uses' => 'EmailController@renderEmail']);
Route::get('ep_vikings_signup', ['as' => 'ep_vikings_signup', 'uses' => 'SignupController@epVikingsSignup']);
Route::post('ep_vikings_signup', ['as' => 'ep_vikings_submit', 'uses' => 'SignupController@epVikingsSubmit']);
Route::get('engage_signup', ['as' => 'engage_signup_generic', 'uses' => 'SignupController@engageGeneric']);
Route::post('engage_signup', ['as' => 'engage_signup_redirect', 'uses' => 'SignupController@engageRedirect']);
Route::get('engage_signup/{name}', ['as' => 'engage_signup', 'uses' => 'SignupController@engage']);
Route::post('signup', ['as' => 'signup', 'uses' => 'SignupController@signup']);
Route::post('signup/forward', ['as' => 'signup.forward', 'uses' => 'SignupController@signupForward']);
Route::get('testmail', function () {
    $campaign = Campaign::find(2);
    \Mail::send('emails.cwt.engage', ['email' => true, 'campaign' => $campaign, 'salted_id' => 'foo'], function ($mail) {
        $mail->to('*****@*****.**', 'Seth Phillips')->subject('test email');
    });
    return 'tested';
示例#14
0
 public function anggota($id)
 {
     // data sekolah
     $sekolah = Sekolah::data();
     $logo_sekolah = $sekolah->logo ?: 'blank.png';
     $nama_sekolah = $sekolah->nama;
     $alamat_sekolah = $sekolah->alamat;
     // data siswa
     $siswa = Siswa::set($id);
     $foto_siswa = $siswa->foto ?: 'blank.png';
     $nis_siswa = $siswa->nis;
     $nama_siswa = $siswa->nama;
     $kelas_siswa = $siswa->kelas;
     $telp_siswa = $siswa->telp ?: '-';
     $alamat_siswa = $siswa->alamat ?: '-';
     // path font
     $helvetica = public_path() . '/font/helvetica.ttf';
     $calibri = public_path() . '/font/calibri.ttf';
     // canvas
     $canvas = Image::canvas(325, 205);
     // logo sekolah
     $logo = Image::make(public_path() . '/foto/sekolah/' . $logo_sekolah)->resize(null, 38, true);
     $canvas->insert($logo, 5, 5, 'top-left');
     // header nama
     $header_nama = imagettfbbox(10, 0, $helvetica, $nama_sekolah);
     $lebar_header_nama = abs($header_nama[2] - $header_nama[0]);
     $canvas->text($nama_sekolah, 350 / 2 - $lebar_header_nama / 2, 15, 10, '333', 0, $helvetica);
     // nama kartu
     $nama_kartu = imagettfbbox(10, 0, $helvetica, 'KARTU ANGGOTA PERPUSTAKAAN');
     $lebar_nama_kartu = abs($nama_kartu[2] - $nama_kartu[0]);
     $canvas->text('KARTU ANGGOTA PERPUSTAKAAN', 350 / 2 - $lebar_nama_kartu / 2, 30, 10, '333', 0, $helvetica);
     // header alamat
     $header_alamat = imagettfbbox(8, 0, $calibri, $alamat_sekolah);
     $lebar_header_alamat = abs($header_alamat[2] - $header_alamat[0]);
     $canvas->text($alamat_sekolah, 350 / 2 - $lebar_header_alamat / 2, 42, 8, '000', 0, $calibri);
     // garis
     $canvas->line('333', 5, 46, 315, 46);
     // nis
     $canvas->text('N I S', 5, 60, 8, '000', 0, $calibri);
     $canvas->text(': ' . $nis_siswa, 40, 60, 8, '000', 0, $calibri);
     // nama
     $canvas->text('Nama', 5, 73, 8, '000', 0, $calibri);
     $canvas->text(': ' . $nama_siswa, 40, 73, 8, '000', 0, $calibri);
     // kelas
     $canvas->text('Kelas', 5, 86, 8, '000', 0, $calibri);
     $canvas->text(': ' . $kelas_siswa, 40, 86, 8, '000', 0, $calibri);
     // telp
     $canvas->text('Telp', 5, 99, 8, '000', 0, $calibri);
     $canvas->text(': ' . $telp_siswa, 40, 99, 8, '000', 0, $calibri);
     // alamat
     $canvas->text('Alamat', 5, 112, 8, '000', 0, $calibri);
     $canvas->text(': ' . $alamat_siswa, 40, 112, 8, '000', 0, $calibri);
     // foto
     $foto = Image::make(public_path() . '/foto/siswa/' . $foto_siswa)->resize(null, 80, true);
     $canvas->insert($foto, 5, 5, 'bottom-left');
     // qrcode
     $path_qr = public_path() . '/qrcode/' . $siswa->nis . '.png';
     // belum ada qrcode
     if (!File::exists($path_qr)) {
         $qr = new QR();
         $qr->setText($nama_siswa);
         $qr->setSize(80);
         $qr->setPadding(0);
         $qr->save($path_qr);
         $qr_code = $path_qr;
         // ada qrcode
     } else {
         $qr_code = Image::make($path_qr)->resize(null, 80, true);
     }
     $canvas->insert($qr_code, 5, 5, 'bottom-right');
     // simpan
     $canvas->save(public_path() . '/anggota/' . $nis_siswa . '.png', 100);
     // gambar
     $gambar = asset('anggota/' . $nis_siswa . '.png');
     return View::make('modal.anggota', compact('siswa', 'gambar'));
 }
示例#15
0
 /**
  * Уменьшаем размер исходного изображения с сохранением пропорций так,
  * чтобы новое получилось вписанным в указанный размер
  * Там где изображение уже отсутствует - добиваем белым цветом до указанного размера
  *
  * @param type $width
  * @param type $height
  *
  * @return \Image
  */
 static function cropImgInBox(\Intervention\Image\Image $img, $width, $height)
 {
     //сделаем так, чтобы исходная картинка вписывалась большей стороной в указанный прямоугольник
     $img = self::resizeImgInBox($img, $width, $height);
     return \Image::canvas($width, $height)->insert($img, 'center-center');
 }
示例#16
0
 /**
  *
  */
 public function file_upload_resize_cut($photo, $work, $destination_path, $target_path, $action)
 {
     // name the ref field after the work id
     $ref = sprintf("%04d", $work->id);
     $photo->move($destination_path, $work->id);
     $target = $destination_path . $work->id;
     $canvas = Image::canvas(640, 640, '#ffffff');
     $layer = Image::make($target);
     $photo_height = $layer->height();
     $photo_width = $layer->width();
     if ($photo_height > $photo_width) {
         //portrait, vertical
         $layer->resize(null, 640, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         });
     } else {
         //landscape, horizontal
         $layer->resize(640, null, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         });
     }
     // add the layer to the canvas, centered
     $image = $canvas->insert($layer, 'center', 320, 320);
     $image->save($target_path . '640/' . $ref . '.jpg');
     $image->resize(320, 320);
     $image->save($target_path . '320/' . $ref . '.jpg');
     $image->resize(160, 160);
     $image->save($target_path . '160/' . $ref . '.jpg');
     $image->resize(120, 120);
     $image->save($target_path . '120/' . $ref . '.jpg');
     $image->resize(64, 64);
     $image->save($target_path . '64/' . $ref . '.jpg');
 }
示例#17
0
 public function postIndex()
 {
     // to prevent abuse of the system we generate a random hash and assign it to user's session
     // this way the same user cannot create many posters - only one allowed per session.
     if (!Session::has('hash')) {
         $hash = str_random(8);
         Session::put('hash', $hash);
         File::makeDirectory('uploads/' . $hash);
     } else {
         $hash = Session::get('hash');
         if (!File::exists('uploads/' . $hash)) {
             File::makeDirectory('uploads/' . $hash);
         }
     }
     $destinationPath = 'uploads/' . $hash;
     $filename = Session::get('filename', 'original.jpg');
     $fullpath = $destinationPath . '/' . $filename;
     // determine if the image should be cropped or not
     $cropped = false;
     if (Input::get('w') != '' && Input::get('w') != 0) {
         $cropped = true;
         // crop the image
         Image::open($fullpath)->crop(Input::get('w'), Input::get('h'), Input::get('x'), Input::get('y'))->save($destinationPath . '/cropped.jpg');
         $filename = 'cropped.jpg';
         $fullpath = $destinationPath . '/' . $filename;
     }
     // define size of the poster
     $imgwidth = 1224;
     $imgheight = 1584;
     // create empty image on top of which everything else will go
     $img = Image::canvas($imgwidth, $imgheight, '#FFFFFF');
     // get text from the inputs
     $headerText = Input::get('header', 'Missing pet');
     $petName = Input::get('name', 'name');
     $petBreed = Input::get('breed', 'breed');
     $petColor = Input::get('color', 'color');
     $petGender = Input::get('gender', 'gender');
     $petDate = Input::get('date', 'date');
     $contactInfo = Input::get('contact', 'contact');
     // determine size of the text strings
     $headerArSize = imagettfbbox(72, 0, 'font/OpenSans-Semibold.ttf', $headerText);
     $headerWidth = abs($headerArSize[2] - $headerArSize[0]);
     $petNameArSize = imagettfbbox(50, 0, 'font/OpenSans-Semibold.ttf', $petName);
     $petNameWidth = abs($petNameArSize[2] - $petNameArSize[0]);
     $petBreedArSize = imagettfbbox(50, 0, 'font/OpenSans-Semibold.ttf', $petBreed);
     $petBreedWidth = abs($petBreedArSize[2] - $petBreedArSize[0]);
     $petColorArSize = imagettfbbox(50, 0, 'font/OpenSans-Semibold.ttf', $petColor);
     $petColorWidth = abs($petColorArSize[2] - $petColorArSize[0]);
     $petGenderArSize = imagettfbbox(50, 0, 'font/OpenSans-Semibold.ttf', $petGender);
     $petGenderWidth = abs($petGenderArSize[2] - $petGenderArSize[0]);
     $petDateArSize = imagettfbbox(50, 0, 'font/OpenSans-Semibold.ttf', $petDate);
     $petDateWidth = abs($petDateArSize[2] - $petDateArSize[0]);
     // write text on top of empty canvas
     $img->text($headerText, $imgwidth / 2 - $headerWidth / 2, 120, 72, '#000000', null, 'font/OpenSans-Semibold.ttf');
     $img->text($petName, $imgwidth / 2 - $petNameWidth / 2, 930, 50, '#333333', null, 'font/OpenSans-Semibold.ttf');
     $img->text($petBreed, $imgwidth / 2 - $petBreedWidth / 2, 1020, 50, '#333333', null, 'font/OpenSans-Semibold.ttf');
     $img->text($petColor, $imgwidth / 2 - $petColorWidth / 2, 1110, 50, '#333333', null, 'font/OpenSans-Semibold.ttf');
     $img->text($petGender, $imgwidth / 2 - $petGenderWidth / 2, 1200, 50, '#333333', null, 'font/OpenSans-Semibold.ttf');
     $img->text($petDate, $imgwidth / 2 - $petDateWidth / 2, 1280, 50, '#333333', null, 'font/OpenSans-Semibold.ttf');
     // write contact info
     $img->text($contactInfo, 200, 1370, 32, '#333333', null, 'font/OpenSans-Semibold.ttf');
     // assign avatar of the pet
     if (File::exists($fullpath)) {
         $avatar = Image::make($fullpath);
     } else {
         $avatar = Image::make('img/dogsketch.jpg');
     }
     $img->insert($avatar, $imgwidth / 2 - $avatar->width / 2, 170);
     $img->save($destinationPath . '/poster.jpg');
     return Response::json(array('image' => url($destinationPath . '/poster.jpg?' . time())), 200);
 }
示例#18
0
 public static function process($modelConfig, $imageFields, $parentProperty)
 {
     $imageData = array();
     $counter = 0;
     foreach ($imageFields as $imageField) {
         $imageData[$counter]['property'] = $imageField->property;
         if (\Request::hasFile($imageField->property)) {
             $ext = \Request::file($imageField->property)->getClientOriginalExtension();
             if (!in_array(strtolower($ext), array('jpg', 'jpeg', 'gif', 'png'))) {
                 throw new \Exception("File is not an image");
             } else {
                 $basePath = public_path() . "/img/modelImages/" . $modelConfig->name . "/";
                 $dirs = [public_path("img"), public_path("img/modelImages"), public_path("img/modelImages/" . $modelConfig->name), public_path("img/modelImages/" . $modelConfig->name . "/original"), public_path("img/modelImages/" . $modelConfig->name . "/gtcmsThumb")];
                 foreach ($dirs as $dir) {
                     if (!is_dir($dir)) {
                         mkdir($dir, 0755);
                     }
                 }
                 //here check if file exists
                 do {
                     $name = str_random(32) . "." . $ext;
                 } while (file_exists($basePath . "original/" . $name));
                 //end check
                 //copy the image to the original folder
                 \Image::make(\Request::file($imageField->property)->getRealPath())->save($basePath . "original/" . $name);
                 $img = \Image::make($basePath . "original/" . $name);
                 if ($parentProperty && $modelConfig->name == 'ModelImage') {
                     $parentModelConfig = AdminHelper::modelExists($parentProperty, 'id');
                     if (config('gtcms.premium') && $parentModelConfig->keyBasedSizes) {
                         $sizes = GtcmsPremium::getKeyBasedImageSizes($parentModelConfig);
                     } else {
                         $sizes = $parentModelConfig->imageSizes;
                     }
                 } else {
                     $sizes = $imageField->sizes;
                 }
                 if (!$sizes) {
                     throw new \Exception("Sizes not found!");
                 }
                 // Get the first size, which has the min/max dimensions
                 foreach ($sizes as $size) {
                     break;
                 }
                 $size = AdminHelper::objectToArray($size);
                 $minWidth = $size[0];
                 $minHeight = $size[1];
                 $transformMethod = $size[2];
                 if (in_array($transformMethod, array('resizeCanvas', 'resize'))) {
                     if ($img->width() < $minWidth && $img->height() < $minHeight) {
                         throw new \Exception(trans('gtcms.imageTooSmall'), self::DIM_ERROR);
                     }
                 }
                 if (in_array($transformMethod, array('minWidth'))) {
                     if ($img->width() < $minWidth) {
                         throw new \Exception(trans('gtcms.imageTooSmall'), self::DIM_ERROR);
                     }
                 }
                 if (in_array($transformMethod, array('minHeight'))) {
                     if ($img->height() < $minHeight) {
                         throw new \Exception(trans('gtcms.imageTooSmall'), self::DIM_ERROR);
                     }
                 } else {
                     if ($img->width() < $minWidth || $img->height() < $minHeight) {
                         throw new \Exception(trans('gtcms.imageTooSmall'), self::DIM_ERROR);
                     }
                 }
                 $returnFolder = 'gtcmsThumb';
                 $gtcmsSize = array(80, 80, 'resizeCanvas', 'gtcmsThumb', 100);
                 $sizes = AdminHelper::objectToArray($sizes);
                 array_unshift($sizes, $gtcmsSize);
                 foreach ($sizes as $size) {
                     $newImg = clone $img;
                     $size = AdminHelper::objectToArray($size);
                     if (!is_dir($basePath . $size[3])) {
                         mkdir($basePath . $size[3], 0755);
                     }
                     if ($size[2] == 'crop') {
                         $newImg->fit($size[0], $size[1])->save($basePath . $size[3] . "/" . $name, $size[4]);
                     } else {
                         if (in_array($size[2], array('resize', 'minWidth', 'minHeight'))) {
                             $newImg->resize($size[0], $size[1], function ($constraint) {
                                 $constraint->aspectRatio();
                                 $constraint->upsize();
                             })->save($basePath . $size[3] . "/" . $name, $size[4]);
                         } else {
                             if ($size[2] == 'resizeCanvas') {
                                 $newImg->resize($size[0], null, function ($constraint) {
                                     $constraint->aspectRatio();
                                     $constraint->upsize();
                                 });
                                 $newImg->resize(null, $size[1], function ($constraint) {
                                     $constraint->aspectRatio();
                                     $constraint->upsize();
                                 });
                                 if ($newImg->width() < $size[0] || $newImg->height() < $size[1]) {
                                     $newImg = \Image::canvas($size[0], $size[1], '#FFFFFF')->insert($newImg, 'center');
                                 }
                                 $newImg->save($basePath . $size[3] . "/" . $name, $size[4]);
                             } else {
                                 $newImg->save($basePath . $size[3] . "/" . $name, $size[4]);
                             }
                         }
                     }
                 }
                 $imageData[$counter]['filename'] = $name;
                 $imageData[$counter]['returnFolder'] = $returnFolder;
                 $counter++;
             }
         }
     }
     return $imageData;
 }