Exemple #1
0
 /**
  * Destroys allocated imagick resources
  */
 public function __destruct()
 {
     if ($this->imagick instanceof \Imagick) {
         $this->imagick->clear();
         $this->imagick->destroy();
     }
 }
Exemple #2
0
 public function save($file, $gray = false, $quality = 100)
 {
     if ($gray) {
         $this->gray();
     }
     $res = $this->image->writeImages($file, true);
     $this->image->clear();
     $this->image->destroy();
     return $res;
 }
 /**
  * @see	\wcf\system\image\adapter\IImageAdapter::loadFile()
  */
 public function loadFile($file)
 {
     try {
         $this->imagick->clear();
         $this->imagick->readImage($file);
     } catch (\ImagickException $e) {
         throw new SystemException("Image '" . $file . "' is not readable or does not exist.");
     }
     $this->readImageDimensions();
 }
Exemple #4
0
 /**
  * Adaptation the image.
  * @param int $width
  * @param int $height
  * @param int $offset_x
  * @param int $offset_y
  */
 protected function _adapt($width, $height, $offset_x, $offset_y)
 {
     $image = new \Imagick();
     $image->newImage($width, $height, 'none');
     $image->compositeImage($this->im, \Imagick::COMPOSITE_ADD, $offset_x, $offset_y);
     $this->im->clear();
     $this->im->destroy();
     $this->im = $image;
     $this->width = $image->getImageWidth();
     $this->height = $image->getImageHeight();
 }
 /**
  * {@inheritDoc}
  */
 public function apply($absolutePath)
 {
     $info = pathinfo($absolutePath);
     if (isset($info['extension']) && false !== strpos(strtolower($info['extension']), 'pdf')) {
         // If it doesn't exists, extract the first page of the PDF
         if (!file_exists("{$absolutePath}.png")) {
             $this->imagick->readImage($absolutePath . '[0]');
             $this->imagick->setImageFormat('png');
             $this->imagick->writeImage("{$absolutePath}.png");
             $this->imagick->clear();
         }
         $absolutePath .= '.png';
     }
     return $absolutePath;
 }
Exemple #6
0
function create_thumb($source_file, $thumb_file, $edge = THUMBNAIL_CROP_EDGE, &$src_w = NULL, &$src_h = NULL)
{
    $composite_img = new Imagick($source_file);
    $blank_img = new Imagick();
    $src_w = $composite_img->getImageWidth();
    $src_h = $composite_img->getImageHeight();
    if ($src_h > $edge && $src_w > $edge) {
        $composite_img->cropThumbnailImage($edge, $edge);
        $composite_img->setImageFormat('jpeg');
        $composite_img->writeImage($thumb_file);
        $composite_img->clear();
        $blank_img = $composite_img;
    } else {
        $blank_img->newImage($edge, $edge, new ImagickPixel('#DEF'), "jpg");
        if ($src_w > $src_h) {
            $crop_x = $src_w / 2 - $edge / 2;
            $crop_y = 0;
            $offset_x = 0;
            $offset_y = $edge / 2 - $src_h / 2;
        } else {
            $crop_x = 0;
            $crop_y = $src_h / 2 - $edge / 2;
            $offset_x = $edge / 2 - $src_w / 2;
            $offset_y = 0;
        }
        $composite_img->cropImage($edge, $edge, $crop_x, $crop_y);
        $blank_img->compositeImage($composite_img, Imagick::COMPOSITE_OVER, $offset_x, $offset_y);
        $blank_img->setImageFormat('jpeg');
        $blank_img->writeImage($thumb_file);
        $blank_img->clear();
    }
    return $blank_img;
}
 public function destroyWatermarkResource()
 {
     if ($this->watermark) {
         $this->watermark->clear();
         $this->watermark = null;
     }
 }
Exemple #8
0
 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;
     }
 }
Exemple #9
0
 public function resize($file, $size = array('width' => 100, 'height' => 100), $type = 'png', $fixed = false)
 {
     $image = new Imagick($this->file);
     $image->setBackgroundColor(new ImagickPixel('transparent'));
     $image->setImageFormat($type);
     if ($fixed === true) {
         $newWidth = $size['width'];
         $newHeight = $size['height'];
     } else {
         $imageprops = $image->getImageGeometry();
         $width = $imageprops['width'];
         $height = $imageprops['height'];
         if ($width > $height) {
             $newHeight = $size['height'];
             $newWidth = $size['height'] / $height * $width;
         } else {
             $newWidth = $size['width'];
             $newHeight = $size['width'] / $width * $height;
         }
     }
     $image->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 1);
     $image->writeImage($file . '.' . $type);
     $image->clear();
     $image->destroy();
 }
Exemple #10
0
function alfath_svg_compiler($options)
{
    global $wp_filesystem;
    if (!class_exists('Imagick')) {
        return new WP_Error('class_not_exist', 'Your server not support imagemagick');
    }
    $im = new Imagick();
    $im->setBackgroundColor(new ImagickPixel('transparent'));
    if (empty($wp_filesystem)) {
        require_once ABSPATH . '/wp-admin/includes/file.php';
        WP_Filesystem();
    }
    $file = get_template_directory() . '/assets/img/nav.svg';
    $target = get_template_directory() . '/assets/img/nav-bg.png';
    if ($wp_filesystem->exists($file)) {
        //check for existence
        $svg = $wp_filesystem->get_contents($file);
        if (!$svg) {
            return new WP_Error('reading_error', 'Error when reading file');
        }
        //return error object
        $svg = preg_replace('/fill="#([0-9a-f]{6})"/', 'fill="' . $options['secondary-color'] . '"', $svg);
        $im->readImageBlob($svg);
        $im->setImageFormat("png24");
        $im->writeImage($target);
        $im->clear();
        $im->destroy();
    } else {
        return new WP_Error('not_found', 'File not found');
    }
}
Exemple #11
0
 function imagick_thumbnail($image, $timage, $ext, $thumbnail_name, $imginfo)
 {
     try {
         $imagick = new Imagick();
         $fullpath = "./" . $this->thumbnail_path . "/" . $timage[0] . "/" . $thumbnail_name;
         if ($ext == "gif") {
             $imagick->readImage($image . '[0]');
         } else {
             $imagick->readImage($image);
         }
         $info = $imagick->getImageGeometry();
         $this->info[0] = $info['width'];
         $this->info[1] = $info['height'];
         $imagick->thumbnailImage($this->dimension, $this->dimension, true);
         if ($ext == "png" || $ext == "gif") {
             $white = new Imagick();
             $white->newImage($this->dimension, $this->dimension, "white");
             $white->compositeimage($image, Imagick::COMPOSITE_OVER, 0, 0);
             $white->writeImage($fullpath);
             $white->clear();
         } else {
             $imagick->writeImage($fullpath);
         }
         $imagick->clear();
     } catch (Exception $e) {
         echo "Unable to load image." . $e->getMessage();
         return false;
     }
     return true;
 }
 /**
  * Apply the transformer on the absolute path and return an altered version of it.
  *
  * @param string $absolutePath
  *
  * @return string|false
  */
 public function apply($absolutePath)
 {
     $info = pathinfo($absolutePath);
     if (isset($info['extension']) && false !== strpos(strtolower($info['extension']), 'pdf') && file_exists($absolutePath)) {
         // If it doesn't exist yet, extract the first page of the PDF
         $previewFilename = $this->getPreviewFilename($absolutePath);
         if (!file_exists($previewFilename)) {
             $this->imagick->readImage($absolutePath . '[0]');
             $this->imagick->setImageFormat('jpg');
             $this->imagick->flattenimages();
             $this->imagick->writeImage($previewFilename);
             $this->imagick->clear();
         }
         $absolutePath = $previewFilename;
     }
     return $absolutePath;
 }
Exemple #13
0
 /**
  * @return  void
  */
 protected function destroy()
 {
     if ($this->resource) {
         $this->resource->clear();
         $this->resource->destroy();
         $this->resource = null;
     }
 }
 function _resize_image($image_path, $max_width = 100, $max_height = 100)
 {
     $imagick = new \Imagick(realpath($image_path));
     $imagick->thumbnailImage($max_width, $max_height, true);
     $blob = $imagick->getImageBlob();
     $imagick->clear();
     return $blob;
 }
Exemple #15
0
 public function testImageThumbnail()
 {
     var_dump("123 Inside Image Thumbnail");
     $thumb = new \Imagick('/home/vagrant/www/consult-api/app/myimage.jpg');
     $thumb->scaleImage(200, 200, 1);
     $thumb->writeImage('/home/vagrant/www/consult-api/app/mythumb.jpg');
     $thumb->clear();
     $thumb->destroy();
 }
 public function it_should_be_able_to_load_metadata(Filesystem $filesystem, \Imagick $imagick)
 {
     $file = new LocalFile($this->file);
     $imagick->readimage($this->file)->shouldBeCalled();
     $imagick->identifyimage()->willReturn(['key' => 'value']);
     $imagick->getimageproperties('*SpotColor*')->willReturn([1]);
     $imagick->clear()->shouldBeCalled();
     $this->getMetadataForFile($file, ['extended' => true])->shouldReturn(['key' => 'value', 'hasSpotColors' => true]);
 }
Exemple #17
0
 /**
  * 处理图片,不改变分辨率,减少图片文件大小
  * @param  [string] $src  原图路径
  * @param  [int] [图片质量]
  * @param  [string] $dest 目标图路径
  * @return [void] 
  */
 public function tinyJpeg($src, $quality = 60, $dest)
 {
     $img = new Imagick();
     $img->readImage($src);
     $img->setImageCompression(Imagick::COMPRESSION_JPEG);
     $img->setImageCompressionQuality($quality);
     $img->stripImage();
     $img->writeImage($dest);
     $img->clear();
 }
Exemple #18
0
 function createMedium($url, $filename, $width, $height)
 {
     # Function creates a smaller version of a photo when its size is bigger than a preset size
     # Excepts the following:
     # (string) $url = Path to the photo-file
     # (string) $filename = Name of the photo-file
     # (int) $width = Width of the photo
     # (int) $height = Height of the photo
     # Returns the following
     # (boolean) true = Success
     # (boolean) false = Failure
     # Set to true when creation of medium-photo failed
     global $settings;
     $error = false;
     # Size of the medium-photo
     # When changing these values,
     # also change the size detection in the front-end
     global $newWidth;
     global $newHeight;
     # Check permissions
     if (hasPermissions(LYCHEE_UPLOADS_MEDIUM) === false) {
         # Permissions are missing
         $error = true;
         echo 'Not enough persmission on the medium folder' . "\n";
     }
     # Is photo big enough?
     # Is Imagick installed and activated?
     if ($error === false && ($width > $newWidth || $height > $newHeight) && (extension_loaded('imagick') && $settings['imagick'] === '1')) {
         $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename;
         # Read image
         $medium = new Imagick();
         $medium->readImage(LYCHEE . $url);
         # Adjust image
         $medium->scaleImage($newWidth, $newHeight, true);
         # Save image
         try {
             $medium->writeImage($newUrl);
         } catch (ImagickException $err) {
             Log::notice($database, __METHOD__, __LINE__, 'Could not save medium-photo: ' . $err->getMessage());
             $error = true;
             echo 'Imagick Exception:' . "\n";
             var_dump($e);
         }
         $medium->clear();
         $medium->destroy();
     } else {
         # Photo too small or
         # Imagick not installed
         $error = true;
     }
     if ($error === true) {
         return false;
     }
     return true;
 }
 public function run($file, $temp_dir)
 {
     $image = new Imagick();
     $image->readImage($file);
     $image->setImageUnits(Imagick::RESOLUTION_PIXELSPERINCH);
     $image->setImageResolution($this->settings['resolution'], $this->settings['resolution']);
     $image->writeImage($file);
     $image->clear();
     $image->destroy();
     return TRUE;
 }
Exemple #20
0
function loadDir($path)
{
    if ($handle = opendir($path)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." and $file != "..") {
                //skip . and ..
                if (is_file($path . '/' . $file)) {
                    $tmpFile = trim($file);
                    $ext = pathinfo($file, PATHINFO_EXTENSION);
                    $File = pathinfo($file, PATHINFO_FILENAME);
                    $valid_exts = array('jpeg', 'JPEG', 'jpg', 'JPG', 'png', 'PNG', 'gif', 'GIF');
                    $sizes = array('f' => 45, 't' => 92, 's' => 120, 'm' => 225, 'l' => 300);
                    //required sizes in WxH ratio
                    if (in_array($ext, $valid_exts)) {
                        // if file is image then process it!
                        foreach ($sizes as $w => $h) {
                            $image = new Imagick();
                            $image->readImage($path . '/' . $tmpFile);
                            $imgWidth = $image->getImageWidth();
                            $imgHeight = $image->getImageHeight();
                            $image->resizeImage($h, $h, Imagick::FILTER_LANCZOS, 1);
                            // resize from array sizes
                            $fileName .= $File . '_' . $w . '.' . $ext;
                            //create the image filaname
                            $image->writeImage($path . '/' . $fileName);
                            $tempFileName = $path . '/' . $fileName;
                            $arrayfiles[] = $tempFileName;
                            $custWidth = $image->getImageWidth();
                            $custHeight = $image->getImageHeight();
                            echo "[ Original dimension : {$imgWidth} x {$imgHeight} ] [ Custom dimension : {$custWidth} x {$custHeight} ] Output image location: <a href='{$tempFileName}' style='text-decoration:none'> " . $tempFileName . "</a>&nbsp;&nbsp;";
                            echo "<img class='img' src='{$tempFileName}' /></br>";
                            $w = '';
                            $h = '';
                            $fileName = '';
                            $image->clear();
                            $image->destroy();
                        }
                        //end foreach sizes
                    }
                }
                if (is_dir($path . '/' . $file)) {
                    echo '</br> <div style="height:0;width:1200px;border:0;border-bottom:2px;border-style: dashed;border-color: #000000"></div><span style="font-weight:bold; font-size:14px; color:red ">Directory Name: ';
                    echo $path . "/" . $file;
                    echo '</span><div style="height:0;width:1200px;border:0;border-bottom:2px;border-style: dashed;border-color: #000000"></div></br>';
                    loadDir($path . '/' . $file);
                }
            }
        }
        // end while
    }
    // end handle
}
 protected function _imageResizeAndSave($object)
 {
     $path = APPLICATION_ROOT . '/public_html/images/topcontentblock/';
     $system->lng = $this->_getParam('lng');
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($path);
     $adapter->setOptions(array('ignoreNoFile' => true));
     if (!$adapter->receive()) {
         $msgr = Sanmax_MessageStack::getInstance('SxModule_Topcontentblock_Validator');
         $msgr->addMessage('file', $adapter->getMessages(), 'title');
     }
     if ($object->getPicture() == null) {
         $object->setPicture('');
     }
     $files = $adapter->getFileInfo();
     foreach ($files as $file) {
         if (!$file['tmp_name']) {
             continue;
         }
         $path0 = $path . "253X115/";
         $path1 = $path . "1263X575/";
         $path2 = $path . "1263X325/";
         $filename = $object->createThumbName($file['name']) . '_' . time() . '.jpg';
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(253, 115);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(100);
         $image->setImageFormat('jpeg');
         $image->writeImage($path0 . $filename);
         $image->clear();
         $image->destroy();
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(1263, 575);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(75);
         $image->setImageFormat('jpeg');
         $image->writeImage($path1 . $filename);
         $image->clear();
         $image->destroy();
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(1263, 325);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(75);
         $image->setImageFormat('jpeg');
         $image->writeImage($path2 . $filename);
         $image->clear();
         $image->destroy();
         unlink($file['tmp_name']);
         $object->setPicture($filename);
     }
 }
 protected function _imageResizeAndSave($object)
 {
     $path = APPLICATION_ROOT . '/public_html/images/eyecatchers/';
     $system->lng = $this->_getParam('lng');
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($path);
     $adapter->setOptions(array('ignoreNoFile' => true));
     if (!$adapter->receive()) {
         $msgr = Sanmax_MessageStack::getInstance('SxModule_Eyecatchers_Validator');
         $msgr->addMessage('file', $adapter->getMessages(), 'title');
     }
     if ($object->getPicture() == null) {
         $object->setPicture('');
     }
     $files = $adapter->getFileInfo();
     foreach ($files as $file) {
         if (!$file['tmp_name']) {
             continue;
         }
         $path0 = $path . "253x115/";
         $path1 = $path . "980x450/";
         if (!is_dir($path0)) {
             mkdir($path0, 0777, true);
         }
         if (!is_dir($path1)) {
             mkdir($path1, 0777, true);
         }
         $filename = $object->createThumbName($file['name']) . '_' . time() . '.png';
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(253, 115);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(100);
         $image->setBackgroundColor(new ImagickPixel('transparent'));
         $image->setImageFormat('png32');
         $image->writeImage($path0 . $filename);
         $image->clear();
         $image->destroy();
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(980, 450);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(75);
         $image->setBackgroundColor(new ImagickPixel('transparent'));
         $image->setImageFormat('png32');
         $image->writeImage($path1 . $filename);
         $image->clear();
         $image->destroy();
         unlink($file['tmp_name']);
         $object->setPicture($filename);
     }
 }
Exemple #23
0
function getDownloadImage($type, $file, $sottoCat, $nome_brand, $nome_colore, $id)
{
    $file_path = "";
    // estensione foto
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if (strtolower($ext) == "jpg") {
        // recupero il numero della foto
        $punto = strrpos($file, ".");
        $file_new = substr($file, 0, $punto);
        // il numero dell'immagine
        $numero_img = substr($file_new, strlen($file_new) - 1, 1);
        $nome_file = replace_accents(url_slug(strtolower($sottoCat))) . "_" . replace_accents(url_slug(strtolower($nome_brand))) . "_" . replace_accents(url_slug(strtolower($nome_colore))) . "_" . replace_accents(url_slug(strtolower($id))) . "-" . $numero_img . "." . $ext;
        $import_location = "../../var/images";
        $file_source = Mage::getStoreConfig('oscommerceimportconf/oscconfiguration/conf_imageurl', Mage::app()->getStore()) . $file;
        $file_target = $import_location . "/" . $nome_file;
        $file_source = str_replace(" ", "%20", $file_source);
        if ($file != '' and !file_exists($file_target)) {
            $rh = fopen($file_source, 'rb');
            $wh = fopen($file_target, 'wb');
            if ($rh === false || $wh === false) {
                // error reading or opening file
                $file_path = "";
            } else {
                while (!feof($rh)) {
                    if (fwrite($wh, fread($rh, 1024)) === FALSE) {
                        $file_path = $file_target;
                    }
                }
            }
            fclose($rh);
            fclose($wh);
        }
        if (file_exists($file_target)) {
            if ($type == 'category') {
                $file_path = $file;
            } else {
                $file_path = $file_target;
            }
        }
        if (filesize($file_path) > 0) {
            $img = new Imagick();
            $img->clear();
            $img->readImage($file_path);
            $img->setOption('jpeg:extent', '180kb');
            $img->writeImage($file_path);
        }
    }
    return $file_path;
}
Exemple #24
0
 public function watermark($file, $mark_image, $set)
 {
     $image = new Imagick();
     $image->readImage($file);
     $watermark = new Imagick();
     $watermark->readImage($mark_image);
     $opacity = isset($set['wm_opacity']) ? (int) $set['wm_opacity'] : 100;
     $watermark->setImageOpacity($opacity / 100);
     $image->compositeImage($watermark, imagick::COMPOSITE_DEFAULT, $set['dest_x'], $set['dest_y']);
     $image->writeImage();
     $image->clear();
     $image->destroy();
     $watermark->clear();
     $watermark->destroy();
 }
	/**
	 * Resize multiple images from a single source.
	 *
	 * @since 3.5.0
	 * @access public
	 *
	 * @param array $sizes {
	 *     An array of image size arrays. Default sizes are 'small', 'medium', 'large'.
	 *
	 *     Either a height or width must be provided.
	 *     If one of the two is set to null, the resize will
	 *     maintain aspect ratio according to the provided dimension.
	 *
	 *     @type array $size {
	 *         @type int  ['width']  Optional. Image width.
	 *         @type int  ['height'] Optional. Image height.
	 *         @type bool $crop   Optional. Whether to crop the image. Default false.
	 *     }
	 * }
	 * @return array An array of resized images' metadata by size.
	 */
	public function multi_resize( $sizes ) {
		$metadata = array();
		$orig_size = $this->size;
		$orig_image = $this->image->getImage();

		foreach ( $sizes as $size => $size_data ) {
			if ( ! $this->image )
				$this->image = $orig_image->getImage();

			if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
				continue;
			}

			if ( ! isset( $size_data['width'] ) ) {
				$size_data['width'] = null;
			}
			if ( ! isset( $size_data['height'] ) ) {
				$size_data['height'] = null;
			}

			if ( ! isset( $size_data['crop'] ) ) {
				$size_data['crop'] = false;
			}

			$resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
			$duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );

			if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
				$resized = $this->_save( $this->image );

				$this->image->clear();
				$this->image->destroy();
				$this->image = null;

				if ( ! is_wp_error( $resized ) && $resized ) {
					unset( $resized['path'] );
					$metadata[$size] = $resized;
				}
			}

			$this->size = $orig_size;
		}

		$this->image = $orig_image;

		return $metadata;
	}
Exemple #26
0
 /**
  * Draw the border.
  *
  * This draws the configured border to the provided image. Beware,
  * that every pixel inside the border clipping will be overwritten
  * with the background color.
  */
 public function apply()
 {
     foreach ($this->_params['images'] as $image) {
         $topimg = new Imagick();
         $topimg->clear();
         $topimg->readImageBlob($image->raw());
         /* Calculate center for composite (gravity center)*/
         $geometry = $this->_image->imagick->getImageGeometry();
         $x = $geometry['width'] / 2;
         $y = $geometry['height'] / 2;
         if (isset($this->_params['x']) && isset($this->_params['y'])) {
             $x = $this->_params['x'];
             $y = $this->_params['y'];
         }
         $this->_image->_imagick->compositeImage($topimg, Imagick::COMPOSITE_OVER, $x, $y);
     }
     return true;
 }
Exemple #27
0
 /**
  * Resizes an image image
  * @return boolean
  */
 public function resize()
 {
     try {
         // Create new Image object //
         $im = new Imagick($this->image->get('image_path'));
         // Resize the image //
         $im->scaleimage($this->image->get('height'), $this->image->get('width'));
         // Grab the output from writing the image to disk //
         $return = $im->writeimage($this->image->get('resized_path'));
         // Clean up memory //
         $im->clear();
         $im->destroy();
         // $return only returns true if image is written //
         return $return ? true : false;
     } catch (Exception $e) {
         $this->log->exceptionLog($e, __METHOD__);
     }
 }
Exemple #28
0
 public function addUploadImage($image)
 {
     $systemPath = public_path() . '/' . $this->imgDir . '/';
     $imageName = $this->id . '-' . $image->getClientOriginalName();
     $image->move($systemPath, $imageName);
     $maxHeight = 100;
     $maxWidth = 100;
     $newHeight = 0;
     $newWidth = 0;
     $inputFile = public_path() . "/img/img-upload/{$imageName}";
     $newImageName = substr($imageName, 0, strlen($imageName) - 4) . "-small.jpg";
     $outputFile = public_path() . "/img/img-upload/{$newImageName}";
     // load the image to be manipulated
     $image = new Imagick($inputFile);
     // get the current image dimensions
     $currentWidth = $image->getImageWidth();
     $currentHeight = $image->getImageHeight();
     // determine what the new height and width should be based on the type of photo
     if ($currentWidth > $currentHeight) {
         // landscape photo
         // width should be resized to max and height should be resized proportionally
         $newWidth = $maxWidth;
         $newHeight = ceil($currentHeight * ($newWidth / $currentWidth));
     } else {
         if ($currentHeight > $currentWidth) {
             // portrait photo
             // height should be resized to max and width should be resized proportionally
             $newHeight = $maxHeight;
             $newWidth = ceil($currentWidth * ($newHeight / $currentHeight));
         } else {
             // square photo
             // resize image to max dimensions
             $newHeight = $newWidth = $maxHeight;
         }
     }
     // perform the image resize
     $image->resizeImage($newWidth, $newHeight, Imagick::FILTER_LANCZOS, true);
     // write out the new image
     $image->writeImage($outputFile);
     // clear memory resources
     $image->clear();
     $image->destroy();
     $this->user_pic_path = '/' . $this->imgDir . '/' . $newImageName;
 }
 public function wp_generate_attachment_metadata($data)
 {
     global $_wp_additional_image_sizes;
     $upload_dir = wp_upload_dir()['basedir'] . '/';
     foreach ($_wp_additional_image_sizes as $k => $size) {
         if (array_key_exists('padded', $size) && $size['padded']) {
             // Check the image has an incorrect aspect ratio
             list($width, $height) = getimagesize($orig_file = $upload_dir . $data['file']);
             if (round($size['height'] * $width / $height) == $size['width']) {
                 continue;
             }
             // Scale image down
             $im = new Imagick($orig_file);
             $im->setImageFormat('png');
             $im->scaleImage($size['width'], $size['height'], true);
             // Get new width & height
             $width = $im->getImageWidth();
             $height = $im->getImageHeight();
             // Save temporary version
             $im->writeImage($orig_file . '.tmp');
             $im->clear();
             $im->destroy();
             // Create the padded version
             $im = imagecreatetruecolor($size['width'], $size['height']);
             imagesavealpha($im, true);
             imagefill($im, 0, 0, imagecolorallocatealpha($im, 0, 0, 0, 127));
             imagecopy($im, $tmp = imagecreatefrompng($orig_file . '.tmp'), round(($size['width'] - $width) / 2), round(($size['height'] - $height) / 2), 0, 0, $width, $height);
             imagedestroy($tmp);
             imagepng($im, $file = $upload_dir . dirname($data['file']) . '/' . ($filename = basename($data['file'], '.' . pathinfo($data['file'])['extension']) . '-' . $size['width'] . 'x' . $size['height'] . '.png'));
             imagedestroy($im);
             // Destroy the temporary version
             unlink($orig_file . '.tmp');
             // Update metadata
             if (!array_key_exists($k, $data['sizes'])) {
                 $data['sizes'][$k] = [];
             }
             $data['sizes'][$k]['file'] = $filename;
             $data['sizes'][$k]['height'] = $size['height'];
             $data['sizes'][$k]['mime-type'] = 'image/png';
             $data['sizes'][$k]['width'] = $size['width'];
         }
     }
     return $data;
 }
Exemple #30
0
function fl_text_render($_file, $id, $text, $fontname, $fontsize, $color = "#000000", $out_image_file_type = "png")
{
    $font = locate_font($fontname);
    if ($font === false) {
        fllog('fl_text_render: font `' . $fontname . '` not found at `' . flvault . $fontname . '`');
        return false;
    }
    $render = false;
    $out_image_file_type = strtolower($out_image_file_type);
    $cachefile = flcache . $id . '.' . $out_image_file_type;
    if ($_file !== false) {
        if (file1_is_older($cachefile, $_file)) {
            $render = true;
        }
    } else {
        $render = true;
    }
    if ($render === true) {
        try {
            $draw = new ImagickDraw();
            $draw->setFont($font);
            $draw->setFontSize(intval($fontsize));
            $draw->setGravity(Imagick::GRAVITY_CENTER);
            $draw->setFillColor($color);
            $canvas = new Imagick();
            $m = $canvas->queryFontMetrics($draw, htmlspecialchars_decode($text));
            $canvas->newImage($m['textWidth'], $m['textHeight'], "transparent", $out_image_file_type);
            $canvas->annotateImage($draw, 0, 0, 0, $text);
            $canvas->setImageFormat(strtoupper($out_image_file_type));
            $canvas->writeImage($cachefile);
            fllog('Writing to: ' . $cachefile);
            $canvas->clear();
            $canvas->destroy();
            $draw->clear();
            $draw->destroy();
        } catch (Exception $e) {
            fllog('fl_text_render() Error: ', $e->getMessage());
            return false;
        }
    }
    return $cachefile;
}