Example #1
0
 public function avatar()
 {
     $uid = $this->request->get('uid');
     $size = $this->request->get('s');
     if (!is_numeric($uid)) {
         Typecho_Common::error(404);
         exit;
     }
     $path = __TYPECHO_ROOT_DIR__ . Widget_Common::getAvatarPath($uid);
     $path .= $uid . '.jpg';
     if (!is_file($path)) {
         $path = __TYPECHO_ROOT_DIR__ . '/usr/avatar/default.jpg';
     }
     require_once __TYPECHO_ROOT_DIR__ . '/var/Util/Image.php';
     $image = new Image();
     $image->open($path);
     $type = $image->type();
     if (is_numeric($size)) {
         $image->thumb($size, $size);
     }
     header('Content-Type:image/' . $type . ';');
     //输出图像
     if ('jpeg' == $type || 'jpg' == $type) {
         // 采用jpeg方式输出
         imagejpeg($image->showImg());
     } elseif ('gif' == $type) {
         imagegif($image->showImg());
     } else {
         $fun = 'image' . $type;
         $fun($image->showImg());
     }
 }
Example #2
0
 public function thumbnail()
 {
     $siteUrl = Typecho_Widget::widget('Widget_Options')->siteUrl;
     $url = $this->request->get('url');
     $size = $this->request->get('s');
     if ($size) {
         $size = explode('x', $size);
         $size[1] = isset($size[1]) ? $size[1] : $size[0];
     } else {
         $options = Typecho_Widget::widget('Widget_Options')->plugin('Tools');
         $width = $options->thumbnailwidth;
         $height = $options->thumbnailheight;
         $size = array($width, $height);
     }
     $path = __TYPECHO_ROOT_DIR__ . $url;
     if (!is_file($path)) {
         exit;
     }
     require_once 'Image.php';
     $image = new Image();
     $image->open($path);
     $type = $image->type();
     $image->thumb($size[0], $size[1], 3);
     header('Content-Type:image/' . $type . ';');
     //输出图像
     if ('jpeg' == $type || 'jpg' == $type) {
         // 采用jpeg方式输出
         imagejpeg($image->showImg());
     } elseif ('gif' == $type) {
         imagegif($image->showImg());
     } else {
         $fun = 'image' . $type;
         $fun($image->showImg());
     }
 }
Example #3
0
 public function update_avatar($uID = false)
 {
     $this->setupUser($uID);
     if (!Loader::helper('validation/token')->validate()) {
         throw new Exception(Loader::helper('validation/token')->getErrorMessage());
     }
     if ($this->canEditAvatar) {
         $av = Loader::helper('concrete/avatar');
         if (is_uploaded_file($_FILES['avatar']['tmp_name'])) {
             $image = \Image::open($_FILES['avatar']['tmp_name']);
             $image = $image->thumbnail(new Box(Config::get('concrete.icons.user_avatar.width'), Config::get('concrete.icons.user_avatar.height')));
             $this->user->updateUserAvatar($image);
         } else {
             if ($_POST['task'] == 'clear') {
                 $this->user->update(array('uHasAvatar' => 0));
             }
         }
     } else {
         throw new Exception(t('Access Denied.'));
     }
     $ui = UserInfo::getByID($uID);
     // avatar doesn't reload automatically
     $sr = new UserEditResponse();
     $sr->setUser($this->user);
     $sr->setMessage(t('Avatar saved successfully.'));
     $html = $av->outputUserAvatar($ui);
     $sr->setAdditionalDataAttribute('imageHTML', $html);
     $sr->outputJSON();
 }
Example #4
0
 public function update_avatar($uID = false)
 {
     $this->setupUser($uID);
     if (!$this->app->make('helper/validation/token')->validate()) {
         throw new Exception($this->app->make('helper/validation/token')->getErrorMessage());
     }
     if ($this->canEditAvatar) {
         $file = $this->request->files->get('avatar');
         if ($file !== null) {
             /* @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
             if (!$file->isValid()) {
                 throw new Exception($file->getErrorMessage());
             }
             $image = \Image::open($file->getPathname());
             $config = $this->app->make('config');
             $image = $image->thumbnail(new Box($config->get('concrete.icons.user_avatar.width'), $config->get('concrete.icons.user_avatar.height')));
             $this->user->updateUserAvatar($image);
         } elseif ($this->request->post('task') == 'clear') {
             $this->user->update(['uHasAvatar' => 0]);
         }
     } else {
         throw new Exception(t('Access Denied.'));
     }
     $ui = UserInfo::getByID($uID);
     // avatar doesn't reload automatically
     $sr = new UserEditResponse();
     $sr->setUser($this->user);
     $sr->setMessage(t('Avatar saved successfully.'));
     $av = $this->user->getUserAvatar();
     $html = $av->output();
     $sr->setAdditionalDataAttribute('imageHTML', $html);
     $sr->outputJSON();
 }
 public function postProfil()
 {
     $validate = Validator::make(Input::all(), ['adsoyad' => 'required', 'email' => 'required|email|unique:users,email,' . Auth::user()->id . '', 'profil' => 'mimes:jpg,png,gif,jpeg']);
     $messages = $validate->messages();
     if ($validate->fails()) {
         return Redirect::back()->with(array('mesaj' => 'true', 'title' => 'Doğrulama Hatası', 'text' => '' . $messages->first() . '', 'type' => 'error'));
     }
     $user = User::findOrFail(Auth::user()->id);
     $user->namesurname = Input::get('adsoyad');
     if (Input::has('password')) {
         $user->password = Hash::make(Input::get('password'));
         $user->save();
     }
     $user->email = Input::get('email');
     if (Input::hasFile('profil')) {
         if (Auth::user()->profil != '') {
             File::delete('Backend/avatar/' . Auth::user()->profil . '');
         }
         $profil = Input::file('profil');
         $dosyaadi = $profil->getClientOriginalName();
         $uzanti = $profil->getClientOriginalExtension();
         $isim = Str::slug($dosyaadi) . Str::slug(str_random(5)) . '.' . $uzanti;
         $dosya = $profil->move('Backend/avatar/', $isim);
         $image = Image::open('Backend/avatar/' . $isim)->resize(80, 80)->save();
         $user->profil = $isim;
         $user->save();
     }
     $user->save();
     if ($user->save()) {
         return Redirect::back()->with(array('mesaj' => 'true', 'title' => 'Kullanıcı Güncellendi', 'text' => 'Kullanıcı Başarı İle Güncellendi', 'type' => 'success'));
     } else {
         return Redirect::back()->with(array('mesaj' => 'true', 'title' => 'Kullanıcı Güncellenemedi', 'text' => 'Kullanıcı Güncellenirken Sorun İle Karşılaşıldı', 'type' => 'error'));
     }
 }
Example #6
0
 /**
  * Test
  *
  * @return void
  */
 public function testSaveInBmp()
 {
     $savingPath = $this->directory . 'saving-test.bmp';
     $this->object->open($this->directory . 'test.png');
     $this->object->resize(50, 50);
     $this->assertFalse($this->object->save($savingPath));
 }
Example #7
0
 public function placeOver(Image $background, $posX, $posY)
 {
     $background->open();
     $this->open();
     imagecopy($background->getResource(), $this->getResource(), $posX, $posY, 0, 0, $this->getWidth(), $this->getHeight());
     $filepath = $background->getFilepath();
     return $this->_writeImageToDisk($filepath, $background->getResource(), $background->getType());
 }
Example #8
0
 public function completeAuthentication(User $u)
 {
     $ui = \UserInfo::getByID($u->getUserID());
     if (!$ui->hasAvatar()) {
         try {
             $image = \Image::open($this->getExtractor()->getImageURL());
             $ui->updateUserAvatar($image);
         } catch (\Imagine\Exception\InvalidArgumentException $e) {
             \Log::addNotice("Unable to fetch user images in Google Authentication Type, is allow_url_fopen disabled?");
         } catch (\Exception $e) {
         }
     }
     return parent::completeAuthentication($u);
 }
 public function storeCover(BookInterface $book, $cover)
 {
     Storage::disk('book_local')->put("{$book->id}/Resources/Templates/ebook/cover.jpg", File::get($cover));
     Storage::disk('book_local')->put("{$book->id}/Resources/Templates/cover.jpg", File::get($cover));
     $print_path = storage_path("books/{$book->id}/Resources/Templates/print");
     if (!is_dir($print_path)) {
         mkdir($print_path, 0775, true);
     }
     $img = new \Imagick(storage_path("books/{$book->id}/Resources/Templates/ebook/cover.jpg"));
     $img->setImageFormat("pdf");
     $img->writeImage(storage_path("books/{$book->id}/Resources/Templates/print/cover.pdf"));
     $thumbnail = \Image::open(storage_path("books/{$book->id}/Resources/Templates/ebook/cover.jpg"))->thumbnail(new Box(356, 522));
     $thumbnail->save(public_path("books/thumbs/{$book->id}.jpg"));
     $thumbnail = \Image::open(storage_path("books/{$book->id}/Resources/Templates/ebook/cover.jpg"))->thumbnail(new Box(138, 230));
     $thumbnail->save(public_path("books/thumbs/{$book->id}_small.jpg"));
 }
Example #10
0
File: image.php Project: rair/yacs
 /**
  * create a thumbnail
  *
  * @param string the full path to the original file
  * @param string the pull path to write the thumbnail
  * @param boolean TRUE to resize to 60x60
  * @param boolean TRUE to see error messages, if any
  * @return TRUE on success, FALSE on error
  */
 public static function shrink($original, $target, $fixed = FALSE, $verbose = TRUE)
 {
     global $context;
     $file_name = basename($original);
     $open = Image::open($original);
     if ($open === FALSE) {
         return FALSE;
     }
     list($image, $image_information) = $open;
     // actual width
     $width = $image_information[0];
     // standard width
     if ($fixed) {
         $maximum_width = 60;
     } elseif (isset($context['thumbnail_width']) && $context['thumbnail_width'] >= 32) {
         $maximum_width = $context['thumbnail_width'];
     } else {
         $maximum_width = 60;
     }
     // actual height
     $height = $image_information[1];
     // standard height
     if ($fixed) {
         $maximum_height = 60;
     } elseif (isset($context['thumbnail_height']) && $context['thumbnail_height'] >= 32) {
         $maximum_height = $context['thumbnail_height'];
     } else {
         $maximum_height = 60;
     }
     // assume resize is not necessary
     $thumbnail_height = $height;
     $thumbnail_width = $width;
     // the image is laid vertically
     if ($height > $width) {
         // set the thumbnail size
         if ($height > $maximum_height) {
             $thumbnail_height = $maximum_height;
             $thumbnail_width = $width * $thumbnail_height / $height;
         }
         // the image is laid horizontally
     } else {
         // set the thumbnail size
         if ($width > $maximum_width) {
             $thumbnail_width = $maximum_width;
             $thumbnail_height = $height * $thumbnail_width / $width;
         }
     }
     // create target folder for the thumbnail
     if ($target_path = dirname($target)) {
         Safe::make_path($target_path);
     }
     // we already have a small image
     if ($thumbnail_width == $width && $thumbnail_height == $height) {
         // copy file content to the thumbnail
         if (!copy($original, $target)) {
             if ($verbose) {
                 Logger::error(sprintf(i18n::s('Cannot copy image to %s'), $target));
             }
             return FALSE;
         }
         // this will be filtered by umask anyway
         Safe::chmod($target, $context['file_mask']);
         // job done
         return TRUE;
     }
     // create the thumbnail in memory
     $thumbnail = NULL;
     if (Image::use_magic()) {
         $thumbnail = $image->resizeImage($thumbnail_width, $thumbnail_height, Imagick::FILTER_POINT, 1);
     } else {
         if ($image_information[2] == 2 && is_callable('ImageCreateTrueColor') && ($thumbnail = ImageCreateTrueColor($thumbnail_width, $thumbnail_height))) {
             ImageCopyResampled($thumbnail, $image, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $width, $height);
         }
         if (!$thumbnail && is_callable('ImageCreate') && ($thumbnail = ImageCreate($thumbnail_width, $thumbnail_height))) {
             ImageCopyResized($thumbnail, $image, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $width, $height);
         }
     }
     // sanity check
     if (!$thumbnail) {
         if ($verbose) {
             Logger::error(sprintf(i18n::s('Impossible to skrink image %s'), $file_name));
         }
         return FALSE;
     }
     // save the thumbnail in the file system
     $result = FALSE;
     if (Image::use_magic()) {
         $result = $image->writeImage($target);
     } else {
         if ($image_information[2] == 1 && is_callable('ImageGIF')) {
             ImageGIF($thumbnail, $target);
         } elseif ($image_information[2] == 2 && is_callable('ImageJPEG')) {
             ImageJPEG($thumbnail, $target, IMG_JPEG_QUALITY);
         } elseif (($image_information[2] == 1 || $image_information[2] == 3) && is_callable('ImagePNG')) {
             ImagePNG($thumbnail, $target);
         } else {
             if ($verbose) {
                 Logger::error(sprintf(i18n::s('Impossible to write to %s.'), $target));
             }
             return FALSE;
         }
     }
     // this will be filtered by umask anyway
     Safe::chmod($target, $context['file_mask']);
     // job done
     if (Image::use_magic()) {
         $image->destroy();
     } else {
         ImageDestroy($thumbnail);
     }
     return TRUE;
 }
Example #11
0
 /**
  * 上传文件的主处理方法
  * @return mixed
  */
 private function upFile()
 {
     $file = $this->file = $_FILES[$this->fileField];
     if (!$file) {
         $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
         return;
     }
     if ($this->file['error']) {
         $this->stateInfo = $this->getStateInfo($file['error']);
         return;
     } else {
         if (!file_exists($file['tmp_name'])) {
             $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
             return;
         } else {
             if (!is_uploaded_file($file['tmp_name'])) {
                 $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
                 return;
             }
         }
     }
     $this->oriName = $file['name'];
     $this->fileSize = $file['size'];
     $this->fileType = $this->getFileExt();
     $this->fullName = $this->getFullName();
     $this->filePath = $this->getFilePath();
     $this->fileName = $this->getFileName();
     $dirname = dirname($this->filePath);
     //检查文件大小是否超出限制
     if (!$this->checkSize()) {
         $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
         return;
     }
     //检查是否不允许的文件格式
     if (!$this->checkType()) {
         $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
         return;
     }
     //创建目录失败
     if (!file_exists($dirname) && !mkdir($dirname, 0777, TRUE)) {
         $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
         return;
     } else {
         if (!is_writeable($dirname)) {
             $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
             return;
         }
     }
     //移动文件
     if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) {
         //移动失败
         $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
     } else {
         //移动成功
         $this->stateInfo = $this->stateMap[0];
         //加水印
         require_once "Image.class.php";
         $image = new Image();
         $image->open($this->filePath)->thumb('480', '5000', Image::IMAGE_THUMB_SCALE)->water('./logo.png', Image::IMAGE_WATER_SOUTHEAST, 100)->save($this->filePath);
     }
 }
Example #12
0
//echo $caminho; exit;
$div1 = explode(".", $caminho);
$new = $div1[0];
for ($i = 1; $i < count($div1) - 1; $i++) {
    $new .= "." . $div1[$i];
}
$nome = basename($caminho);
$nome = str_replace("." . $div1[count($div1) - 1], "", $nome);
$div2 = explode('-', $new);
$width = $div2[count($div2) - 2];
$height = $div2[count($div2) - 1];
$caminho = str_replace("size-" . $width . "-" . $height, "", $caminho);
$arq = new Arquivos(str_replace("", '', Sistema::$caminhoDiretorio) . urldecode($caminho));
header('Expires: 0');
header('Pragma: no-cache');
if (strtoupper($arq->extensao) == "JPEG" || strtoupper($arq->extensao) == "JPG" || strtoupper($arq->extensao) == "PNG" || strtoupper($arq->extensao) == "GIF" || strtoupper($arq->extensao) == "BMP") {
    header("Content-type: image/" . $arq->extensao);
    $img = new Image($arq);
    $img->open();
    if (!empty($width) && !empty($height)) {
        $img->redimensionar($width, $height);
        $img->saveImage(dirname(substr(str_replace("", '', Sistema::$caminhoDiretorio), 0, -1) . urldecode($caminho)), urldecode($nome));
    }
    $img->getImage();
} else {
    header("Content-Type: application/" . $arq->extensao);
    header('Content-disposition: attachment; filename="' . $arq->getNome() . '";');
    $len = filesize($arq->url);
    header("Content-Length: " . $len . ";\n");
    echo $arq->arquivo;
}
 /**
  * Returns a path to the specified item, resized and/or cropped to meet max width and height. $obj can either be
  * a string (path) or a file object.
  * Returns an object with the following properties: src, width, height
  *
  * @param File|string $obj
  * @param int $maxWidth
  * @param int $maxHeight
  * @param bool $crop
  * @return \stdClass Object that has the following properties: src, width, height
  */
 public function getThumbnail($obj, $maxWidth, $maxHeight, $crop = false)
 {
     $storage = $this->getStorageLocation();
     $filesystem = $storage->getFileSystemObject();
     $configuration = $storage->getConfigurationObject();
     $fh = \Core::make('helper/file');
     if ($obj instanceof File) {
         try {
             $fr = $obj->getFileResource();
             $fID = $obj->getFileID();
             $filename = md5(implode(':', array($fID, $maxWidth, $maxHeight, $crop, $fr->getTimestamp()))) . '.' . $fh->getExtension($fr->getPath());
         } catch (\Exception $e) {
             $filename = '';
         }
     } else {
         $filename = md5(implode(':', array($obj, $maxWidth, $maxHeight, $crop, filemtime($obj)))) . '.' . $fh->getExtension($obj);
     }
     $abspath = '/cache/' . $filename;
     if (!$filesystem->has($abspath)) {
         if ($obj instanceof File && $fr->exists()) {
             $image = \Image::load($fr->read());
         } else {
             $image = \Image::open($obj);
         }
         // create image there
         $this->create($image, $abspath, $maxWidth, $maxHeight, $crop);
     }
     $src = $configuration->getPublicURLToFile($abspath);
     $thumb = new \stdClass();
     $thumb->src = $src;
     //this is terrible
     try {
         //try and get it locally, otherwise use http
         $dimensions = getimagesize($abspath);
     } catch (\Exception $e) {
         //$dimensions = getimagesize($src);
     }
     $thumb->width = $dimensions[0];
     $thumb->height = $dimensions[1];
     return $thumb;
 }
Example #14
0
 /**
  * @param Request $request
  */
 protected function imageManipulationSync(Request $request)
 {
     $file = $request->file('image');
     $nomeFoto = $request->get('foto');
     $file->move("foto/real/", $nomeFoto);
     $urlFilePath = 'foto/real/' . $nomeFoto;
     $thumbnail = \Image::open($urlFilePath)->thumbnail(new \Imagine\Image\Box(90, 70));
     $thumbnail->save('foto/thumbnail/' . $nomeFoto);
     $thumbnail = \Image::open($urlFilePath)->thumbnail(new \Imagine\Image\Box(400, 300));
     $thumbnail->save('foto/medium/' . $nomeFoto);
 }
Example #15
0
 public static function process_image($extend)
 {
     $file = Arr::get(static::files(), $extend->key);
     if ($file and $file['error'] === UPLOAD_ERR_OK) {
         $name = basename($file['name']);
         $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
         if ($filepath = static::upload($file)) {
             $filename = basename($filepath);
             // resize image
             if (isset($extend->attributes->size->width) and isset($extend->attributes->size->height)) {
                 $image = Image::open($filepath);
                 $width = intval($extend->attributes->size->width);
                 $height = intval($extend->attributes->size->height);
                 // resize larger images
                 if ($width and $height and ($image->width() > $width or $image->height() > $height)) {
                     $image->resize($width, $height);
                     $image->output($ext, $filepath);
                 }
             }
             return Json::encode(compact('name', 'filename'));
         }
     }
 }
Example #16
0
 /**
  * Get the thumb image for manipulation
  * @return \Imagine\Image\ImageInterface
  */
 public function loadImage()
 {
     return Image::open($this->getCachePath());
 }
Example #17
0
 * 得到上传文件所对应的各个参数,数组结构
 * array(
 *     "state" => "",          //上传状态,上传成功时必须返回"SUCCESS"
 *     "url" => "",            //返回的地址
 *     "title" => "",          //新文件名
 *     "original" => "",       //原始文件名
 *     "type" => ""            //文件类型
 *     "size" => "",           //文件大小
 * )
 */
$config = (include $rootpath . '/App/Admin/Conf/Water.php');
if ($config['WATER_FUNTION'] == 1) {
    $info = $up->getFileInfo();
    $filePath = $rootpath . $info['url'];
    $imgObj = new Image();
    $imgObj->open($filePath);
    $waterpos = $config['WATER_POS'];
    $watercom = $config['WATER_COMPRESSION'];
    switch ($config['WATER_FILE_TYPE']) {
        case 1:
            $waterimg = $rootpath . $config['WATER_IMAGE'];
            $imgObj->water($waterimg, $waterpos, $watercom);
            break;
        case 2:
            $waterfont = $rootpath . $config['WATER_FONTFILE'];
            $imgObj->text($config['WATER_TEXT'], $waterfont, $config['WATER_FONTSIZE'], $config['WATER_FONTCOLOR'], $waterpos, 0, $config['WATER_ANGLE']);
            break;
    }
    $imgObj->save($filePath);
}
/* 返回数据 */
 /**
  * put your comment there...
  * 
  */
 protected function _generateThumbnail()
 {
     if ($this->attributes['width'] == $this->_original_image_info[0] && $this->attributes['height'] == $this->_original_image_info[1]) {
         $this->_calculated_width = $this->attributes['width'];
         return $this->_calculated_height = $this->attributes['height'];
     }
     if ($this->attributes['width'] == 0 || $this->attributes['height'] == 0) {
         $this->_calculated_width = $this->_original_image_info[0];
         return $this->_calculated_height = $this->_original_image_info[1];
     }
     //make sure the thumbnail directory exists.
     if (!is_writable($this->thumbs_dir_path)) {
         trigger_error('Cannot detect a writable thumbs directory!', E_USER_NOTICE);
     }
     if (is_readable($this->_thumb_src)) {
         $this->_calculated_width = (int) $this->attributes['width'];
         $this->_calculated_height = (int) $this->attributes['height'];
         return $this->src = $this->_thumb_src;
     }
     // resize image
     $image = new Image();
     $image->open($this->src, $this->thumb_background_rgb)->resize((int) $this->attributes['width'], (int) $this->attributes['height'])->save($this->_thumb_src, (int) $this->thumb_quality);
     $this->_thumbnail = $image;
     $this->_calculated_width = $this->_thumbnail->getWidth();
     $this->_calculated_height = $this->_thumbnail->getHeight();
     $this->src = $this->_thumb_src;
 }
Example #19
0
 $img->setSessao($lP->getTabela(), $p->getId());
 $arq = Arquivos::__OpenArquivoByTEMP($_FILES['Filedata']);
 //header("Content-type: image/jpeg");
 $img->setImage(new Image($arq));
 $img->getImage()->open();
 //echo $img->getImage()->getImage();exit;
 if ($rs['produtos']) {
     if ($rs['tipo'] == 1) {
         if (!empty($rs['texto'])) {
             $ma = new NewImage(strlen($rs['texto']) * 9, 20);
             $ma->writeText($rs['texto']);
         }
     } elseif ($rs['tipo'] == 2) {
         if (!empty($rs['imagem'])) {
             $ma = new Image(new Arquivos(Sistema::$caminhoURL . Sistema::$caminhoDataIdiomas . $rs['imagem']));
             $ma->open();
             //echo $ma->getImage();exit;
         }
     }
     if ($ma) {
         if ($rs['posicaohorizontal'] == 1) {
             $x = 0;
         } elseif ($rs['posicaohorizontal'] == 2) {
             $x = $img->getImage()->largura / 2 - $ma->largura / 2;
         } elseif ($rs['posicaohorizontal'] == 3) {
             $x = $img->getImage()->largura - $ma->largura;
         }
         if ($rs['posicaovertical'] == 1) {
             $y = 0;
         } elseif ($rs['posicaovertical'] == 2) {
             $y = $img->getImage()->altura / 2 - $ma->altura / 2;
 /**
  * Returns a path to the specified item, resized and/or cropped to meet max width and height. $obj can either be
  * a string (path) or a file object.
  * Returns an object with the following properties: src, width, height
  *
  * @param File|string $obj
  * @param int $maxWidth
  * @param int $maxHeight
  * @param bool $crop
  * @return \stdClass Object that has the following properties: src, width, height
  */
 public function getThumbnail($obj, $maxWidth, $maxHeight, $crop = false)
 {
     $storage = $this->getStorageLocation();
     $filesystem = $storage->getFileSystemObject();
     $configuration = $storage->getConfigurationObject();
     $fh = \Core::make('helper/file');
     if ($obj instanceof File) {
         try {
             $fr = $obj->getFileResource();
             $fID = $obj->getFileID();
             $filename = md5(implode(':', array($fID, $maxWidth, $maxHeight, $crop, $fr->getTimestamp()))) . '.' . $fh->getExtension($fr->getPath());
         } catch (\Exception $e) {
             $filename = '';
         }
     } else {
         $filename = md5(implode(':', array($obj, $maxWidth, $maxHeight, $crop, filemtime($obj)))) . '.' . $fh->getExtension($obj);
     }
     $abspath = '/cache/' . $filename;
     if (!$filesystem->has($abspath)) {
         if ($obj instanceof File && $fr->exists()) {
             $image = \Image::load($fr->read());
         } else {
             $image = \Image::open($obj);
         }
         // create image there
         $this->create($image, $abspath, $maxWidth, $maxHeight, $crop);
     }
     $src = $configuration->getPublicURLToFile($abspath);
     $thumb = new \stdClass();
     $thumb->src = $src;
     // this is a hack, but we shouldn't go out on the network if we don't have to. We should probably
     // add a method to the configuration to handle this. The file storage locations should be able to handle
     // thumbnails.
     if ($configuration instanceof DefaultConfiguration) {
         $dimensionsPath = $configuration->getRootPath() . $abspath;
     } else {
         $dimensionsPath = $src;
     }
     try {
         //try and get it locally, otherwise use http
         $dimensions = getimagesize($dimensionsPath);
         $thumb->width = $dimensions[0];
         $thumb->height = $dimensions[1];
     } catch (\Exception $e) {
     }
     return $thumb;
 }
Example #21
0
File: main.php Project: vench/esee
<?php

namespace esee;

require_once 'esee/App.php';
App::autoload();
$image = new Image('../x1.jpg');
$image->open();
$diff = 16777215 / 2;
$provider = new provider\ProviderFile('data.txt');
$chainBuilder = new ChainBuilder($image, $diff);
$ar = [];
for ($y = 0; $y < $image->getHeight(); $y++) {
    for ($x = 0; $x < $image->getWidth(); $x++) {
        if ($chainBuilder->getValue($x, $y) == 1) {
            $c = $chainBuilder->makeChain($x, $y);
            if (is_null($c)) {
                continue;
            }
            Helper::view2($c);
            list($ax, $ay) = Helper::avg($c);
            $char = $provider->findByXY($ax, $ay);
            if (!is_null($char)) {
                echo "Find: {$char->char}\n";
                exit;
            } else {
                echo "No find: {$ax}, {$ay}\n";
            }
            array_push($ar, $c);
        }
    }
Example #22
0
 /**
  * ====================================================================
  *  COMBINE MULTIPLE IMAGE FILE(S) INTO A SINGLE IMAGE (SPRITE)
  * ====================================================================
  *
  * -- CODE: -----------------------------------------------------------
  *
  *    Image::take(array(
  *        'icon-1.png',
  *        'icon-2.png',
  *        'icon-3.png'
  *    ))->merge(0, 'vertical')->saveAs('sprites.png');
  *
  * --------------------------------------------------------------------
  *
  */
 public static function merge($gap = 0, $orientation = 'vertical', $bg = false, $alpha_for_hex = 1)
 {
     $bucket = array();
     $width = 0;
     $height = 0;
     $max_width = array();
     $max_height = array();
     $orientation = strtolower($orientation);
     self::$open = (array) self::$open;
     foreach (self::getInfo() as $info) {
         $bucket[] = array('width' => $info['width'], 'height' => $info['height']);
         $max_width[] = $info['width'];
         $max_height[] = $info['height'];
         $width += $info['width'] + $gap;
         $height += $info['height'] + $gap;
     }
     if (!$bg) {
         $bg = array(0, 0, 0, 0);
         // transparent
     }
     if (is_array($bg)) {
         if (count($bg) === 3) {
             $bg[] = 1;
             // missing alpha channel
         }
         list($r, $g, $b, $a) = array_values($bg);
     } else {
         $bg = (string) $bg;
         if ($bg[0] === '#' && ($color = Converter::HEX2RGB($bg))) {
             $r = $color['r'];
             $g = $color['g'];
             $b = $color['b'];
             $a = $alpha_for_hex;
         } else {
             if ($color = Converter::RGB($bg)) {
                 $r = $color['r'];
                 $g = $color['g'];
                 $b = $color['b'];
                 $a = $color['a'];
             }
         }
     }
     $a = 127 - $a * 127;
     if ($orientation[0] === 'v') {
         $pallete = imagecreatetruecolor(max($max_width), $height - $gap);
     } else {
         $pallete = imagecreatetruecolor($width - $gap, max($max_height));
     }
     $bg = imagecolorallocatealpha($pallete, $r, $g, $b, $a);
     imagefill($pallete, 0, 0, $bg);
     imagealphablending($pallete, true);
     imagesavealpha($pallete, true);
     $start_width_from = 0;
     $start_height_from = 0;
     for ($i = 0, $count = count(self::$open); $i < $count; ++$i) {
         self::gen(self::$open[$i]);
         imagealphablending(self::$GD, false);
         imagesavealpha(self::$GD, true);
         imagecopyresampled($pallete, self::$GD, $start_width_from, $start_height_from, 0, 0, $bucket[$i]['width'], $bucket[$i]['height'], $bucket[$i]['width'], $bucket[$i]['height']);
         $start_width_from += $orientation[0] === 'h' ? $bucket[$i]['width'] + $gap : 0;
         $start_height_from += $orientation[0] === 'v' ? $bucket[$i]['height'] + $gap : 0;
     }
     self::twin($pallete, 'png');
     return new static();
 }
Example #23
0
 /**
  * Returns a path to the specified item, resized and/or cropped to meet max width and height. $obj can either be
  * a string (path) or a file object.
  * Returns an object with the following properties: src, width, height
  * @param mixed $obj
  * @param int $maxWidth
  * @param int $maxHeight
  * @param bool $crop
  */
 public function getThumbnail($obj, $maxWidth, $maxHeight, $crop = false)
 {
     $fID = false;
     $fh = Loader::helper('file');
     if ($obj instanceof File) {
         try {
             $fr = $obj->getFileResource();
             $fID = $obj->getFileID();
             $filename = md5(implode(':', array($fID, $maxWidth, $maxHeight, $crop, $fr->getTimestamp()))) . '.' . $fh->getExtension($fr->getPath());
         } catch (\Exception $e) {
             $filename = '';
         }
     } else {
         $filename = md5(implode(':', array($obj, $maxWidth, $maxHeight, $crop, filemtime($obj)))) . '.' . $fh->getExtension($obj);
     }
     if (!file_exists(Config::get('concrete.cache.directory') . '/' . $filename)) {
         if ($obj instanceof File) {
             $image = \Image::load($fr->read());
         } else {
             $image = \Image::open($obj);
         }
         // create image there
         $this->create($image, Config::get('concrete.cache.directory') . '/' . $filename, $maxWidth, $maxHeight, $crop);
     }
     $src = REL_DIR_FILES_CACHE . '/' . $filename;
     $abspath = Config::get('concrete.cache.directory') . '/' . $filename;
     $thumb = new \stdClass();
     if (isset($abspath) && file_exists($abspath)) {
         $thumb->src = $src;
         $dimensions = getimagesize($abspath);
         $thumb->width = $dimensions[0];
         $thumb->height = $dimensions[1];
         return $thumb;
     }
 }
Example #24
0
	function get_thumb ($width = null, $height = null) {
		
		load('Image');
		
		$path = $this->get_real_path();
		
		// Value to append to the thumbnail filename
		$extra = '_t';
		
		// Append width and/or height if size changed
		if ($width) {
			$extra .= '_w' . $width;
		}
		if ($height) {
			$extra .= '_h' . $height;
		}
		
		// Split file path and change file name
		$path_info = pathinfo($path);
		$path_info['filename'] .= $extra;
		
		// Join path together
		$new_path = sprintf('%s/%s.%s', $path_info['dirname'], $path_info['filename'], $path_info['extension']);
		
		// If the thumbnail doesn't exists or the original has been modified
		if (!file_exists($new_path) || (filemtime($path) > filemtime($new_path))) {
			// Create image object
			$i = Image::open($path);
			// Adjust size
			$i->fit($width, $height);
			
			$i->save_as($new_path);
		}
		
		return url(Frix::config('MEDIA_URL'), $this->path, sprintf('%s.%s', $path_info['filename'], $path_info['extension']));
		
	}
Example #25
0
 public function submit()
 {
     $assignment = PermissionKey::getByHandle('edit_user_properties')->getMyAssignment();
     $vals = Loader::helper('validation/strings');
     $valt = Loader::helper('validation/token');
     $valc = Loader::helper('concrete/validation');
     $username = trim($_POST['uName']);
     $username = preg_replace("/\\s+/", " ", $username);
     $_POST['uName'] = $username;
     $password = $_POST['uPassword'];
     if (!$vals->email($_POST['uEmail'])) {
         $this->error->add(t('Invalid email address provided.'));
     } elseif (!$valc->isUniqueEmail($_POST['uEmail'])) {
         $this->error->add(t("The email address '%s' is already in use. Please choose another.", $_POST['uEmail']));
     }
     if (strlen($username) < Config::get('concrete.user.username.minimum')) {
         $this->error->add(t('A username must be at least %s characters long.', Config::get('concrete.user.username.minimum')));
     }
     if (strlen($username) > Config::get('concrete.user.username.maximum')) {
         $this->error->add(t('A username cannot be more than %s characters long.', Config::get('concrete.user.username.maximum')));
     }
     if (strlen($username) >= Config::get('concrete.user.username.minimum') && !$valc->username($username)) {
         if (Config::get('concrete.user.username.allow_spaces')) {
             $this->error->add(t('A username may only contain letters, numbers, spaces (not at the beginning/end), dots (not at the beginning/end), underscores (not at the beginning/end).'));
         } else {
             $this->error->add(t('A username may only contain letters, numbers, dots (not at the beginning/end), underscores (not at the beginning/end).'));
         }
     }
     if (!$valc->isUniqueUsername($username)) {
         $this->error->add(t("The username '%s' already exists. Please choose another", $username));
     }
     if ($username == USER_SUPER) {
         $this->error->add(t('Invalid Username'));
     }
     \Core::make('validator/password')->isValid($password, $this->error);
     if (!$valt->validate('submit')) {
         $this->error->add($valt->getErrorMessage());
     }
     $aks = UserAttributeKey::getRegistrationList();
     foreach ($aks as $uak) {
         $controller = $uak->getController();
         $validator = $controller->getValidator();
         $response = $validator->validateSaveValueRequest($controller, $this->request, $uak->isAttributeKeyRequiredOnRegister());
         /**
          * @var $response ResponseInterface
          */
         if (!$response->isValid()) {
             $error = $response->getErrorObject();
             $this->error->add($error);
         }
     }
     if (!$this->error->has()) {
         // do the registration
         $data = array('uName' => $username, 'uPassword' => $password, 'uEmail' => $_POST['uEmail'], 'uDefaultLanguage' => $_POST['uDefaultLanguage']);
         $uo = UserInfo::add($data);
         if (is_object($uo)) {
             $av = Loader::helper('concrete/avatar');
             if ($assignment->allowEditAvatar()) {
                 if (is_uploaded_file($_FILES['uAvatar']['tmp_name'])) {
                     $image = \Image::open($_FILES['uAvatar']['tmp_name']);
                     $image = $image->thumbnail(new Box(Config::get('concrete.icons.user_avatar.width'), Config::get('concrete.icons.user_avatar.height')));
                     $uo->updateUserAvatar($image);
                 }
             }
             $saveAttributes = array();
             foreach ($aks as $uak) {
                 if (in_array($uak->getAttributeKeyID(), $assignment->getAttributesAllowedArray())) {
                     $saveAttributes[] = $uak;
                 }
             }
             if (count($saveAttributes) > 0) {
                 $uo->saveUserAttributesForm($saveAttributes);
             }
             $gIDs = array();
             if (is_array($_POST['gID'])) {
                 foreach ($_POST['gID'] as $gID) {
                     $gx = Group::getByID($gID);
                     $gxp = new Permissions($gx);
                     if ($gxp->canAssignGroup()) {
                         $gIDs[] = $gID;
                     }
                 }
             }
             $uo->updateGroups($gIDs);
             $uID = $uo->getUserID();
             $this->redirect('/dashboard/users/search', 'view', $uID, 'created');
         } else {
             $this->error->add(t('An error occurred while trying to create the account.'));
             $this->set('error', $this->error);
         }
     } else {
         $this->view();
     }
 }
 */
require_once __DIR__ . '/vendor/autoload.php';
use Gregwar\Image\Image as GregwarImage;
// Usage in templates:
// {Image::open('themes/default/assets/img/fansoro-logo.png')->resize(100, 100)->png()}
class image extends GregwarImage
{
}
// Shortcode:
// {Image open="themes/default/assets/img/fansoro-logo.png"}
Shortcode::add('Image', function ($attributes) {
    // Extract attributes
    extract($attributes);
    // Open Image
    if (isset($open)) {
        $file = Image::open($open);
        // Resize Image
        if (isset($width) && isset($height)) {
            if (isset($resize_method) && in_array($resize_method, $resize_methods = ['scale', 'force', 'crop', 'zoom'])) {
                switch ($resize_method) {
                    case 'scale':
                        $file->scaleResize($width, $height, isset($background) ? $background : 0xffffff);
                        break;
                    case 'force':
                        $file->forceResize($width, $height, isset($background) ? $background : 0xffffff);
                        break;
                    case 'crop':
                        $file->cropResize($width, $height, isset($background) ? $background : 0xffffff);
                        break;
                    case 'zoom':
                        $file->zoomCrop($width, $height, isset($background) ? $background : 0xffffff, isset($xPos) ? $xPos : 0, isset($yPos) ? $yPos : 0);
 public function postUpload()
 {
     $file = Input::file('file');
     if (!Session::has('hash')) {
         $hash = str_random(8);
         Session::put('hash', $hash);
     } else {
         $hash = Session::get('hash');
     }
     $destinationPath = 'uploads/' . $hash;
     $extension = $file->getClientOriginalExtension();
     $filename = 'original.' . $extension;
     Session::put('filename', $filename);
     $upload_success = Input::file('file')->move($destinationPath, $filename);
     if ($upload_success) {
         Image::open($destinationPath . '/' . $filename)->resize(null, 600, true)->save($destinationPath . '/' . $filename);
         return Response::json(array('files' => array('name' => url($destinationPath . '/' . $filename . '?' . time()))), 200);
     } else {
         return Response::json('error', 400);
     }
 }
Example #28
0
File: demo.php Project: lyb411/util
<?php

include './Image.php';
echo '<pre>';
$img = '/tmp/20151005/5613e8ca1832d87cb24a35a89b178fca.jpg';
$image = new Image(Image::IMAGE_GD);
//GD库处理
$image->open($img);
/******************************获取图像信息**********************************************************************************************/
$width = $image->width();
// 返回图片的宽度
$height = $image->height();
// 返回图片的高度
$type = $image->type();
// 返回图片的类型
$mime = $image->mime();
// 返回图片的mime类型
$size = $image->size();
// 返回图片的尺寸数组 0 图片宽度 1 图片高度
/******************************生成缩略图,按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg******************************************/
//$image->thumb(150, 150)->save('/tmp/20151005/thumb.jpg');//我们看到实际生成的缩略图并不是150*150,因为默认采用原图等比例缩放的方式生成缩略图,最大宽度是150。
/* IMAGE_THUMB_SCALE     =   1 ; //等比例缩放类型(默认)
 IMAGE_THUMB_FILLED    =   2 ; //缩放后填充类型
IMAGE_THUMB_CENTER    =   3 ; //居中裁剪类型
IMAGE_THUMB_NORTHWEST =   4 ; //左上角裁剪类型
IMAGE_THUMB_SOUTHEAST =   5 ; //右下角裁剪类型
IMAGE_THUMB_FIXED     =   6 ; //固定尺寸缩放类型 */
/******************************添加图片水印*************************************************************************************************/
/* $image->crop(440, 440)->save('/tmp/20151005/crop.jpg');//将图片裁剪为440x440并保存为corp.jpg
$image->water('/tmp/20151005/logo.png')->save("/tmp/20151005/water.gif");// 给裁剪后的图片添加图片水印(水印文件位于./logo.png),位置为右下角,保存为water.gif
 /**
  * Generate an album image from a Last.fm URL
  *
  * @param string $url   URL of Last.fm album image
  * @param mixed  $error Error message string
  * 
  * @return  mixed
  */
 public function generateImage($url, $error = false)
 {
     $this->filenameSansPath = $this->username . '_' . $this->number . '_' . $this->result['playcount'] . '_' . md5($this->result['name']) . '.png';
     $this->filename = public_path() . '/' . $this->filenameSansPath;
     if (Cache::has($this->filename)) {
         if (file_exists($this->filename)) {
             Log::info('Loaded cached object', ['file' => $this->filenameSansPath]);
             $image = Image::open($this->filename);
             return $image->encode($this->filename, 90);
         }
     }
     if ($error) {
         // Normally, you'd only come down this path if the function was called by something else forcing an error
         Log::error('There was an error, generate the error image');
         // We had an error, we're a sad panda
         $image = Image::make(public_path() . '/resources/sadpanda.png');
     } else {
         // Pull image from Last.fm and create the Image instance
         try {
             $image = Image::make($url);
         } catch (Exception $e) {
             Log::error('Image path is invalid', ['message' => 'Error: ' . $e->getMessage(), 'url' => $url, 'code' => $e->getCode()]);
             // Go back and generate the error image
             return $this->generateImage(false, 'Unable to locate image');
         }
         // Resize image to 300x300 px, just in case the image is too large/small
         $image->resize(300, 300);
     }
     // Expand image up 36px with the background color with white
     $image->resizeCanvas(0, 36, 'bottom', true, $this->text['colours']['white']);
     // Larger rectangle that forms the border
     $image->rectangle($this->text['colours']['border'], 0, 0, 299, 24, false);
     // Smaller rectangle with the background
     $image->rectangle($this->text['colours']['background'], 1, 1, 298, 23);
     if ($error) {
         $image->text('Error: ' . $error, 7, 17, $this->text['size'], $this->text['colours']['black'], 0, $this->text['fonts']['bold']);
     } else {
         $x = 0;
         // 1. or 2. (etc)
         $image->text($this->number . '.', $x += 7, 17, $this->text['size'], $this->text['colours']['black'], 0, $this->text['fonts']['bold']);
         $bbox = imagettfbbox($this->text['size'], 0, $this->text['fonts']['bold'], $this->number . '.');
         // Artist Name
         $image->text($this->result['artist']['name'], $x += $bbox[2] += 4, 17, $this->text['size'], $this->text['colours']['link'], 0, $this->text['fonts']['normal']);
         $bbox = imagettfbbox($this->text['size'], 0, $this->text['fonts']['normal'], $this->result['artist']['name']);
         // Chuck in a dash
         $image->text('-', $x += $bbox[2] += 6, 17, $this->text['size'], $this->text['colours']['black'], 0, $this->text['fonts']['normal']);
         $bbox = imagettfbbox($this->text['size'], 0, $this->text['fonts']['normal'], '-');
         // And the Album Title
         $image->text($this->result['name'], $x += $bbox[2] += 4, 17, $this->text['size'], $this->text['colours']['link'], 0, $this->text['fonts']['bold']);
         $bbox = imagettfbbox($this->text['size'], 0, $this->text['fonts']['bold'], $this->result['name']);
         // And the Playcount in brackets
         $image->text('(' . $this->result['playcount'] . ')', $x += $bbox[2] + 4, 17, $this->text['size'], $this->text['colours']['black'], 0, $this->text['fonts']['normal']);
         // And we're done making the image
     }
     // Save the image as a .png with a quality of 90
     $image->save($this->filename);
     // I don't want to optimise the error message images
     if (!$error) {
         Log::info('Finished generating image non-optimised image');
         if (Cache::forever($this->filename, true)) {
             Log::info('Added ' . $this->filenameSansPath . ' to cache');
         }
         // Get a random number of seconds between 10 and 99 for the queue - I don't really want to
         // start generating smaller images straight away
         $seconds = mt_rand(10, 99);
         Log::info('Sent image to optimiser queue, starting in ' . $seconds . ' seconds');
         // Send the image to the optimiser for the next requests...
         Queue::later($seconds, 'LastfmController@optimiseImage', ['image' => $this->filename, 'level' => 2]);
     }
     return $image;
 }
Example #30
0
 private static function resizeImage($extend, $filepath)
 {
     // resize image
     if (isset($extend->attributes->size->width) and isset($extend->attributes->size->height)) {
         $image = Image::open($filepath);
         $width = intval($extend->attributes->size->width);
         $height = intval($extend->attributes->size->height);
         // resize larger images
         if ($width and $height and ($image->width() > $width or $image->height() > $height)) {
             $image->resize($width, $height);
             $image->output($ext, $filepath);
         }
     }
 }