function resize($source_name, $width = "", $height = "", $save_name = "") { $resource = NewMagickWand(); MagickReadImage($resource, $source_name); $src_image_x = MagickGetImageWidth($resource); $src_image_y = MagickGetImageHeight($resource); $src_image_scale = $src_image_x / $src_image_y; if ($width && $height) { $new_image_x = $width; $new_image_y = $height; } else { if ($width) { $new_image_x = $width; $new_image_y = $new_image_x * ($src_image_y / $src_image_x); } else { $new_image_y = $height; $new_image_x = $new_image_y * ($src_image_x / $src_image_y); } } MagickResizeImage($resource, $new_image_x, $new_image_y, MW_BoxFilter, 1); if ($save_name) { MagickWriteImage($resource, $save_name); } else { header('Content-Type: image/jpeg'); MagickEchoImageBlob($resource); } DestroymagickWand($resource); }
public static function makeGifFromZip($zip_file_path, $delay) { $dir = $zip_file_path . 'dir/'; $zip = new ZipArchive(); $res = $zip->open($zip_file_path); if ($res === TRUE) { $zip->extractTo($dir); $zip->close(); } $files = glob($dir . '/*'); ksort($files); $mw = NewMagickWand(); for ($i = 0, $l = count($files); $i < $l; $i++) { $rw = NewMagickWand(); MagickReadImage($rw, $files[$i]); MagickSetImageDelay($rw, intval($delay) / 10); //magickwand比较特殊,>用的不是毫秒,所以毫秒需要转成1/100秒 MagickAddImage($mw, $rw); DestroyMagickWand($rw); } MagickSetFormat($mw, 'gif'); $gif_file_path = $zip_file_path . '.gif'; MagickWriteImages($mw, $gif_file_path, true); DestroyMagickWand($mw); //todo 删除目录 return $gif_file_path; }
/** * @return Uploader */ public function prepare() { if (is_array($this->session)) { $this->digital = (string) $this->session['digital']; $this->public = (bool) $this->session['fg_publico']; } else { throw new Exception('Não foi possível recuperar os dados da sessão!'); } if ($this->_isFile()) { $this->hash = (string) hash_file('md5', $this->file["tmp_name"]); $this->type = (string) substr($this->file["name"], -3); $this->size = (int) $this->file["size"]; try { MagickReadImage($object = NewMagickWand(), $this->file["tmp_name"]); $this->width = MagickGetImageWidth($object); $this->height = MagickGetImageHeight($object); $this->codeType = MagickGetImageFormat($object); $this->sizeBytes = MagickGetImageSize($object); $this->compression = MagickGetImageCompression($object); $this->compressionQuality = MagickGetImageCompressionQuality($object); $this->resolution = MagickGetImageResolution($object); $this->resolutionUnits = MagickGetImageUnits($object); } catch (Exception $e) { throw new Exception('Ocorreu um erro!'); } } else { throw new Exception('O arquivo está ausente!'); } return $this; }
public function load($sourcePath) { parent::load($sourcePath); $this->_getResource(); try { MagickReadImage($this->_resource, $sourcePath); } catch (Exception $e) { throw new Bbx_Media_Image_Processor_Exception('Failed to load image ' . $sourcePath); } }
public function watermark($file, $mark_image, $set) { $sourceWand = NewMagickWand(); $compositeWand = NewMagickWand(); MagickReadImage($compositeWand, $mark_image); MagickReadImage($sourceWand, $file); MagickSetImageIndex($compositeWand, 0); MagickSetImageType($compositeWand, MW_TrueColorMatteType); MagickEvaluateImage($compositeWand, MW_SubtractEvaluateOperator, ($set['wm_opacity'] ? $set['wm_opacity'] : 50) / 100, MW_OpacityChannel); MagickCompositeImage($sourceWand, $compositeWand, MW_ScreenCompositeOp, $set['dest_x'], $set['dest_y']); MagickWriteImage($sourceWand, $file); }
function makeThumbnailtoFile($destFile) { $returnVal = false; if (!$this->isWorking()) { return false; } $image = NewMagickWand(); MagickReadImage($image, $this->sourceFile); MagickSetImageCompressionQuality($image, $this->thumbQuality); MagickThumbnailImage($image, $this->thumbWidth, $this->thumbHeight); $returnVal = MagickWriteImage($image, $destFile); unset($image); return $returnVal; }
public function getImgWand($resource = "", $size = array()) { $result = NewMagickWand(); if (count($size) == 2) { MagickSetWandSize($result, $size[0], $size[1]); } if (IsMagickWand($resource)) { $result = CloneMagickWand($resource); } elseif (is_array($resource) && count($resource) == 3) { MagickNewImage($result, $resource[1], $resource[2], $resource[0]); } elseif (!empty($resource)) { MagickReadImage($result, $resource); } return $result; }
/** * liberty_magickwand_convert_colorspace * * @param array $pFileHash * @param string $pColorSpace - target color space, only 'grayscale' is currently supported * @access public * @return TRUE on success, FALSE on failure - mErrors will contain reason for failure */ function liberty_magickwand_convert_colorspace_image(&$pFileHash, $pColorSpace) { $ret = FALSE; if (!empty($pFileHash['source_file']) && is_file($pFileHash['source_file'])) { $magickWand = NewMagickWand(); if ($error = liberty_magickwand_check_error(MagickReadImage($magickWand, $pFileHash['source_file']), $magickWand)) { bit_error_log("MagickReadImage Failed:{$error} ( {$pFileHash['source_file']} )"); } else { MagickRemoveImageProfile($magickWand, "ICC"); switch (strtolower($pColorSpace)) { case 'grayscale': if (MagickGetImageColorspace($magickWand) == MW_GRAYColorspace) { $ret = TRUE; } else { MagickSetImageColorspace($magickWand, MW_GRAYColorspace); if (empty($pFileHash['dest_file'])) { $pFileHash['dest_file'] = STORAGE_PKG_PATH . $pFileHash['dest_branch'] . $pFileHash['name']; } if ($error = liberty_magickwand_check_error(MagickWriteImage($magickWand, $pFileHash['dest_file']), $magickWand)) { bit_error_log("MagickWriteImage Failed:{$error} ( {$pFileHash['source_file']} )"); } else { $ret = TRUE; } } break; } } DestroyMagickWand($magickWand); } return $ret; }
/** * Imports the given file using the MagickWand extension if possible. (Internal only) * @param SloodleModulePresenter $presenter An object representing the Presenter we are importing into. * @param string $srcfile Full path of the PDF file we are importing * @param string $destpath Folder path to which the imported files will be added. * @param string $viewurl URL of the folder in which the imported files will be viewed * @param string $destfile Name for the output files (excluding extension, such as .jpg). The page numbers will be appended automatically, before the extension * @param string $destfileext Extension for destination files, not including the dot. (e.g. "jpg" or "png"). * @param string $destname Basic name to use for each imported slide. The page numbers will be appended automatically. * @param integer $position The position within the Presentation to add the new slides. Optional. Default is to put them at the end. * @return integer|bool If successful, an integer indicating the number of slides loaded is displayed. If the import does not (or cannot) work, then boolean false is returned. * @access private */ function _import_MagickWand($presenter, $srcfile, $destpath, $viewurl, $destfile, $destfileext, $destname, $position = -1) { global $CFG; // Only continue if the MagickWand extension is loaded (this is done by the check_compatibility function) if (!extension_loaded('magickwand')) { return false; } // Load the PDF file sloodle_debug('Loading PDF file... '); $mwand = NewMagickWand(); if (!MagickReadImage($mwand, $srcfile)) { sloodle_debug('failed.<br/>'); return false; } sloodle_debug('OK.<br/>'); // Quick validation - position should start at 1. (-ve numbers mean "at the end") if ($position == 0) { $position = 1; } // Go through each page sloodle_debug('Preparing to iterate through pages of document...<br/>'); MagickSetFirstIterator($mwand); $pagenum = 0; $page_position = -1; do { // Determine this page's position in the Presentation if ($position > 0) { $page_position = $position + $pagenum; } $pagenum++; // Construct the file and slide names for this page $page_filename = "{$destpath}/{$destfile}-{$pagenum}.{$destfileext}"; // Where it gets uploaded to $page_slidesource = "{$viewurl}/{$destfile}-{$pagenum}.{$destfileext}"; // The URL to access it publicly $page_slidename = "{$destname} ({$pagenum})"; // Output the file sloodle_debug(" Writing page {$pagenum} to file..."); if (!MagickWriteImage($mwand, $page_filename)) { sloodle_debug('failed.<br/>'); } else { sloodle_debug('OK.<br/>'); } // Add the entry to the Presenter sloodle_debug(" Adding slide \"{$page_slidename}\" to presentation at position {$page_position}... "); if (!$presenter->add_entry($page_slidesource, 'image', $page_slidename, $page_position)) { sloodle_debug('failed.<br/>'); } else { sloodle_debug('OK.<br/>'); } } while (MagickNextImage($mwand)); sloodle_debug('Finished.<br/>'); DestroyMagickWand($mwand); return $pagenum; }
function PosterizeNew() { $MagickWand = NewMagickWand(); MagickReadImage($MagickWand, "/home/alex/src/imws-server/app/www/turtlz.jpg"); #$e = MagickGetExceptionString($MagickWand); #die($e); MagickSetImageFormat($MagickWand, 'png'); MagickWriteImage($MagickWand, "/tmp/zz"); }
/** * Resize an image to a specific width/height * * @param int $maxWidth maximum image Width (px) * @param int $maxHeight maximum image Height (px) * @param string $origFile current images folder path (must have trailing end slash) * @param string $destFile destination folder path for resized image (must have trailing end slash) * @param int $quality Percentage image save quality 100 = no compression, 0 = max compression * * @return object image */ public function resize($maxWidth, $maxHeight, $origFile, $destFile, $quality = 100) { $ext = $this->getImgType($origFile); if (!$ext) { // False so not an image type so cant resize // $$$ hugh - testing making thumbs for PDF's, so need a little tweak here $origInfo = pathinfo($origFile); if (JString::strtolower($origInfo['extension']) != 'pdf') { return; } } ini_set('display_errors', true); // See if the imagick image lib is installed if (class_exists('Imagick')) { /* $$$ hugh - having a go at handling PDF thumbnails, which should work as long as the server * has ghostscript (GS) installed. Don't have a generic test for GS being available, so * it'll just fail if no GS. */ $origInfo = pathinfo($origFile); if (JString::strtolower($origInfo['extension']) == 'pdf') { $pdfThumbType = 'png'; // OK, it's a PDF, so first we need to add the page number we want to the source filename $pdfFile = $origFile . '[0]'; if (is_callable('exec')) { $destFile = str_replace('.pdf', '.png', $destFile); // Output File $convert = "convert " . $pdfFile . " -colorspace RGB -resize " . $maxWidth . " " . $destFile; // Command creating exec($convert); // Execution of complete command. } else { // Now just load it, set format, resize, save and garbage collect. // Hopefully IM will call the right delegate (ghostscript) to load the PDF. $im = new Imagick($pdfFile); $im->setImageFormat($pdfThumbType); $im->thumbnailImage($maxWidth, $maxHeight, true); $im->writeImage($destFile); // as destroy() is deprecated $im->clear(); } } else { $im = new Imagick(); /* Read the image file */ $im->readImage($origFile); /* Thumbnail the image ( width 100, preserve dimensions ) */ $im->thumbnailImage($maxWidth, $maxHeight, true); /* Write the thumbnail to disk */ $im->writeImage($destFile); /* Free resources associated to the Imagick object */ $im->destroy(); } $this->thumbPath = $destFile; } else { $resource = NewMagickWand(); if (!MagickReadImage($resource, $origFile)) { echo "ERROR!"; print_r(MagickGetException($resource)); } $resource = MagickTransformImage($resource, '0x0', $maxWidth . 'x' . $maxWidth); $this->thumbPath = $destFile; MagickWriteImage($resource, $destFile); } }
/** * liberty_generate_thumbnails * * @param array $pFileHash * @access public * @return TRUE on success, FALSE on failure - mErrors will contain reason for failure */ function liberty_generate_thumbnails($pFileHash) { global $gBitSystem, $gThumbSizes; $resizeFunc = liberty_get_function('resize'); $ret = FALSE; // allow custom selection of thumbnail sizes if (empty($pFileHash['thumbnail_sizes'])) { if (!empty($gThumbSizes) && is_array($gThumbSizes)) { $pFileHash['thumbnail_sizes'] = array_keys($gThumbSizes); } else { $pFileHash['thumbnail_sizes'] = array('large', 'medium', 'small', 'avatar', 'icon'); } } if (!preg_match('#image/(gif|jpe?g|png)#i', $pFileHash['type']) && $gBitSystem->isFeatureActive('liberty_jpeg_originals') || in_array('original', $pFileHash['thumbnail_sizes'])) { // jpeg version of original if (preg_match('/pdf/i', $pFileHash['type'])) { // has a customer pdf rasterization function been defined? if (function_exists('liberty_rasterize_pdf') && ($rasteredFile = liberty_rasterize_pdf($pFileHash['source_file']))) { $pFileHash['source_file'] = $rasteredFile; } else { $magickWand = NewMagickWand(); if (!($pFileHash['error'] = liberty_magickwand_check_error(MagickReadImage($magickWand, $pFileHash['source_file']), $magickWand))) { MagickSetFormat($magickWand, 'JPG'); if (MagickGetImageColorspace($magickWand) == MW_CMYKColorspace) { MagickProfileImage($magickWand, "ICC", UTIL_PKG_PATH . 'icc/srgb.icm'); MagickSetImageColorspace($magickWand, MW_sRGBColorspace); } $imgWidth = MagickGetImageWidth($magickWand); $imgHeight = MagickGetImageHeight($magickWand); MagickSetImageUnits($magickWand, MW_PixelsPerInchResolution); MagickSetResolution($magickWand, 300, 300); $rasteredFile = dirname($pFileHash['source_file']) . '/original.jpg'; if (!($pFileHash['error'] = liberty_magickwand_check_error(MagickWriteImage($magickWand, $rasteredFile), $magickWand))) { $pFileHash['source_file'] = $rasteredFile; } } } } else { $pFileHash['dest_base_name'] = 'original'; $pFileHash['name'] = 'original.jpg'; $pFileHash['max_width'] = MAX_THUMBNAIL_DIMENSION; $pFileHash['max_height'] = MAX_THUMBNAIL_DIMENSION; if ($convertedFile = $resizeFunc($pFileHash)) { $pFileHash['source_file'] = $convertedFile; $ret = TRUE; } } $pFileHash['type'] = $gBitSystem->verifyMimeType($pFileHash['source_file']); } // override $mimeExt if we have a custom setting for it if ($gBitSystem->isFeatureActive('liberty_thumbnail_format')) { $mimeExt = $gBitSystem->getConfig('liberty_thumbnail_format'); } else { list($type, $mimeExt) = preg_split('#/#', strtolower($pFileHash['type'])); } if (preg_match("!(png|gif)!", $mimeExt)) { $destExt = '.' . $mimeExt; } else { $destExt = '.jpg'; } $initialDestPath = $pFileHash['dest_branch']; foreach ($pFileHash['thumbnail_sizes'] as $thumbSize) { if (isset($gThumbSizes[$thumbSize])) { $pFileHash['dest_base_name'] = $thumbSize; $pFileHash['name'] = $thumbSize . $destExt; if (!empty($gThumbSizes[$thumbSize]['width'])) { $pFileHash['max_width'] = $gThumbSizes[$thumbSize]['width']; } else { // Have to unset since we reuse $pFileHash unset($pFileHash['max_width']); } // reset dest_branch for created thumbs if (!empty($pFileHash['thumb_path'])) { $pFileHash['dest_file'] = $pFileHash['thumb_path'] . $pFileHash['name']; } else { // create a subdirectory for the thumbs $pFileHash['dest_branch'] = $initialDestPath . 'thumbs/'; clearstatcache(); if (!is_dir(STORAGE_PKG_PATH . $pFileHash['dest_branch'])) { mkdir(STORAGE_PKG_PATH . $pFileHash['dest_branch'], 0775, TRUE); clearstatcache(); } } if (!empty($gThumbSizes[$thumbSize]['height'])) { $pFileHash['max_height'] = $gThumbSizes[$thumbSize]['height']; } else { // Have to unset since we reuse $pFileHash unset($pFileHash['max_height']); } if ($pFileHash['icon_thumb_path'] = $resizeFunc($pFileHash)) { $ret = TRUE; // use the previous thumb as the source for the next, decreasingly smaller thumb as this GREATLY increases speed $pFileHash['source_file'] = $pFileHash['icon_thumb_path']; } } } // to keep everything in bitweaver working smoothly, we need to remove the thumbs/ subdir again $pFileHash['dest_branch'] = $initialDestPath; return $ret; }
function resize_file_MagicWand(&$file, $create) { $image = NewMagickWand(); MagickReadImage($image, $this->upload->path . '/' . $this->orgFileName); MagickResizeImage($image, $this->newWidth, $this->newHeight, MW_MitchellFilter, 1); MagickSetImageCompressionQuality($image, $this->quality); //Set the extension of the new file $ext = $this->GetNewfileExtension(); if (file_exists($this->upload->path . '/' . $file->name . "." . $ext) and $file->name . "." . $ext != $file->fileName and $this->upload->nameConflict == "uniq") { $file->setFileName($this->upload->createUniqName($file->name . "." . $ext)); } if ($create == "image") { $fileName = $file->name . "." . $ext; @unlink($this->upload->path . '/' . $this->orgFileName); MagickWriteImage($image, $this->upload->path . '/' . $fileName); $file->setFileName($fileName); } else { if ($this->pathThumb == "") { $this->pathThumb = $this->upload->path; } if ($this->naming == "suffix") { $fileName = $file->name . $this->suffix . "." . $ext; } else { $fileName = $this->suffix . $file->name . "." . $ext; } MagickWriteImage($image, $this->pathThumb . '/' . $fileName); $file->setThumbFileName($fileName, $this->pathThumb, $this->naming, $this->suffix); } DestroyMagickWand($image); }
/** * 设置图片水印 * @param object image 实体对象 * @param string 文件路径 * @param array 设置的集合 * @return null */ function image_watermark(&$imgmdl, $file, $set) { switch ($set['wm_type']) { case 'text': $mark_image = $set['wm_text_image']; break; case 'image': $mark_image = $set['wm_image']; break; default: return; } if ($set['wm_text_preview']) { $mark_image = $set['wm_text_image']; } else { $mark_image = $imgmdl->fetch($mark_image); } list($watermark_width, $watermark_height, $type) = getimagesize($mark_image); list($src_width, $src_height) = getimagesize($file); list($dest_x, $dest_y) = self::get_watermark_dest($src_width, $src_height, $watermark_width, $watermark_height, $set['wm_loc']); if (ECAE_MODE) { include_lib('image.php'); $obj = new ecae_image(); $obj->set_file($file); $obj->watermark(file_get_contents($mark_image), $dest_x, $dest_y, 0, 0, $set['wm_opacity'] ? $set['wm_opacity'] : 50); $content = $obj->exec(); if ($content) { file_put_contents($file, $content); } } elseif (function_exists('NewMagickWand')) { $sourceWand = NewMagickWand(); $compositeWand = NewMagickWand(); MagickReadImage($compositeWand, $mark_image); MagickReadImage($sourceWand, $file); MagickSetImageIndex($compositeWand, 0); MagickSetImageType($compositeWand, MW_TrueColorMatteType); MagickEvaluateImage($compositeWand, MW_SubtractEvaluateOperator, ($set['wm_opacity'] ? $set['wm_opacity'] : 50) / 100, MW_OpacityChannel); MagickCompositeImage($sourceWand, $compositeWand, MW_ScreenCompositeOp, $dest_x, $dest_y); MagickWriteImage($sourceWand, $file); } elseif (method_exists(image_clip, 'imagecreatefrom')) { $sourceimage = self::imagecreatefrom($file); $watermark = self::imagecreatefrom($mark_image); imagecolortransparent($watermark, imagecolorat($watermark, 0, 0)); imagealphablending($watermark, 1); $set['wm_opacity'] = intval($set['wm_opacity']); imagecopymerge($sourceimage, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, $set['wm_opacity']); imagejpeg($sourceimage, $file); imagedestroy($sourceimage); imagedestroy($watermark); } @unlink($mark_image); }
function resizeMobile2($src_path, $dest_path, $d_width, $d_height) { $mk = NewMagickWand(); if (!MagickPingImage($mk, $src_path)) { echo "magick wand - no image \n"; $format = sprintf("convert %s -resize %dx%d -colors 256 -quality 90 -depth 8 %s", $src_path, $destWidth, $destHeight, $dest_path); $buffer = ""; exec($format, $buffer); return false; } // Now we need to clear out the data that MagickPingImage() put there ClearMagickWand($mk); if (MagickReadImage($mk, $src_path)) { list($srcWidth, $srcHeight, $destWidth, $destHeight) = getRate($src_path, $d_width, $d_height); //소스 이미지를 읽어서 $mk = MagickTransformImage($mk, NULL, $destWidth . "x" . $destHeight); MagickSetImageCompressionQuality($mk, 90); MagickSetImageDepth($mk, 8); //MagickSetImageIndex($mk, 256); MagickProfileImage($mk, "*", ""); MagickQuantizeImage($mk, 256, MW_RGBColorspace, 0, true, false); //$chk = MagickResizeImage($mk, $destWidth, $destHeight); //echo "$src_path , $dest_path, $destWidth, $destHeight \n"; // 이미지를 리사이징해라. 가로 $w 세로 $h //MagickResizeImage() 이라는 함수도 있는데 위의 것이 더 범용적입니다. if ($mk == null) { //echo "this is convert"; $format = sprintf("convert %s -resize %dx%d -colors 256 -quality 90 -depth 8 %s", $src_path, $destWidth, $destHeight, $dest_path); $buffer = ""; exec($format, $buffer); //echo "object is null \n"; return true; } MagickWriteImage($mk, $dest_path); // 새로운 이미지를 만들어라~ ClearMagickWand($mk); } else { echo "magick wand - read fail \n"; return false; } return true; }
/** * @return Imagens * @param string $digital * @param string $md5 * @param boolean $high * @param int $active * @param int $total */ public function createCacheJpegView($digital, $md5, $high = false) { $iImageHeightPixel = $high === false ? 960 : 2480; $iImageWidthPixel = $high === false ? 1280 : 3508; $lote = $this->generateLote($digital); $dirCache = sprintf('%s/cache/%s', __CAM_UPLOAD__, $lote); $tiff = sprintf('%s/%s/%s/%s.tif', __CAM_UPLOAD__, $lote, $digital, $md5); $view = sprintf('%s/%s/%s_view_%d.jpg', $dirCache, $digital, $md5, $high === false ? self::Q_LOW : self::Q_HIGH); $thumbs = sprintf('%s/%s/%s_thumb.jpg', $dirCache, $digital, $md5); if (!is_file($tiff)) { throw new Exception('Arquivo TIFF original não encontrado!'); } if (is_file($view)) { return $this; } // thumbs if (!is_file($thumbs)) { MagickReadImage($magickThumbs = NewMagickWand(), $tiff); if (MagickGetImageWidth($magickThumbs) < MagickGetImageHeight($magickThumbs)) { MagickResizeImage($magickThumbs, 150, 200, MW_QuadraticFilter, 1.0); } else { MagickResizeImage($magickThumbs, 200, 150, MW_QuadraticFilter, 1.0); } MagickSetImageFormat($magickThumbs, 'JPG'); MagickSetImageResolution($magickThumbs, 200, 200); MagickSetImageUnits($magickThumbs, MW_PixelsPerInchResolution); MagickSetImageCompression($magickThumbs, MW_JPEGCompression); MagickSetImageCompressionQuality($magickThumbs, 0.0); MagickWriteImage($magickThumbs, $thumbs); } // views MagickReadImage($magickView = NewMagickWand(), $tiff); if (MagickGetImageWidth($magickView) > MagickGetImageHeight($magickView)) { MagickResizeImage($magickView, $iImageWidthPixel, $iImageHeightPixel, MW_QuadraticFilter, 1.0); } else { MagickResizeImage($magickView, $iImageHeightPixel, $iImageWidthPixel, MW_QuadraticFilter, 1.0); } MagickSetImageFormat($magickView, 'JPG'); MagickSetImageResolution($magickView, 200, 200); MagickSetImageUnits($magickView, MW_PixelsPerInchResolution); MagickSetImageCompression($magickView, MW_JPEGCompression); MagickSetImageCompressionQuality($magickView, 0.0); MagickWriteImage($magickView, $view); $errorMagick = MagickGetExceptionString($magickView); if ($errorMagick) { throw new Exception($errorMagick); } return $this; }
/** * Open the source and target image for processing it * * @param Asido_TMP &$tmp * @return boolean * @access protected */ function __open(&$tmp) { $tmp->source = NewMagickWand(); $error_open = !MagickReadImage($tmp->source, $tmp->source_filename); $error_open &= !($tmp->target = CloneMagickWand($tmp->source)); // get width & height of the image // if (!$error_open) { $tmp->image_width = MagickGetImageWidth($tmp->source); $tmp->image_height = MagickGetImageHeight($tmp->source); } return !$error_open; }
private function createAndUploadImageDimensionMap(Image $image, $dimensionsKeyname) { $imd = $this->getDimensionByKeyname($dimensionsKeyname); $srcPth = $this->imagesRoot . $image->FilePath; if (file_exists($srcPth)) { $tempPath = tempnam(sys_get_temp_dir(), 'img_'); if ($dimensionsKeyname == 'original') { $s3Path = $srcPth; $pts = getimagesize($s3Path); $width = $pts[0]; $height = $pts[1]; $newDims = array('x' => $width, 'y' => $height); $s3Path = $srcPth; } else { //need to redimension this image, using MagickWand $magick_wand = NewMagickWand(); MagickReadImage($magick_wand, $srcPth); $width = MagickGetImageWidth($magick_wand); $height = MagickGetImageHeight($magick_wand); $newDims = $this->getNewDimensionsPreservingAspectRatio($width, $height, $imd->Width, $imd->Height); MagickScaleImage($magick_wand, $newDims['x'], $newDims['y']); MagickWriteImage($magick_wand, $tempPath); $s3Path = $tempPath; } $headers = array(); //This holds the http headers for our S3 object. switch ($image->ImageType) { case 'GIF': $headers['Content-Type'] = 'image/gif'; break; case 'JPG': $headers['Content-Type'] = 'image/jpeg'; break; case 'PNG': $headers['Content-Type'] = 'image/png'; break; default: throw new Exception("Unrecognized type {$image->getType()}"); break; } //A "Far Future" expiration - maximizing the chance that the user's web browser will use //a cached version rather than requesting the file from Cloudfront. //Also set to public (as recommended by Google Speed Tracer), so that caching will work when //using SSL as well. Even though Cloudfont doesn't support ssl today, someday it will //and we will be prepared! $headers['Cache-Control'] = 'public, max-age=315360000'; //10 years $imDimMap = new ImageDimensionsMap(); $imDimMap->ImageId = $image->Id; $imDimMap->ImageDimensionsId = $imd->Id; $imDimMap->Width = $newDims['x']; $imDimMap->Height = $newDims['y']; $imDimMap->Version = $image->Version; $imDimMap->save(); //upload the new file to S3 try { $acl = S3Service::ACL_PUBLIC_READ; if (!file_exists($tempPath)) { throw new Exception("{$tempPath} dosn't exist"); } $res = $this->s3->putObject(S3Service::inputFile($s3Path, true), $this->bucket, $this->getPath($image, $imDimMap, $imd), $acl, array(), $headers); if ($res) { unlink($tempPath); } else { //something's wrong. Fail silently and just leave the old version if it exists. //Don't throw an exception or raise a failure, because there's a user on the other side //of this request waiting to see this image. $imDimMap->Version = $imDimMap->Version - 1; $imDimMap->save(); } } catch (Exception $e) { //something's wrong. Fail silently and just leave the old version if it exist. //Don't throw an exception or raise a failure, because there's a user on the other side //of this request waiting to see this image. $imDimMap->Version = $imDimMap->Version - 1; $imDimMap->save(); } } return $imDimMap; }
function createThumb($objWidth, $objHeight, $nmw = "") { $srcImage = $this->src_image_name; if (!IsMagickWand($nmw)) { $nmw = NewMagickWand(); MagickReadImage($nmw, $srcImage); } $srcImageWidth = MagickGetImageWidth($nmw); $srcImageHeight = MagickGetImageHeight($nmw); if ($objWidth == 0 || $objHeight == 0) { $objWidth = $srcImageWidth; $objHeight = $srcImageHeight; } if ($objWidth < $objHeight) { $mu = $srcImageWidth / $objWidth; $objHeight = ceil($srcImageHeight / $mu); } else { $mu = $srcImageHeight / $objHeight; $objWidth = ceil($srcImageWidth / $mu); } MagickScaleImage($nmw, $objWidth, $objHeight); $ndw = NewDrawingWand(); DrawComposite($ndw, MW_AddCompositeOp, 0, 0, $objWidth, $objHeight, $nmw); $res = NewMagickWand(); MagickNewImage($res, $objWidth, $objHeight); MagickDrawImage($res, $ndw); MagickSetImageFormat($res, MagickGetImageFormat($nmw)); return $res; }
function image_watermark(&$imgmdl, $file, $set) { switch ($set['wm_type']) { case 'text': $mark_image = $set['wm_text_image']; break; case 'image': $mark_image = $set['wm_image']; break; default: return; } $mark_image = $imgmdl->fetch($mark_image); list($watermark_width, $watermark_height, $type) = getimagesize($mark_image); list($src_width, $src_height) = getimagesize($file); list($dest_x, $dest_y) = self::get_watermark_dest($src_width, $src_height, $watermark_width, $watermark_height, $set['wm_loc']); if (function_exists('NewMagickWand')) { $sourceWand = NewMagickWand(); $compositeWand = NewMagickWand(); MagickReadImage($compositeWand, $mark_image); MagickReadImage($sourceWand, $file); MagickSetImageIndex($compositeWand, 0); MagickSetImageType($compositeWand, MW_TrueColorMatteType); MagickEvaluateImage($compositeWand, MW_SubtractEvaluateOperator, ($set['wm_opacity'] ? $set['wm_opacity'] : 50) / 100, MW_OpacityChannel); MagickCompositeImage($sourceWand, $compositeWand, MW_ScreenCompositeOp, $dest_x, $dest_y); MagickWriteImage($sourceWand, $file); } elseif (method_exists(image_clip, 'imagecreatefrom')) { $sourceimage = self::imagecreatefrom($file); $watermark = self::imagecreatefrom($mark_image); imagecolortransparent($watermark, imagecolorat($watermark, 0, 0)); imagealphablending($watermark, 1); if ($type == IMAGETYPE_PNG) { imagecopy($sourceimage, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height); } else { imagecopymerge($sourceimage, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, $set['wm_opacity'] ? $set['wm_opacity'] : 100); } imagejpeg($sourceimage, $file); imagedestroy($sourceimage); imagedestroy($watermark); } }
function zoomImg($src, $dest, $width, $height) { $srcImgRes = NewMagickWand(); if (!MagickReadImage($srcImgRes, $src)) { exit("Error MagickReadImage {$src}\n"); } MagickScaleImage($srcImgRes, $width, $height); MagickWriteImage($srcImgRes, $dest); }
/** * resize an image to a specific width/height using imagemagick * you cant set the quality of the resized image * @param int maximum image Width (px) * @param int maximum image Height (px) * @param string full path of image to resize * @param string full file path to save resized image to * @return string output from image magick command */ function resize($maxWidth, $maxHeight, $origFile, $destFile) { $ext = $this->GetImgType($origFile); if (!$ext) { //false so not an image type so cant resize // $$$ hugh - testing making thumbs for PDF's, so need a little tweak here $originfo = pathinfo($origFile); if (strtolower($originfo['extension']) != 'pdf') { return; } } ini_set('display_errors', true); //see if the imagick image lib is installed if (class_exists('Imagick')) { // $$$ hugh - having a go at handling PDF thumbnails, which should work as long as the server // has ghostscript (GS) installed. Don't have a generic test for GS being available, so // it'll just fail if no GS. $originfo = pathinfo($origFile); if (strtolower($originfo['extension']) == 'pdf') { $pdf_thumb_type = 'png'; // could use jpg or whatever // OK, it's a PDF, so first we need to add the page number we want to the source filename $pdf_file = $origFile . '[0]'; // Now check to see if the destination filename needs changing - existing code will probably // just have used the sourcefile extension for the thumb file. $destinfo = pathinfo($destFile); if (strtolower($destinfo['extension']) == 'pdf') { // rebuild $destFile with valid image extension // NOTE - changed $destFile arg to pass by reference OOOPS can't do that! // $$$ rob 04/08/2011 wont work in php 5.1 //$destFile = $destinfo['dirname'] . DS . $destinfo['filename'] . '.' . $pdf_thumb_type; $thumb_file = JFile::stripExt($destFile) . '.' . $pdf_thumb_type; } // Now just load it, set format, resize, save and garbage collect. // Hopefully IM will call the right delagate (ghostscript) to load the PDF. $im = new Imagick($pdf_file); $im->setImageFormat($pdf_thumb_type); $im->thumbnailImage($maxWidth, $maxHeight, true); $im->writeImage($destFile); $im->destroy(); } else { $im = new Imagick(); /* Read the image file */ $im->readImage($origFile); /* Thumbnail the image ( width 100, preserve dimensions ) */ $im->thumbnailImage($maxWidth, $maxHeight, true); /* Write the thumbail to disk */ $im->writeImage($destFile); /* Free resources associated to the Imagick object */ $im->destroy(); } $this->_thumbPath = $destFile; } else { $resource = NewMagickWand(); if (!MagickReadImage($resource, $origFile)) { echo "ERROR!"; print_r(MagickGetException($resource)); } $resource = MagickTransformImage($resource, '0x0', $maxWidth . 'x' . $maxWidth); $this->_thumbPath = $destFile; MagickWriteImage($resource, $destFile); } }
public function convert($ps_format, $ps_orig_filepath, $ps_dest_filepath) { $vs_filepath = $vs_ext = ""; # # First make sure the original file is an image # if (!($vs_mimetype = $this->test($ps_orig_filepath, ""))) { return false; } if ($vs_mimetype == "application/pdf") { return false; } $va_dest_path_pieces = explode("/", $ps_dest_filepath); $vs_dest_filestem = array_pop($va_dest_path_pieces); $vs_dest_dir = join("/", $va_dest_path_pieces); $vn_width = $vn_height = null; switch ($ps_format) { # ------------------------------------ case 'image/jpeg': $vs_ext = "jpg"; $vs_filepath = $vs_dest_filestem . "_conv." . $vs_ext; switch ($this->backend) { case LIBRARY_GD: if ($vs_mimetype = $this->test($ps_orig_filepath)) { switch ($vs_mimetype) { case "image/jpeg": $rsource = imagecreatefromjpeg($ps_orig_filepath); break; case "image/png": $rsource = imagecreatefrompng($ps_orig_filepath); break; case "image/gif": $rsource = imagecreatefromgif($ps_orig_filepath); break; default: return false; break; } if (!$r) { return false; } list($vn_width, $vn_height) = getimagesize($ps_orig_filepath); if ($vn_width > $vn_height) { $vn_ratio = $vn_height / $vn_width; $vn_target_width = 800; $vn_target_height = 800 * $vn_ratio; } else { $vn_ratio = $vn_width / $vn_height; $vn_target_height = 800; $vn_target_width = 800 * $vn_ratio; } if (!($rdest = imagecreatetruecolor($vn_target_width, $vn_target_height))) { return false; } if (!imagecopyresampled($rdest, $rsource, 0, 0, 0, 0, $vn_target_width, $vn_target_height, $vn_width, $vn_height)) { return false; } if (!imagejpeg($rdest, $vs_dest_dir . "/" . $vs_filepath)) { return false; } } else { return false; } break; default: $handle = NewMagickWand(); if (MagickReadImage($handle, $ps_orig_filepath)) { if (WandHasException($handle)) { return false; } $vn_width = MagickGetImageWidth($handle); $vn_height = MagickGetImageHeight($handle); if ($vn_width > $vn_height) { $vn_ratio = $vn_height / $vn_width; $vn_target_width = 800; $vn_target_height = 800 * $vn_ratio; } else { $vn_ratio = $vn_width / $vn_height; $vn_target_height = 800; $vn_target_width = 800 * $vn_ratio; } if (!MagickResizeImage($handle, $vn_target_width, $vn_target_height, MW_CubicFilter, 1)) { return false; } if (!MagickWriteImage($handle, $vs_dest_dir . "/" . $vs_filepath)) { return false; } } break; } break; # ------------------------------------ # ------------------------------------ default: return false; break; # ------------------------------------ } return array("extension" => $vs_ext, "format_name" => $this->info["CONVERSIONS"][$ps_format]["format_name"], "dangerous" => 0, "width" => $vn_width, "height" => $vn_height, "long_format_name" => $this->info["CONVERSIONS"][$ps_format]["long_format_name"]); }
/** * Image Process Using MagickWand * * This function will resize, crop or rotate * * @access public * @auth John Meng * @param string * @return bool */ function image_process_magickwand($action = 'resize') { if (!file_exists($this->full_src_path)) { $this->set_error("Image source file not found!"); return false; } if (file_exists($this->full_dst_path)) { @unlink("{$this->full_dst_path}"); } $magick_wand = NewMagickWand(); MagickRemoveImageProfiles($magick_wand); MagickSetCompressionQuality($magick_wand, $this->quality); MagickReadImage($magick_wand, $this->full_src_path); switch ($action) { case 'crop': MagickCropImage($magick_wand, $this->width, $this->height, $this->x_axis, $this->y_axis); break; case 'rotate': switch ($this->rotation_angle) { case 90: $angle = 90; break; case 180: $angle = 180; break; case 270: $angle = 270; break; case 'vrt': $angle = 180; break; case 'hor': $angle = 270; break; } MagickRotateImage($magick_wand, null, $angle); break; case 'resize': default: MagickResizeImage($magick_wand, $this->width, $this->height, MW_LanczosFilter, 1.0); break; } MagickWriteImage($magick_wand, $this->full_dst_path); DestroymagickWand($magick_wand); // Set the file to 777 @chmod($this->full_dst_path, $this->dir_write_mode); return TRUE; }
/** * liberty_magickwand_panorama_image - strictly speaking, this belongs in one of the image processing plugin files, but we'll leave it here for the moment * * @param array $pFileHash File hash - souce_file is required * @param array $pOptions * @access public * @return TRUE on success, FALSE on failure - mErrors will contain reason for failure */ function liberty_magickwand_panorama_image(&$pFileHash, $pOptions = array()) { $magickWand = NewMagickWand(); $pFileHash['error'] = NULL; if (!empty($pFileHash['source_file']) && is_file($pFileHash['source_file'])) { if (!($pFileHash['error'] = liberty_magickwand_check_error(MagickReadImage($magickWand, $pFileHash['source_file']), $magickWand))) { // calculate border width $iwidth = round(MagickGetImageWidth($magickWand)); $iheight = round(MagickGetImageHeight($magickWand)); $aspect = $iwidth / $iheight; $metaHash = array('width' => $iwidth, 'height' => $iheight, 'aspect' => $aspect); // store original file information that we can adjust the viewer LibertyMime::storeMetaData($pFileHash['attachment_id'], 'PANO', $metaHash); // we need to pad the image if the aspect ratio is not 2:1 (give it a wee bit of leeway that we don't add annoying borders if not really needed) if ($aspect > 2.1 || $aspect < 1.9) { $bwidth = $bheight = 0; if ($aspect > 2) { $bheight = round(($iwidth / 2 - $iheight) / 2); } else { $bwidth = round(($iheight / 2 - $iwidth) / 2); } // if the ratio has nothing to do with a panorama image - i.e. gives us a negative number here, we won't generate a panorama image if ($bheight > 0) { $pixelWand = NewPixelWand(); PixelSetColor($pixelWand, !empty($pOptions['background']) ? $pOptions['background'] : 'black'); if (!($pFileHash['error'] = liberty_magickwand_check_error(MagickBorderImage($magickWand, $pixelWand, $bwidth, $bheight), $magickWand))) { if (!($pFileHash['error'] = liberty_magickwand_check_error(MagickWriteImage($magickWand, $pFileHash['source_file']), $magickWand))) { // yay! } } DestroyPixelWand($pixelWand); } } } } DestroyMagickWand($magickWand); return empty($pFileHash['error']); }
protected function generateMW() { if (file_exits($this->pathcache . $this->getBaseName())) { return true; } $img = NewMagickWand(); MagickReadImage($img, $this->pathname . $this->filename); $this->info = array('width' => MagickGetImageWidth($img), 'height' => MagickGetImageHeight($img), 'duration' => 0, 'mime' => $this->mime, 'size' => filesize($this->pathname . $this->filename)); MagickSetImageFormat($img, 'JPEG'); MagickWriteImage($img, $this->pathcache . $this->getBaseName()); $this->mime = 'image/jpeg'; $this->type = array('image', 'jpeg'); $this->pathname = $this->pathcache; $this->filename = $this->getBaseName(); return true; }