/** * {@inheritdoc} */ public function getFormat() { $format = $this->imagick->getImageFormat(); if (!in_array($format, static::$supportedFormats)) { throw new RuntimeException('Unsupported image format'); } return $format; }
/** * Updates size properties * * @param int $width Image width * @param int $height Image height * @param bool $get_format Whether to get image format */ protected function update_size($width, $height, $get_format = false) { $this->width = $width; $this->height = $height; if ($get_format) { $this->format = strtolower($this->image->getImageFormat()); if ($this->format == 'jpg') { $this->format = 'jpeg'; } } }
/** * 打开一张图像 * @param string $imgname 图像路径 * @throws \Exception */ public function open($imgname) { //检测图像文件 if (!is_file($imgname)) { throw new \Exception(_('The image file does not exist')); } //销毁已存在的图像 empty($this->img) || $this->img->destroy(); //载入图像 $this->img = new \Imagick(realpath($imgname)); //设置图像信息 $this->info = array('width' => $this->img->getImageWidth(), 'height' => $this->img->getImageHeight(), 'type' => strtolower($this->img->getImageFormat()), 'mime' => $this->img->getImageMimeType()); }
function load($file_name, $type = '') { $this->destroyImage(); $imginfo = @getimagesize($file_name); if (!$imginfo) { throw new lmbFileNotFoundException($file_name); } $this->img = new Imagick(); $this->img->readImage($file_name); if (!$this->img instanceof Imagick) { throw new lmbImageCreateFailedException($file_name); } $this->img_type = $this->img->getImageFormat(); }
/** * @param $width * @param $height * @return Imagick */ protected function createImage($width, $height, $color = "transparent") { $newImage = new \Imagick(); $newImage->newimage($width, $height, $color); $newImage->setImageFormat($this->resource->getImageFormat()); return $newImage; }
public function makeThumb($path, $W = NULL, $H = NULL) { $image = new Imagick(); $image->readImage($ImgSrc); // Trasformo in RGB solo se e` il CMYK if ($image->getImageColorspace() == Imagick::COLORSPACE_CMYK) { $image->transformImageColorspace(Imagick::COLORSPACE_RGB); } $image->profileImage('*', NULL); $image->stripImage(); $imgWidth = $image->getImageWidth(); $imgHeight = $image->getImageHeight(); if ((!$H || $H == null || $H == 0) && (!$W || $W == null || $W == 0)) { $W = $imgWidth; $H = $imgHeight; } elseif (!$H || $H == null || $H == 0) { $H = $W * $imgHeight / $imgWidth; } elseif (!$W || $W == null || $W == 0) { $W = $H * $imgWidth / $imgHeight; } $image->resizeImage($W, $H, Imagick::FILTER_LANCZOS, 1); /** Scrivo l'immagine */ $image->writeImage($path); /** IMAGE OUT */ header('X-MHZ-FLY: Nice job!'); header(sprintf('Content-type: image/%s', strtolower($image->getImageFormat()))); echo $image->getImageBlob(); $image->destroy(); die; }
/** * * @param Imagick $image * @param string $filename * @param string $mime_type * @return array|WP_Error */ protected function _save( $image, $filename = null, $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); if ( ! $filename ) $filename = $this->generate_filename( null, null, $extension ); try { // Store initial Format $orig_format = $this->image->getImageFormat(); $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) ); $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) ); // Reset original Format $this->image->setImageFormat( $orig_format ); } catch ( Exception $e ) { return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); } // Set correct file permissions $stat = stat( dirname( $filename ) ); $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits @ chmod( $filename, $perms ); /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ return array( 'path' => $filename, 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 'width' => $this->size['width'], 'height' => $this->size['height'], 'mime-type' => $mime_type, ); }
/** * @param $file * @return string */ public function thumbnail($file) { $format = ''; $name = md5((new \DateTime())->format('c')); foreach ($this->sizes as $size) { $image = new \Imagick($file); $imageRatio = $image->getImageWidth() / $image->getImageHeight(); $width = $size['width']; $height = $size['height']; $customRation = $width / $height; if ($customRation < $imageRatio) { $widthThumb = 0; $heightThumb = $height; } else { $widthThumb = $width; $heightThumb = 0; } $image->thumbnailImage($widthThumb, $heightThumb); $image->cropImage($width, $height, ($image->getImageWidth() - $width) / 2, ($image->getImageHeight() - $height) / 2); $image->setCompressionQuality(100); $format = strtolower($image->getImageFormat()); $pp = $this->cachePath . '/' . $size['name'] . "_{$name}." . $format; $image->writeImage($pp); } return "_{$name}." . $format; }
private function watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo) { try { // Open the original image $img = new Imagick($src); // Open the watermark $watermark = new Imagick($watermark); // Set transparency if (strtoupper($watermark->getImageFormat()) !== 'PNG') { $watermark->setImageOpacity($transparency / 100); } // Overlay the watermark on the original image $img->compositeImage($watermark, imagick::COMPOSITE_OVER, $dest_x, $dest_y); // Set quality if (strtoupper($img->getImageFormat()) === 'JPEG') { $img->setImageCompression(imagick::COMPRESSION_JPEG); $img->setCompressionQuality($quality); } $result = $img->writeImage($src); $img->clear(); $img->destroy(); $watermark->clear(); $watermark->destroy(); return $result ? true : false; } catch (Exception $e) { return false; } }
public function run() { $faker = Faker::create(); $imgDir = public_path() . DS . 'assets' . DS . 'upload' . DS . 'images'; if (!File::exists($imgDir)) { File::makeDirectory($imgDir, 0755); } File::cleanDirectory($imgDir, true); foreach (range(1, 500) as $index) { $dir = $imgDir . DS . $index; if (!File::exists($dir)) { File::makeDirectory($dir, 0755); } $width = $faker->numberBetween(800, 1024); $height = $faker->numberBetween(800, 1024); $orgImg = $faker->image($dir, $width, $height); chmod($orgImg, 0755); $img = str_replace($dir . DS, '', $orgImg); $image = new Imagick($orgImg); $dpi = $image->getImageResolution(); $dpi = $dpi['x'] > $dpi['y'] ? $dpi['x'] : $dpi['y']; $size = $image->getImageLength(); $extension = strtolower($image->getImageFormat()); //get 5 most used colors from the image $color_extractor = new ColorExtractor(); $myfile = $orgImg; $mime_type = $image->getImageMimeType(); switch ($mime_type) { case 'image/jpeg': $palette_obj = $color_extractor->loadJpeg($myfile); break; case 'image/png': $palette_obj = $color_extractor->loadPng($myfile); break; case 'image/gif': $palette_obj = $color_extractor->loadGif($myfile); break; } $main_color = ''; if (is_object($palette_obj)) { $arr_palette = $palette_obj->extract(5); if (!empty($arr_palette)) { $main_color = strtolower($arr_palette[0]); for ($i = 1; $i < count($arr_palette); $i++) { $main_color .= ',' . strtolower($arr_palette[$i]); } } } //update field main_color from images table $image_obj = VIImage::findorFail((int) $index); $image_obj->main_color = $main_color; $image_obj->save(); $id = VIImageDetail::insertGetId(['path' => 'assets/upload/images/' . $index . '/' . $img, 'height' => $height, 'width' => $width, 'ratio' => $width / $height, 'dpi' => $dpi, 'size' => $size, 'extension' => $extension, 'type' => 'main', 'image_id' => $index]); BackgroundProcess::makeSize($id); } }
/** * @param \Imagick $image * @param string $format * @return \Imagick */ private function setImageFormat($image, $format) { if ($image->getImageFormat() !== $format) { $image->setImageFormat($format); } if ($format == 'jpeg') { $image->setImageCompressionQuality(90); } return $image; }
private function inscribeImageIntoCanvas(\Imagick $image) : \Imagick { $dimensions = $image->getImageGeometry(); $x = (int) round(($this->width - $dimensions['width']) / 2); $y = (int) round(($this->height - $dimensions['height']) / 2); $canvas = new \Imagick(); $canvas->newImage($this->width, $this->height, $this->backgroundColor, $image->getImageFormat()); $canvas->compositeImage($image, \Imagick::COMPOSITE_OVER, $x, $y); return $canvas; }
/** * Generates and dies with an image containing the heading and the text of the error. * * @param string $headingText The heading of the error. * @param string $errorText The text of the error. */ public function generate($headingText, $errorText) { $draw = new ImagickDraw(); $draw->setFillColor('#777777'); $draw->setFontSize(15); $draw->setFont('fonts/exo2bold.ttf'); $headingMetrics = $this->canvas->queryFontMetrics($draw, $headingText); $draw->setFont('fonts/exo2regular.ttf'); $textMetrics = $this->canvas->queryFontMetrics($draw, $errorText); $this->canvas->newImage(max($textMetrics['textWidth'], $headingMetrics['textWidth']) + 6, $textMetrics['textHeight'] + $headingMetrics['textHeight'] + 6, new ImagickPixel('white')); $this->canvas->annotateImage($draw, 3, $headingMetrics['textHeight'] * 2, 0, $errorText); $draw->setFont('fonts/exo2bold.ttf'); $draw->setFillColor('#333333'); $draw->setGravity(Imagick::GRAVITY_NORTH); $this->canvas->annotateImage($draw, 3, 3, 0, $headingText); $this->canvas->setImageFormat('png'); header('Content-Type: image/' . $this->canvas->getImageFormat()); header("Cache-Control: max-age=60"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60) . " GMT"); die($this->canvas); }
/** * @return int * @throws CM_Exception_Invalid */ public function getFormat() { $imagickFormat = $this->_imagick->getImageFormat(); switch ($imagickFormat) { case 'JPEG': return self::FORMAT_JPEG; case 'GIF': return self::FORMAT_GIF; case 'PNG': return self::FORMAT_PNG; default: throw new CM_Exception_Invalid('Unsupported format `' . $imagickFormat . '`.'); } }
/** * 复制图片 * @param string $dir * @param string $fileName * @return mixed */ public function copy($dir = '', $fileName = '') { /** * two ways * $this->image->writeImage($path); * file_put_contents($path, $this->image); */ $fileName = $fileName ? $fileName : $this->genFileName(); $format = strtolower($this->image->getImageFormat()); $fileName = $fileName . '.' . $format; $dir = rtrim($dir, '/') . '/'; $realFileName = $dir . $fileName; //origin file_put_contents /* $blobData = $this->image->getImageBlob(); $result = file_put_contents($realFileName,$blobData); */ //writeImage $result = $this->image->writeImage($realFileName); $storage['fileName'] = $fileName; $storage['flag'] = $result ? true : false; return $storage; }
/** * @see \wcf\system\image\adapter\IImageAdapter::overlayImage() */ public function overlayImage($file, $x, $y, $opacity) { try { $overlayImage = new \Imagick($file); } catch (\ImagickException $e) { throw new SystemException("Image '" . $file . "' is not readable or does not exist."); } $overlayImage->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity, \Imagick::CHANNEL_OPACITY); if ($this->imagick->getImageFormat() == 'GIF') { $this->imagick = $this->imagick->coalesceImages(); do { $this->imagick->compositeImage($overlayImage, \Imagick::COMPOSITE_OVER, $x, $y); } while ($this->imagick->nextImage()); } else { $this->imagick->compositeImage($overlayImage, \Imagick::COMPOSITE_OVER, $x, $y); $this->imagick = $this->imagick->flattenImages(); } }
/** * Output an image to buffer or return as string * * @param string $type Image format * @param boolean $buffer Output or return? * @return mixed * @throws Engine_Image_Adapter_Exception If unable to output */ public function output($type = 'jpeg', $buffer = false) { $this->_checkOpenImage(); // Set file type if ($type == 'jpg') { $type = 'jpeg'; } $type = strtoupper($type); if ($type !== $this->_resource->getImageFormat()) { $this->_resource->setImageFormat($type); } // Set quality if (null !== $this->_quality) { $this->_resource->setImageCompressionQuality($this->_quality); } // Output if ($buffer) { return (string) $this->_resource; } else { echo $this->_resource; } return $this; }
private function make_thumbnail_Imagick($src_path, $width, $height, $dest) { $image = new Imagick($src_path); # Select the first frame to handle animated images properly if (is_callable(array($image, 'setIteratorIndex'))) { $image->setIteratorIndex(0); } // устанавливаем качество $format = $image->getImageFormat(); if ($format == 'JPEG' || $format == 'JPG') { $image->setImageCompression(Imagick::COMPRESSION_JPEG); } $image->setImageCompressionQuality(85); $h = $image->getImageHeight(); $w = $image->getImageWidth(); // если не указана одна из сторон задаем ей пропорциональное значение if (!$width) { $width = round($w * ($height / $h)); } if (!$height) { $height = round($h * ($width / $w)); } list($dx, $dy, $wsrc, $hsrc) = $this->crop_coordinates($height, $h, $width, $w); // обрезаем оригинал $image->cropImage($wsrc, $hsrc, $dx, $dy); $image->setImagePage($wsrc, $hsrc, 0, 0); // Strip out unneeded meta data $image->stripImage(); // уменьшаем под размер $image->scaleImage($width, $height); $image->writeImage($dest); chmod($dest, 0755); $image->clear(); $image->destroy(); return true; }
/** * * @param unknown $file * @throws ImageModifierException */ public function __construct($file) { if (!file_exists($file)) { throw new ImageModifierException("File '{$file}' doesn't exist."); } try { $img = new \Imagick($file); } catch (\ImagickException $e) { throw new ImageModifierException("Imagick reports error for file {$file}."); } $this->file = $file; $this->mimeType = 'image/' . strtolower($img->getImageFormat()); $this->srcWidth = $img->getImageWidth(); $this->srcHeight = $img->getImageHeight(); if (!preg_match('#^image/(?:' . implode('|', $this->supportedFormats) . ')$#', $this->mimeType)) { throw new ImageModifierException("File {$file} is not of type '" . implode("', '", $this->supportedFormats) . "'."); } $src = new \stdClass(); $src->resource = $img; $src->width = $this->srcWidth; $src->height = $this->srcHeight; $this->src = $src; $this->queue = array(); }
private function thumbnail_file_with_imagick($file_path, $save_as, $w = 0, $h = 0) { try { $real_save_as = $save_as; $save_as = tempnam(PERCH_RESFILEPATH, '_im_tmp_'); $Image = new Imagick($file_path . '[0]'); $Image->setImageFormat('jpg'); if ($Image->getImageHeight() <= $Image->getImageWidth()) { $Image->thumbnailImage($w * $this->density, 0); } else { $Image->thumbnailImage(0, $w * $this->density); } // progressive jpg? if ($this->progressive_jpeg) { $Image->setInterlaceScheme(Imagick::INTERLACE_PLANE); } $Image->writeImage($save_as); copy($save_as, $real_save_as); unlink($save_as); $save_as = $real_save_as; $out = array(); $out['w'] = (int) $Image->getImageWidth() / $this->density; $out['h'] = (int) $Image->getImageHeight() / $this->density; $out['file_path'] = $save_as; $parts = explode(DIRECTORY_SEPARATOR, $save_as); $out['file_name'] = array_pop($parts); $out['web_path'] = str_replace(PERCH_RESFILEPATH . DIRECTORY_SEPARATOR, PERCH_RESPATH . '/', $save_as); $out['density'] = $this->density; $out['mime'] = 'image/' . $Image->getImageFormat(); $Image->destroy(); return $out; } catch (Exception $e) { PerchUtil::debug('Unable to create thumbnail', 'error'); PerchUtil::debug($e, 'error'); } return false; }
<?php $app->get('/image/:filename/:width(/:height)', function ($filename, $width, $height = 0) use($app) { if ($width > 450 || $height > 450) { $app->halt(403, 'Request forbidden due to invalid image dimensions.'); } $img = new Imagick("/var/www/portal.pathtoarabic.com/public/img/{$filename}"); $img->resizeImage($width, $height, imagick::FILTER_LANCZOS, 0.9); $app->contentType('image/' . $img->getImageFormat()); echo $img; }); $app->get('/', function () use($app, $user) { $app->redirect('/home'); }); $app->get('/login', function () use($app, $user) { if ($user->isLoggedIn()) { $app->redirect('/home'); } # FIXME: nonce handling is broken because user id cannot be known in advance. What's the solution? $app->render('login.twig', ['loginurl' => \PTA\App::getLoginURL(), 'nonce' => $user->createNonce($_SERVER['REMOTE_ADDR'], 'login', 0)]); }); $app->get('/welcome', function () use($app, $user) { #if ($user->hasCompletedSurvey()) # $app->redirect('/home'); #} $app->render('welcome.twig', ['pjax' => array_key_exists('X-PJAX', getallheaders()), 'name' => $user->getName()]); }); $app->get('/survey', function () use($app, $user) { $productType = $user->getProductType(); if ($user->hasCompletedSurvey()) { $app->redirect('/home');
public function updateImage() { if (!Request::ajax()) { return App::abort(404); } $arrReturn = ['status' => 'error']; $id = Input::has('id') ? Input::get('id') : 0; if ($id) { $create = false; try { $image = VIImage::findorFail((int) Input::get('id')); } catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) { return App::abort(404); } $message = 'has been updated successful'; } else { $create = true; $image = new VIImage(); $message = 'has been created successful'; } if ($create && !Input::hasFile('image')) { return ['status' => 'error', 'message' => 'You need to upload at least 1 image.']; } $image->name = Input::get('name'); $image->short_name = Str::slug($image->name); $image->description = Input::get('description'); $image->keywords = Input::get('keywords'); $image->keywords = rtrim(trim($image->keywords), ','); $image->model = Input::get('model'); $image->model = rtrim(trim($image->model), ','); $image->artist = Input::get('artist'); $image->age_from = Input::get('age_from'); $image->age_to = Input::get('age_to'); $image->gender = Input::get('gender'); $image->number_people = Input::get('number_people'); $pass = $image->valid(); if ($pass->passes()) { if (Input::hasFile('image')) { $color_extractor = new ColorExtractor(); $myfile = Input::file('image'); $mime_type = $myfile->getClientMimeType(); switch ($mime_type) { case 'image/jpeg': $palette_obj = $color_extractor->loadJpeg($myfile); break; case 'image/png': $palette_obj = $color_extractor->loadPng($myfile); break; case 'image/gif': $palette_obj = $color_extractor->loadGif($myfile); break; } $main_color = ''; if (is_object($palette_obj)) { $arr_palette = $palette_obj->extract(5); if (!empty($arr_palette)) { $main_color = strtolower($arr_palette[0]); for ($i = 1; $i < count($arr_palette); $i++) { $main_color .= ',' . strtolower($arr_palette[$i]); } } } $image->main_color = $main_color; } $image->save(); //insert into statistic_images table if ($create) { StatisticImage::create(['image_id' => $image->id, 'view' => '0', 'download' => '0']); } foreach (['category_id' => 'categories', 'collection_id' => 'collections'] as $key => $value) { $arrOld = $remove = $add = []; $old = $image->{$value}; $data = Input::has($key) ? Input::get($key) : []; $data = (array) json_decode($data[0]); if (!empty($old)) { foreach ($old as $val) { if (!in_array($val->id, $data)) { $remove[] = $val->id; } else { $arrOld[] = $val->id; } } } foreach ($data as $id) { if (!$id) { continue; } if (!in_array($id, $arrOld)) { $add[] = $id; } } if (!empty($remove)) { $image->{$value}()->detach($remove); } if (!empty($add)) { $image->{$value}()->attach($add); } foreach ($add as $v) { $arrOld[] = $v; } $image->{'arr' . ucfirst($value)} = $arrOld; } $path = public_path('assets' . DS . 'upload' . DS . 'images' . DS . $image->id); if ($create) { $main = new VIImageDetail(); $main->image_id = $image->id; $main->type = 'main'; File::makeDirectory($path, 0755, true); } else { $main = VIImageDetail::where('type', 'main')->where('image_id', $image->id)->first(); File::delete(public_path($main->path)); } if (Input::hasFile('image')) { $file = Input::file('image'); $name = $image->short_name . '.' . $file->getClientOriginalExtension(); $file->move($path, $name); $imageChange = true; } else { if (Input::has('choose_image') && Input::has('choose_name')) { $chooseImage = Input::get('choose_image'); $name = Input::get('choose_name'); file_put_contents($path . DS . $name, file_get_contents($chooseImage)); $imageChange = true; } } if (isset($imageChange)) { $main->path = 'assets/upload/images/' . $image->id . '/' . $name; $img = Image::make($path . DS . $name); $main->width = $img->width(); $main->height = $img->height(); $main->ratio = $main->width / $main->height; $img = new Imagick($path . DS . $name); $dpi = $img->getImageResolution(); $main->dpi = $dpi['x'] > $dpi['y'] ? $dpi['x'] : $dpi['y']; $main->size = $img->getImageLength(); $main->extension = strtolower($img->getImageFormat()); $main->save(); BackgroundProcess::makeSize($main->detail_id); $image->changeImg = true; if ($create) { $image->dimension = $main->width . 'x' . $main->height; $image->newImg = true; $image->path = URL . '/pic/large-thumb/' . $image->short_name . '-' . $image->id . '.jpg'; } } $arrReturn['status'] = 'ok'; $arrReturn['message'] = "{$image->name} {$message}."; $arrReturn['data'] = $image; return $arrReturn; } $arrReturn['message'] = ''; $arrErr = $pass->messages()->all(); foreach ($arrErr as $value) { $arrReturn['message'] .= "{$value}\n"; } return $arrReturn; }
function upload_image($file_array, $slug, $small_width = 350) { // upload troubleshooting // echo "Upload: " . $file_array["name"] . "<br>"; // echo "Type: " . $file_array["type"] . "<br>"; // echo "Size: " . ($file_array["size"] / 1024) . " kB<br>"; // echo "Stored in: " . $file_array["tmp_name"]; // check if image was uploaded if (empty($file_array)) { return false; } // check for error if ($file_array["error"] > 0) { echo "Error: " . $file_array["error"]; return false; } // check if the file has a size. if (!getimagesize($file_array['tmp_name'])) { echo "Error: image has no data."; return false; } $image_name = $file_array["name"]; // check if name contains php $pos = strpos($image_name, '.php'); if (!($pos === false)) { echo "Error: File name cannot contain '.php'."; return false; } $ext = strtolower('.' . end(explode(".", $image_name))); //check if extension is allowed or not $whitelist = array(".jpg", ".jpeg", ".gif", ".png"); if (!in_array($ext, $whitelist)) { echo "Error: Not jpg, jpeg, gif or png."; return false; } $filetype = $file_array['type']; $filetype = strtolower($filetype); // double check that it is an image $pos = strpos($filetype, 'image'); if ($pos === false) { echo "Error: Filetype says not an image."; return false; } // again make sure the mime type is an image $imageinfo = getimagesize($file_array['tmp_name']); if ($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/jpg' && $imageinfo['mime'] != 'image/png') { echo "Error: MIME type says not an image."; return false; } // check for double file type (image with comment) if (substr_count($filetype, '/') > 1) { echo "Error: Double file type."; return false; } $image_name = $slug . $ext; if (move_uploaded_file($file_array['tmp_name'], "../uploaded_images/" . $image_name)) { $pic = "http://codame.com/uploaded_images/{$image_name}"; $small_pic = str_replace($ext, '-small' . $ext, $image_name); $small_pic_path = '../uploaded_images/' . $small_pic; // generate small version $img = new Imagick($pic); $format = $img->getImageFormat(); if ($format == 'GIF') { // gifs are not resized. Instead for consistency a copy of the gif is appended with -small. try { copy('../uploaded_images/' . $image_name, $small_pic_path); } catch (Exception $e) { echo 'Error: Couldnt copy gif. Exception: ', $e->getMessage(), "n"; return false; } } else { try { $img->thumbnailImage($small_width, 0); $img->writeImage($small_pic_path); } catch (Exception $e) { echo 'Error: Couldnt resize image. Exception: ', $e->getMessage(), "n"; return false; } } return $pic; } else { echo "Error: A problem occurred when moving the file to the uploads folder."; } }
/** * ImageMagick based image properties read. */ private function identify() { $rcube = rcube::get_instance(); // use ImageMagick in command line if ($cmd = $rcube->config->get('im_identify_path')) { $args = array('in' => $this->image_file, 'format' => "%m %[fx:w] %[fx:h]"); $id = rcube::exec($cmd . ' 2>/dev/null -format {format} {in}', $args); if ($id) { return explode(' ', strtolower($id)); } } // use PHP's Imagick class if (class_exists('Imagick', false)) { try { $image = new Imagick($this->image_file); return array(strtolower($image->getImageFormat()), $image->getImageWidth(), $image->getImageHeight()); } catch (Exception $e) { } } }
public function createThumb($key, $sw = 0, $sh = 0) { if (array_key_exists($key, $_FILES) && $_FILES[$key]['size']) { try { // イメージ読み込み $image = new Imagick(); $image->readImageBlob(file_get_contents($_FILES[$key]['tmp_name'])); $iw = $image->getImageWidth(); $ih = $image->getImageHeight(); $uniqid = uniqid('', true); if ($image->getImageFormat() == 'JPEG') { $format = 'jpg'; } elseif ($image->getImageFormat() == 'PNG') { $format = 'png'; } elseif ($image->getImageFormat() == 'GIF') { $format = 'gif'; } else { return null; } $path_t = APPLICATION_PATH . "/images/thumbnail/" . $uniqid . '.s.' . $format; $url_t = $this->view->app->base_url . "/images/thumbnail/" . $uniqid . '.s.' . $format; // リサイズなし if ($sw == $iw && $sh == $ih) { // ファイル書き込み $fh = fopen($path_t, 'wb'); fwrite($fh, $image->getImagesBlob()); fclose($fh); } elseif ($sw / $iw > $sh / $ih) { $ww = intval($iw * $sh / $ih); $hh = intval($ih * $sw / $iw); $image->scaleImage($sw, $hh); // 重ね合わせ $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, 0, intval(($sh - $hh) / 2)); $im2->setImageFormat($format); // ファイル書き込み $fh = fopen($path_t, 'wb'); fwrite($fh, $im2->getImagesBlob()); fclose($fh); } else { $ww = intval($iw * $sh / $ih); $hh = intval($ih * $sw / $iw); $image->scaleImage($ww, $sh); // 重ね合わせ $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, intval(($sw - $ww) / 2), 0); $im2->setImageFormat($format); // ファイル書き込み $fh = fopen($path_t, 'wb'); fwrite($fh, $im2->getImagesBlob()); fclose($fh); } return array('thumb_url' => $url_t); } catch (Exception $e) { return null; } } else { return null; } }
/** * @final * @global array $motopressCESettings * @global MPCERequirements $motopressCERequirements * @global stdClass $motopressCELang * @param string $icon * @param string $iconDir */ protected final function icon($icon, $iconDir) { global $motopressCESettings; global $motopressCERequirements; global $motopressCELang; if (is_string($icon)) { $icon = trim($icon); if (!empty($icon)) { $icon = filter_var($icon, FILTER_SANITIZE_STRING); if (dirname($icon) === '.') { $iconPath = $motopressCESettings['plugin_root'] . '/' . $motopressCESettings['plugin_name'] . '/images/ce/' . $iconDir . '/' . $icon; $iconUrl = $motopressCESettings['plugin_root_url'] . '/' . $motopressCESettings['plugin_name'] . '/images/ce/' . $iconDir . '/' . $icon; } else { $iconPath = WP_CONTENT_DIR . '/' . $icon; $iconUrl = WP_CONTENT_URL . '/' . $icon; } $iconUrl .= '?ver=' . $motopressCESettings['plugin_version']; if (file_exists($iconPath)) { $mimeType = null; if ($motopressCERequirements->getGd()) { $info = getimagesize($iconPath); if ($info) { $mimeType = $info['mime']; } } if (is_null($mimeType) && $motopressCERequirements->getFileinfo() && version_compare(PHP_VERSION, '5.3.0', '>=')) { $finfo = new finfo(FILEINFO_MIME_TYPE); $finfoMimeType = $finfo->file($iconPath); if ($finfoMimeType) { $mimeType = $finfoMimeType; } } if (is_null($mimeType) && $motopressCERequirements->getExif()) { $exifImageType = exif_imagetype($iconPath); if ($exifImageType) { $mimeType = image_type_to_mime_type($exifImageType); } } $extension = null; if (is_null($mimeType) && $motopressCERequirements->getImagick()) { try { $imagick = new Imagick($iconPath); $extension = strtolower($imagick->getImageFormat()); } catch (ImagickException $e) { if ($motopressCESettings['debug']) { var_dump($e); } } } if (is_null($extension) && $motopressCERequirements->getGmagick()) { try { $gmagick = new Gmagick($iconPath); $extension = strtolower($gmagick->getimageformat()); } catch (GmagickException $e) { if ($motopressCESettings['debug']) { var_dump($e); } } } if (is_null($extension)) { $extension = pathinfo($iconPath, PATHINFO_EXTENSION); } if (!is_null($mimeType) || !is_null($extension)) { if (in_array($mimeType, self::$mimeTypes) || in_array($extension, self::$extensions)) { $this->icon = $iconUrl; } else { $this->addError('icon', strtr($motopressCELang->CEIconValidation, array('%name%' => $mimeType))); } } else { $this->addError('icon', $motopressCELang->CEUnknownMimeType); } } else { $this->addError('icon', strtr($motopressCELang->fileNotExists, array('%name%' => $iconPath))); } } else { $this->addError('icon', $motopressCELang->CEEmpty); } } else { $this->addError('icon', strtr($motopressCELang->CEInvalidArgumentType, array('%name%' => gettype($icon)))); } }
/** * * @var string $file path to image file * @return array */ protected function loadImage($file) { $result = array(); $image = new \Imagick($file); $result['image'] = $image; $geometry = $image->getImageGeometry(); $result['width'] = $geometry['width']; $result['height'] = $geometry['height']; $result['format'] = $image->getImageFormat(); return $result; }
} if ($_GET['max_width']) { $image_cache->set_max_width($_GET['max_width']); } if ($_GET['max_height']) { $image_cache->set_max_height($_GET['max_height']); } if ($_GET['width']) { $file_path = constant("BASE_DIR") . "/filesystem/temp/" . $image_cache->get_image($_GET['width']); } elseif ($_GET['height']) { $file_path = constant("BASE_DIR") . "/filesystem/temp/" . $image_cache->get_image(null, $_GET['height']); } else { $file_path = constant("BASE_DIR") . "/filesystem/temp/" . $image_cache->get_image(); } if (!$file_path) { $file_path = constant("WWW_DIR") . "/images/access.jpg"; } } else { $file_path = constant("WWW_DIR") . "/images/access.jpg"; } } else { $file_path = constant("WWW_DIR") . "/images/access.jpg"; } $image = new Imagick($file_path); if ($image->getImageFormat() != "PNG") { $image->setImageFormat("jpg"); header("Content-Type: image/jpeg"); } else { header("Content-Type: image/png"); } echo $image;
public function doUpload2($key, $sw = 0, $sh = 0) { if (array_key_exists($_FILES[$key]['type'], self::$FORMAT) && $_FILES[$key]["size"] < self::$MAX_SIZE) { $config = Zend_Registry::get('config'); // イメージ読み込み $image = new Imagick(); $image->readImage($_FILES[$key]['tmp_name']); $iw = $image->getImageWidth(); $ih = $image->getImageHeight(); $image_direction = 1; //portrait // フォーマットチェック if ($image->getImageFormat() != 'JPEG') { return null; } elseif ($iw == 1461 && $ih == 2122) { $orig_image = file_get_contents($_FILES[$key]['tmp_name']); $image_direction = 1; //portrait } elseif ($iw == 2122 && $ih == 1461) { $tt = $sw; $sw = $sh; $sh = $tt; $orig_image = file_get_contents($_FILES[$key]['tmp_name']); $image_direction = 2; //landscape } else { return null; } $image_id = str_replace(".", "", uniqid('', true)) . ".jpg"; // 拡大縮小 if ($sw > $iw && $sh > $ih) { // リサイズなし } elseif ($sw / $iw > $sh / $ih) { // 幅縮小 $image->resizeImage((int) ($iw * $sh / $ih), $sh, imagick::FILTER_LANCZOS, 0.9); } else { // 高さ縮小 $image->resizeImage($sw, (int) ($ih * $sw / $iw), imagick::FILTER_LANCZOS, 0.9); } // ファイル書き込み $path = '/home/sites/livecard/www/upload/picture/' . $image_id; $link = $config->app->base_url . '/upload/picture/' . $image_id; file_put_contents($path, $orig_image); // ファイル書き込み $tpath = '/home/sites/livecard/www/upload/picture/thumb/' . $image_id; $tlink = $config->app->base_url . '/upload/picture/thumb/' . $image_id; $image->writeImage($tpath); $image->destroy(); return array('imageUrl' => $link, 'thumbnailUrl' => $tlink, 'imageDirection' => $image_direction); } return null; }
$im->readImage(JPEG_FILE); $im->setImageFormat('png'); $im->writeImageFile($fp); $im->clear(); fclose($fp); // Output the format $identify = new Imagick(PNG_FILE); echo $identify->getImageFormat() . PHP_EOL; // Lets try again, setting the filename rather than format // This should cause PNG image to be written $fp = fopen(PNG_FILE, "w+"); $im->readImage(JPEG_FILE); $im->setImageFilename('png:'); $im->writeImageFile($fp); $im->clear(); fclose($fp); // If all goes according to plan, on second time we should get PNG $identify = new Imagick(PNG_FILE); echo $identify->getImageFormat() . PHP_EOL; // Lastly, test the newly added format parameter $fp = fopen(PNG_FILE, "w+"); $im->readImage(JPEG_FILE); $im->writeImageFile($fp, 'png'); $im->clear(); fclose($fp); // If all goes according to plan, on second time we should get PNG $identify = new Imagick(PNG_FILE); echo $identify->getImageFormat() . PHP_EOL; unlink(PNG_FILE); unlink(JPEG_FILE); echo 'done' . PHP_EOL;