コード例 #1
0
 /**
  * Upload Avatar from Base64 encoded image
  * 
  * @param \RainLab\User\Models\User $user
  * @param string $source
  * string contend of an image on Base64 enconding 
  */
 public static function uploadAvatarFromString($user, $source)
 {
     $dst = '/tmp/avatar_' . $user->getKey() . '_' . uniqid();
     FileHelper::put($dst, base64_decode($source));
     $validImage = true;
     try {
         // Validated is a JPG or PNG
         $imageType = exif_imagetype($dst);
         $validImage = in_array($imageType, [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF]);
         // Validated is not bigger that xx by xx
         if ($validImage) {
             // Test if image is corrupted if OctoberCMS Resizer can open it
             // is more likely the image is ok
             Resizer::open($dst);
             // Test image dimensions
             list($width, $height, $type, $attr) = getimagesize($dst);
             $validImage = $width <= 400 && $height <= 400;
         }
         // Add right file extension to the upload file
         if ($validImage) {
             // Save image with correct image extension
             $extension = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_GIF => 'gif'][$imageType];
             $newDst = $dst . '.' . $extension;
             rename($dst, $newDst);
             $dst = $newDst;
         }
     } catch (\Exception $e) {
         $validImage = false;
     }
     if (!$validImage) {
         throw new \Exception('Must be a valid JPG, GIF or PNG. And not bigger that 400x400 pixels.');
     }
     $file = new File();
     $file->data = $dst;
     $file->is_public = true;
     $file->save();
     if ($file) {
         $user->avatar()->add($file);
     }
 }