Exemple #1
2
function IMAGEN_tipo_normal()
{
    $escalado = 'IMG/i/m/' . $_GET['ancho'] . '_' . $_GET['alto'] . '_' . $_GET['sha1'];
    $origen = 'IMG/i/' . $_GET['sha1'];
    $ancho = $_GET['ancho'];
    $alto = $_GET['alto'];
    if (@($ancho * $alto) > 562500) {
        die('La imagen solicitada excede el límite de este servicio');
    }
    if (!file_exists($escalado)) {
        $im = new Imagick($origen);
        $im->setCompression(Imagick::COMPRESSION_JPEG);
        $im->setCompressionQuality(85);
        $im->setImageFormat('jpeg');
        $im->stripImage();
        $im->despeckleImage();
        $im->sharpenImage(0.5, 1);
        //$im->reduceNoiseImage(0);
        $im->setInterlaceScheme(Imagick::INTERLACE_PLANE);
        $im->resizeImage($ancho, $alto, imagick::FILTER_LANCZOS, 1);
        $im->writeImage($escalado);
        $im->destroy();
    }
    $im = new Imagick($escalado);
    $output = $im->getimageblob();
    $outputtype = $im->getFormat();
    $im->destroy();
    header("Content-type: {$outputtype}");
    header("Content-length: " . filesize($escalado));
    echo $output;
}
 /**
  * Saves the image to a file
  *
  * @param $filename string the name of the file to write to
  *
  * @return bool|PEAR_Error TRUE or a PEAR_Error object on error
  * @access public
  */
 function save($filename, $type = '', $quality = null)
 {
     $options = is_array($quality) ? $quality : array();
     if (is_numeric($quality)) {
         $options['quality'] = $quality;
     }
     $quality = $this->_getOption('quality', $options, 75);
     // PIMCORE_MODIFICATION
     $this->imagick->setCompressionQuality($quality);
     $this->imagick->setImageCompressionQuality($quality);
     if ($type && strcasecmp($type, $this->type)) {
         try {
             $this->imagick->setImageFormat($type);
         } catch (ImagickException $e) {
             return $this->raiseError('Could not save image to file (conversion failed).', IMAGE_TRANSFORM_ERROR_FAILED);
         }
     }
     try {
         $this->imagick->writeImage($filename);
     } catch (ImagickException $e) {
         return $this->raiseError('Could not save image to file: ' . $e->getMessage(), IMAGE_TRANSFORM_ERROR_IO);
     }
     if (!$this->keep_settings_on_save) {
         $this->free();
     }
     return true;
 }
 public function run($file, $temp_dir)
 {
     $info = $this->getImageDetails($file);
     $image = new Imagick();
     $image->readImage($file);
     if ($info['ext'] == 'jpg') {
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setCompressionQuality($this->settings['quality']);
         $image->setImageFormat('jpeg');
     }
     if ($info['ext'] == 'gif') {
         //remove the canvas (for .gif)
         $image->setImagePage(0, 0, 0, 0);
     }
     //crop and resize the image
     $image->resizeImage($this->settings['width'], $this->settings['height'], Imagick::FILTER_LANCZOS, 1, true);
     $image->writeImage($file);
     return TRUE;
 }
 public function generateMosaic($input_path, $libraries = array())
 {
     if (empty($libraries)) {
         throw new \RuntimeException('At least one metapixel library needs to be used.');
     }
     if (!is_file($input_path)) {
         throw new \RuntimeException(sprintf('%s does not exist or could not be read.', $input_path));
     }
     $opts = '';
     foreach ($libraries as $library) {
         $path = $this->library_path . '/' . $library;
         $opts .= "--library {$path} ";
     }
     $opts = rtrim($opts);
     $path_parts = pathinfo($input_path);
     $output_path = $path_parts['dirname'] . '/tmp_metapixel_' . uniqid() . '.png';
     $process = new Process("metapixel {$opts} --metapixel {$input_path} {$output_path} --scale={$this->scale}");
     $process->setTimeout(null);
     $process->run();
     if (!$process->isSuccessful()) {
         throw new \RuntimeException($process->getErrorOutput());
     }
     $im = new \Imagick($output_path);
     $width = floor($im->getImageWidth() / $this->scale);
     $height = floor($im->getImageHeight() / $this->scale);
     $im->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1);
     $im->setImageFormat('jpg');
     $im->setCompressionQuality(90);
     $mosaic_path = preg_replace('/\\.png$/', '_converted.jpg', $output_path);
     $im->writeImage($mosaic_path);
     $_id = $this->mosaic_repository->storeMosaic($mosaic_path, array('mimetype' => 'image/jpeg', 'width' => $width, 'height' => $height));
     unlink($input_path);
     unlink($output_path);
     unlink($mosaic_path);
     return $_id;
 }
 function save($file_name = null, $quality = null)
 {
     $type = $this->out_type;
     if (!$type) {
         $type = $this->img_type;
     }
     if (!self::supportSaveType($type)) {
         throw new lmbImageTypeNotSupportedException($type);
     }
     $this->img->setImageFormat($type);
     $this->img->setImageFilename($file_name);
     if (!is_null($quality) && strtolower($type) == 'jpeg') {
         if (method_exists($this->img, 'setImageCompression')) {
             $this->img->setImageCompression(imagick::COMPRESSION_JPEG);
             $this->img->setImageCompressionQuality($quality);
         } else {
             $this->img->setCompression(imagick::COMPRESSION_JPEG);
             $this->img->setCompressionQuality($quality);
         }
     }
     if (!$this->img->writeImage($file_name)) {
         throw new lmbImageSaveFailedException($file_name);
     }
     $this->destroyImage();
 }
Exemple #6
0
 /**
  * @param  $path
  */
 public function save($path, $format = null, $quality = null)
 {
     if (!$format) {
         $format = "png";
     }
     $this->resource->stripimage();
     $this->resource->setImageFormat($format);
     if ($quality) {
         $this->resource->setCompressionQuality((int) $quality);
         $this->resource->setImageCompressionQuality((int) $quality);
     }
     $this->resource->writeImage($path);
     return $this;
 }
Exemple #7
0
 /**
  * Associates the model with the file
  * @param string $filePath
  * @return boolean
  */
 public function setFile($filePath)
 {
     if (!file_exists($filePath)) {
         return false;
     }
     $info = getimagesize($filePath);
     $imageWidth = $info[0];
     $imageHeight = $info[1];
     $image = new Imagick();
     $image->readimage($filePath);
     $image->setResourceLimit(Imagick::RESOURCETYPE_MEMORY, 1);
     $maxSize = 1920;
     if ($imageWidth > $maxSize && $imageWidth > $imageHeight) {
         $image->thumbnailimage($maxSize, null);
     } elseif ($imageHeight > $maxSize && $imageHeight > $imageWidth) {
         $image->thumbnailimage(null, $maxSize);
     }
     $image->setCompression(Imagick::COMPRESSION_JPEG);
     $image->setCompressionQuality(80);
     $image->stripimage();
     $this->size = filesize($filePath);
     $this->type = $info['mime'];
     $this->width = $info[0];
     $this->height = $info[1];
     $this->content = $image->getImageBlob();
     $this->expireAt(time() + static::EXP_DAY);
     return true;
 }
 /**
  * @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;
 }
Exemple #9
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 #10
0
 private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4, $format = "png", $quality = 85, $filename = FALSE, $save = TRUE, $print = false)
 {
     $imgH = count($frame);
     $imgW = strlen($frame[0]);
     $col[0] = new \ImagickPixel("white");
     $col[1] = new \ImagickPixel("black");
     $image = new \Imagick();
     $image->newImage($imgW, $imgH, $col[0]);
     $image->setCompressionQuality($quality);
     $image->setImageFormat($format);
     $draw = new \ImagickDraw();
     $draw->setFillColor($col[1]);
     for ($y = 0; $y < $imgH; $y++) {
         for ($x = 0; $x < $imgW; $x++) {
             if ($frame[$y][$x] == '1') {
                 $draw->point($x, $y);
             }
         }
     }
     $image->drawImage($draw);
     $image->borderImage($col[0], $outerFrame, $outerFrame);
     $image->scaleImage(($imgW + 2 * $outerFrame) * $pixelPerPoint, 0);
     if ($save) {
         if ($filename === false) {
             throw new Exception("QR Code filename can't be empty");
         }
         $image->writeImages($filename, true);
     }
     if ($print) {
         Header("Content-type: image/" . $format);
         echo $image;
     }
 }
function convert_to_IMG($attachment, $options)
{
    $path = get_path($attachment);
    $dir = get_dir($attachment);
    $basename = get_basename($attachment);
    $converted_images = array();
    $max_width = $options['max_width'] ? (int) $options['max_width'] : 0;
    $max_height = $options['max_height'] ? (int) $options['max_height'] : 0;
    $img_extension = $options['img_extension'] ? $options['img_extension'] : 'jpg';
    $pages_to_convert = $options["pages_to_convert"] ? (int) $options["pages_to_convert"] : 0;
    if ($pages_to_convert > 5) {
        $pages_to_convert = 5;
    }
    $pages_to_convert = $pages_to_convert - 1;
    $quality = $options['quality'] ? (int) $options['quality'] : 80;
    if ($quality > 100) {
        $quality = 100;
    }
    try {
        $imagick = new Imagick();
        $imagick->clear();
        $imagick->destroy();
        if ($options) {
            $imagick->setResolution(150, 150);
            $imagick->readimage($path);
            $imagick->setCompressionQuality($quality);
        } else {
            $imagick->setResolution(72, 72);
            $imagick->readimage($path);
        }
        foreach ($imagick as $c => $_page) {
            if ($pages_to_convert == -1 || $c <= $pages_to_convert) {
                $_page->setImageBackgroundColor('white');
                $_page->setImageFormat($img_extension);
                if ($max_width && $max_height) {
                    $_page->adaptiveResizeImage($max_width, $max_height, true);
                }
                $blankPage = new \Imagick();
                $blankPage->newPseudoImage($_page->getImageWidth(), $_page->getImageHeight(), "canvas:white");
                $blankPage->compositeImage($_page, \Imagick::COMPOSITE_OVER, 0, 0);
                if ($blankPage->writeImage($dir . "/" . $basename . '-' . $c . '.' . $img_extension)) {
                    array_push($converted_images, $dir . "/" . $basename . '-' . $c . '.' . $img_extension);
                }
                $blankPage->clear();
                $blankPage->destroy();
            }
        }
    } catch (ImagickException $e) {
        $converted_images = false;
    } catch (Exception $e) {
        $converted_images = false;
    }
    return $converted_images;
}
Exemple #12
0
 function makeThumbnailtoFile($destFile)
 {
     $returnVal = false;
     if (!$this->isWorking()) {
         return false;
     }
     $image = new Imagick($this->sourceFile);
     $image->setCompressionQuality($this->thumbQuality);
     $image->thumbnailImage($this->thumbWidth, $this->thumbHeight);
     $returnVal = $image->writeImage($destFile);
     unset($image);
     return $returnVal;
 }
Exemple #13
0
function using_imagick()
{
    global $image, $mask, $clut, $final, $qual;
    $im = new Imagick($image);
    # Apply color lookup table
    $im->clutImage(new Imagick($clut));
    # Apply transparency mask
    $im->compositeImage(new Imagick($mask), imagick::COMPOSITE_COPYOPACITY, 0, 0);
    # Save the image
    $im->setCompressionQuality($qual);
    $im->setImageDepth(8);
    $im->setFormat("png");
    $im->writeImage($final);
}
 public function storeBase64Image($name, $dir, $fileContentBase64)
 {
     $uploadDir = $this->rootDir . '/../web' . $dir;
     if (!is_dir($uploadDir)) {
         mkdir($uploadDir, 0777, true);
     }
     $image = new \Imagick();
     $data = explode(',', $fileContentBase64);
     $fileContent = base64_decode($data[1]);
     $image->readImageBlob($fileContent);
     $filename = $name . "." . time() . '.jpg';
     $image->setImageFormat('jpeg');
     $image->setCompression(\Imagick::COMPRESSION_JPEG);
     $image->setCompressionQuality(50);
     $image->writeImage($uploadDir . $filename);
     return $filename;
 }
Exemple #15
0
function Imagen__CrearMiniatura($Origen, $Destino, $Ancho = 100, $Alto = 100)
{
    $im = new Imagick($Origen);
    $im->setImageColorspace(255);
    $im->setCompression(Imagick::COMPRESSION_JPEG);
    $im->setCompressionQuality(80);
    $im->setImageFormat('jpeg');
    list($newX, $newY) = scaleImage($im->getImageWidth(), $im->getImageHeight(), $Ancho, $Alto);
    $im->thumbnailImage($newX, $newY, false);
    return $im->writeImage($Destino);
}
Exemple #16
0
$general->addAttribute("titulo", "Catalogo");
$general->addAttribute("pagina", "");
$pagina_actual = 1;
while ($f = mysql_fetch_assoc($r)) {
    $ref = $general->addChild('ref');
    //$ref->addAttribute("titulo",iconv('ISO-8859-1','UTF-8//TRANSLIT',$f['titulo']));
    $ref->addAttribute("titulo", $f['titulo']);
    $ref->addAttribute("pagina", $pagina_actual);
    $cp = 'SELECT foto, pc.titulo FROM flores_productos_categoria LEFT JOIN flores_producto_contenedor AS pc USING(codigo_producto) LEFT JOIN flores_producto_variedad USING(codigo_producto) WHERE codigo_categoria=' . $f['codigo_categoria'] . ' GROUP BY codigo_producto';
    $rp = db_consultar($cp);
    $pagina_actual += 1 + mysql_numrows($rp);
    while ($fp = mysql_fetch_assoc($rp)) {
        if (!file_exists('catalogo360/pages/' . $fp['foto'])) {
            $im = new Imagick('IMG/i/' . $fp['foto']);
            $im->setCompression(Imagick::COMPRESSION_JPEG);
            $im->setCompressionQuality(90);
            $im->setImageFormat('jpeg');
            $im->stripImage();
            $draw = new ImagickDraw();
            $pixel = new ImagickPixel('gray');
            $pixel->setColor('black');
            $draw->setFont('flower.ttf');
            $draw->setFontSize(30);
            $im->thumbnailImage(350, 525, false);
            $im->annotateImage($draw, 10, 45, 0, $fp['titulo']);
            $im->writeImage('catalogo360/pages/' . $fp['foto']);
            $im->clear();
            $im->destroy();
            unset($im);
        }
        $XMLP->pages->addChild('page', 'pages/' . $fp['foto']);
Exemple #17
0
	/**
	 * Puts an image in the page.
	 * The upper-left corner must be given.
	 * The dimensions can be specified in different ways:<ul>
	 * <li>explicit width and height (expressed in user unit)</li>
	 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
	 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
	 * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
	 * The format can be specified explicitly or inferred from the file extension.<br />
	 * It is possible to put a link on the image.<br />
	 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
	 * @param $file (string) Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg').
	 * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
	 * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
	 * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
	 * @param $link (mixed) URL or identifier returned by AddLink().
	 * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
	 * @param $resize (mixed) If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
	 * @param $dpi (int) dot-per-inch resolution used on resize
	 * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
	 * @param $ismask (boolean) true if this image is a mask, false otherwise
	 * @param $imgmask (mixed) image object returned by this function or false
	 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
	 * @param $fitbox (mixed) If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom).
	 * @param $hidden (boolean) If true do not display the image.
	 * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
	 * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
	 * @param $altimgs (array) Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
	 * @return image information
	 * @public
	 * @since 1.1
	 */
	public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false, $alt=false, $altimgs=array()) {
		if ($x === '') {
			$x = $this->x;
		}
		if ($y === '') {
			$y = $this->y;
		}
		// check page for no-write regions and adapt page margins if necessary
		list($x, $y) = $this->checkPageRegions($h, $x, $y);
		$cached_file = false; // true when the file is cached
		$exurl = ''; // external streams
		// check if we are passing an image as file or string
		if ($file[0] === '@') {
			// image from string
			$imgdata = substr($file, 1);
			$file = K_PATH_CACHE.'img_'.md5($imgdata);
			$fp = fopen($file, 'w');
			fwrite($fp, $imgdata);
			fclose($fp);
			unset($imgdata);
			$cached_file = true;
			$imsize = @getimagesize($file);
			if ($imsize === FALSE) {
				unlink($file);
				$cached_file = false;
			}
		} else { // image file
			if ($file{0} === '*') {
				// image as external stream
				$file = substr($file, 1);
				$exurl = $file;
			}
			// check if is local file
			if (!@file_exists($file)) {
				// encode spaces on filename (file is probably an URL)
				$file = str_replace(' ', '%20', $file);
			}
			if (@file_exists($file)) {
				// get image dimensions
				$imsize = @getimagesize($file);
			} else {
				$imsize = false;
			}
			if ($imsize === FALSE) {
				if (function_exists('curl_init')) {
					// try to get remote file data using cURL
					$cs = curl_init(); // curl session
					curl_setopt($cs, CURLOPT_URL, $file);
					curl_setopt($cs, CURLOPT_BINARYTRANSFER, true);
					curl_setopt($cs, CURLOPT_FAILONERROR, true);
					curl_setopt($cs, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($cs, CURLOPT_FOLLOWLOCATION, true);
					curl_setopt($cs, CURLOPT_CONNECTTIMEOUT, 5);
					curl_setopt($cs, CURLOPT_TIMEOUT, 30);
					curl_setopt($cs, CURLOPT_SSL_VERIFYPEER, false);
					curl_setopt($cs, CURLOPT_SSL_VERIFYHOST, false);
					curl_setopt($cs, CURLOPT_USERAGENT, 'TCPDF');
					$imgdata = curl_exec($cs);
					curl_close($cs);
					if ($imgdata !== FALSE) {
						// copy image to cache
						$file = K_PATH_CACHE.'img_'.md5($imgdata);
						$fp = fopen($file, 'w');
						fwrite($fp, $imgdata);
						fclose($fp);
						unset($imgdata);
						$cached_file = true;
						$imsize = @getimagesize($file);
						if ($imsize === FALSE) {
							unlink($file);
							$cached_file = false;
						}
					}
				} elseif (($w > 0) AND ($h > 0)) {
					// get measures from specified data
					$pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
					$ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
					$imsize = array($pw, $ph);
				}
			}
		}
		if ($imsize === FALSE) {
			if (substr($file, 0, -34) == K_PATH_CACHE.'msk') { // mask file
				// get measures from specified data
				$pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
				$ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
				$imsize = array($pw, $ph);
			} else {
				$this->Error('[Image] Unable to get image: '.$file);
			}
		}
		// get original image width and height in pixels
		list($pixw, $pixh) = $imsize;
		// calculate image width and height on document
		if (($w <= 0) AND ($h <= 0)) {
			// convert image size to document unit
			$w = $this->pixelsToUnits($pixw);
			$h = $this->pixelsToUnits($pixh);
		} elseif ($w <= 0) {
			$w = $h * $pixw / $pixh;
		} elseif ($h <= 0) {
			$h = $w * $pixh / $pixw;
		} elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
			if (strlen($fitbox) !== 2) {
				// set default alignment
				$fitbox = '--';
			}
			// scale image dimensions proportionally to fit within the ($w, $h) box
			if ((($w * $pixh) / ($h * $pixw)) < 1) {
				// store current height
				$oldh = $h;
				// calculate new height
				$h = $w * $pixh / $pixw;
				// height difference
				$hdiff = ($oldh - $h);
				// vertical alignment
				switch (strtoupper($fitbox{1})) {
					case 'T': {
						break;
					}
					case 'M': {
						$y += ($hdiff / 2);
						break;
					}
					case 'B': {
						$y += $hdiff;
						break;
					}
				}
			} else {
				// store current width
				$oldw = $w;
				// calculate new width
				$w = $h * $pixw / $pixh;
				// width difference
				$wdiff = ($oldw - $w);
				// horizontal alignment
				switch (strtoupper($fitbox{0})) {
					case 'L': {
						if ($this->rtl) {
							$x -= $wdiff;
						}
						break;
					}
					case 'C': {
						if ($this->rtl) {
							$x -= ($wdiff / 2);
						} else {
							$x += ($wdiff / 2);
						}
						break;
					}
					case 'R': {
						if (!$this->rtl) {
							$x += $wdiff;
						}
						break;
					}
				}
			}
		}
		// fit the image on available space
		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
		// calculate new minimum dimensions in pixels
		$neww = round($w * $this->k * $dpi / $this->dpi);
		$newh = round($h * $this->k * $dpi / $this->dpi);
		// check if resize is necessary (resize is used only to reduce the image)
		$newsize = ($neww * $newh);
		$pixsize = ($pixw * $pixh);
		if (intval($resize) == 2) {
			$resize = true;
		} elseif ($newsize >= $pixsize) {
			$resize = false;
		}
		// check if image has been already added on document
		$newimage = true;
		if (in_array($file, $this->imagekeys)) {
			$newimage = false;
			// get existing image data
			$info = $this->getImageBuffer($file);
			if (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
				// check if the newer image is larger
				$oldsize = ($info['w'] * $info['h']);
				if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
					$newimage = true;
				}
			}
		} elseif (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
			// check for cached images with alpha channel
			$filehash = md5($file);
			$tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
			$tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
			if (in_array($tempfile_plain, $this->imagekeys)) {
				// get existing image data
				$info = $this->getImageBuffer($tempfile_plain);
				// check if the newer image is larger
				$oldsize = ($info['w'] * $info['h']);
				if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
					$newimage = true;
				} else {
					$newimage = false;
					// embed mask image
					$imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
					// embed image, masked with previously embedded mask
					return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
				}
			}
		}
		if ($newimage) {
			//First use of image, get info
			$type = strtolower($type);
			if ($type == '') {
				$type = $this->getImageFileType($file, $imsize);
			} elseif ($type == 'jpg') {
				$type = 'jpeg';
			}
			$mqr = $this->get_mqr();
			$this->set_mqr(false);
			// Specific image handlers
			$mtd = '_parse'.$type;
			// GD image handler function
			$gdfunction = 'imagecreatefrom'.$type;
			$info = false;
			if ((method_exists($this, $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
				// TCPDF image functions
				$info = $this->$mtd($file);
				if ($info == 'pngalpha') {
					return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
				}
			}
			if (!$info) {
				if (function_exists($gdfunction)) {
					// GD library
					$img = $gdfunction($file);
					if ($resize) {
						$imgr = imagecreatetruecolor($neww, $newh);
						if (($type == 'gif') OR ($type == 'png')) {
							$imgr = $this->_setGDImageTransparency($imgr, $img);
						}
						imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
						if (($type == 'gif') OR ($type == 'png')) {
							$info = $this->_toPNG($imgr);
						} else {
							$info = $this->_toJPEG($imgr);
						}
					} else {
						if (($type == 'gif') OR ($type == 'png')) {
							$info = $this->_toPNG($img);
						} else {
							$info = $this->_toJPEG($img);
						}
					}
				} elseif (extension_loaded('imagick')) {
					// ImageMagick library
					$img = new Imagick();
					if ($type == 'SVG') {
						// get SVG file content
						$svgimg = file_get_contents($file);
						// get width and height
						$regs = array();
						if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
							$svgtag = $regs[1];
							$tmp = array();
							if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
								$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
								$owu = sprintf('%.3F', ($ow * $dpi / 72)).$this->pdfunit;
								$svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
							} else {
								$ow = $w;
							}
							$tmp = array();
							if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
								$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
								$ohu = sprintf('%.3F', ($oh * $dpi / 72)).$this->pdfunit;
								$svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
							} else {
								$oh = $h;
							}
							$tmp = array();
							if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
								$vbw = ($ow * $this->imgscale * $this->k);
								$vbh = ($oh * $this->imgscale * $this->k);
								$vbox = sprintf(' viewBox="0 0 %.3F %.3F" ', $vbw, $vbh);
								$svgtag = $vbox.$svgtag;
							}
							$svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
						}
						$img->readImageBlob($svgimg);
					} else {
						$img->readImage($file);
					}
					if ($resize) {
						$img->resizeImage($neww, $newh, 10, 1, false);
					}
					$img->setCompressionQuality($this->jpeg_quality);
					$img->setImageFormat('jpeg');
					$tempname = tempnam(K_PATH_CACHE, 'jpg_');
					$img->writeImage($tempname);
					$info = $this->_parsejpeg($tempname);
					unlink($tempname);
					$img->destroy();
				} else {
					return;
				}
			}
			if ($info === false) {
				//If false, we cannot process image
				return;
			}
			$this->set_mqr($mqr);
			if ($ismask) {
				// force grayscale
				$info['cs'] = 'DeviceGray';
			}
			$info['i'] = $this->numimages;
			if (!in_array($file, $this->imagekeys)) {
				++$info['i'];
			}
			if ($imgmask !== false) {
				$info['masked'] = $imgmask;
			}
			if (!empty($exurl)) {
				$info['exurl'] = $exurl;
			}
			// array of alternative images
			$info['altimgs'] = $altimgs;
			// add image to document
			$this->setImageBuffer($file, $info);
		}
		if ($cached_file) {
			// remove cached file
			unlink($file);
		}
		// set alignment
		$this->img_rb_y = $y + $h;
		// set alignment
		if ($this->rtl) {
			if ($palign == 'L') {
				$ximg = $this->lMargin;
			} elseif ($palign == 'C') {
				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
			} elseif ($palign == 'R') {
				$ximg = $this->w - $this->rMargin - $w;
			} else {
				$ximg = $x - $w;
			}
			$this->img_rb_x = $ximg;
		} else {
			if ($palign == 'L') {
				$ximg = $this->lMargin;
			} elseif ($palign == 'C') {
				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
			} elseif ($palign == 'R') {
				$ximg = $this->w - $this->rMargin - $w;
			} else {
				$ximg = $x;
			}
			$this->img_rb_x = $ximg + $w;
		}
		if ($ismask OR $hidden) {
			// image is not displayed
			return $info['i'];
		}
		$xkimg = $ximg * $this->k;
		if (!$alt) {
			// only non-alternative immages will be set
			$this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
		}
		if (!empty($border)) {
			$bx = $this->x;
			$by = $this->y;
			$this->x = $ximg;
			if ($this->rtl) {
				$this->x += $w;
			}
			$this->y = $y;
			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
			$this->x = $bx;
			$this->y = $by;
		}
		if ($link) {
			$this->Link($ximg, $y, $w, $h, $link, 0);
		}
		// set pointer to align the next text/objects
		switch($align) {
			case 'T': {
				$this->y = $y;
				$this->x = $this->img_rb_x;
				break;
			}
			case 'M': {
				$this->y = $y + round($h/2);
				$this->x = $this->img_rb_x;
				break;
			}
			case 'B': {
				$this->y = $this->img_rb_y;
				$this->x = $this->img_rb_x;
				break;
			}
			case 'N': {
				$this->SetY($this->img_rb_y);
				break;
			}
			default:{
				break;
			}
		}
		$this->endlinex = $this->img_rb_x;
		if ($this->inxobj) {
			// we are inside an XObject template
			$this->xobjects[$this->xobjid]['images'][] = $info['i'];
		}
		return $info['i'];
	}
Exemple #18
0
function reduire_image($userfile_name)
{
    global $pmb_vignette_x;
    global $pmb_vignette_y;
    global $base_path;
    global $pmb_curl_available;
    if (!$pmb_vignette_x) {
        $pmb_vignette_x = 100;
    }
    if (!$pmb_vignette_y) {
        $pmb_vignette_y = 100;
    }
    $src_image = '';
    if (file_exists("{$base_path}/temp/{$userfile_name}")) {
        $bidon = "{$base_path}/temp/{$userfile_name}";
        $source_file = $bidon . "[0]";
    } else {
        $bidon = $userfile_name;
        //Il s'agit d'une url, on copie le fichier en local
        $nom_temp = session_id() . microtime();
        $nom_temp = str_replace(' ', '_', $nom_temp);
        $nom_temp = str_replace('.', '_', $nom_temp);
        $fichier_tmp = "{$base_path}/temp/" . $nom_temp;
        if ($pmb_curl_available) {
            $aCurl = new Curl();
            $aCurl->save_file_name = $fichier_tmp;
            $aCurl->get($userfile_name);
        } else {
            $handle = fopen($userfile_name, "rb");
            $filecontent = stream_get_contents($handle);
            fclose($handle);
            $fd = fopen($fichier_tmp, "w");
            fwrite($fd, $filecontent);
            fclose($fd);
        }
        $source_file = $fichier_tmp . "[0]";
    }
    $error = true;
    if (extension_loaded('imagick')) {
        mysql_set_wait_timeout(3600);
        $error = false;
        try {
            $img = new Imagick();
            $img->readImage($source_file);
            if ($img->getImageWidth() > $pmb_vignette_x || $img->getImageHeight() > $pmb_vignette_y) {
                // Si l'image est trop grande on la réduit
                $img->thumbnailimage($pmb_vignette_x, $pmb_vignette_y, true);
            }
            $img->setImageFormat("png");
            $img->setCompression(Imagick::COMPRESSION_LZW);
            $img->setCompressionQuality(90);
            $contenu_vignette = $img->getImageBlob();
        } catch (Exception $ex) {
            $error = true;
        }
        unlink($fichier_tmp);
    }
    if ($error) {
        $size = @getimagesize($bidon);
        /*   ".gif"=>"1",
        	         ".jpg"=>"2",
        	         ".jpeg"=>"2",
        	         ".png"=>"3",
        	         ".swf"=>"4",
        	         ".psd"=>"5",
        	         ".bmp"=>"6");
        		*/
        switch ($size[2]) {
            case 1:
                $src_img = imagecreatefromgif($bidon);
                break;
            case 2:
                $src_img = imagecreatefromjpeg($bidon);
                break;
            case 3:
                $src_img = imagecreatefrompng($bidon);
                break;
            case 6:
                $src_img = imagecreatefromwbmp($bidon);
                break;
            default:
                break;
        }
        $erreur_vignette = 0;
        if ($src_img) {
            $rs = $pmb_vignette_x / $pmb_vignette_y;
            $taillex = imagesx($src_img);
            $tailley = imagesy($src_img);
            if (!$taillex || !$tailley) {
                return "";
            }
            if ($taillex > $pmb_vignette_x || $tailley > $pmb_vignette_y) {
                $r = $taillex / $tailley;
                if ($r < 1 && $rs < 1) {
                    //Si x plus petit que y et taille finale portrait
                    //Si le format final est plus large en proportion
                    if ($rs > $r) {
                        $new_h = $pmb_vignette_y;
                        $new_w = $new_h * $r;
                    } else {
                        $new_w = $pmb_vignette_x;
                        $new_h = $new_w / $r;
                    }
                } else {
                    if ($r < 1 && $rs >= 1) {
                        //Si x plus petit que y et taille finale paysage
                        $new_h = $pmb_vignette_y;
                        $new_w = $new_h * $r;
                    } else {
                        if ($r > 1 && $rs < 1) {
                            //Si x plus grand que y et taille finale portrait
                            $new_w = $pmb_vignette_x;
                            $new_h = $new_w / $r;
                        } else {
                            //Si x plus grand que y et taille finale paysage
                            if ($rs < $r) {
                                $new_w = $pmb_vignette_x;
                                $new_h = $new_w / $r;
                            } else {
                                $new_h = $pmb_vignette_y;
                                $new_w = $new_h * $r;
                            }
                        }
                    }
                }
            } else {
                $new_h = $tailley;
                $new_w = $taillex;
            }
            $dst_img = imagecreatetruecolor($pmb_vignette_x, $pmb_vignette_y);
            ImageSaveAlpha($dst_img, true);
            ImageAlphaBlending($dst_img, false);
            imagefilledrectangle($dst_img, 0, 0, $pmb_vignette_x, $pmb_vignette_y, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
            imagecopyresized($dst_img, $src_img, round(($pmb_vignette_x - $new_w) / 2), round(($pmb_vignette_y - $new_h) / 2), 0, 0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));
            imagepng($dst_img, "{$base_path}/temp/" . SESSid);
            $fp = fopen("{$base_path}/temp/" . SESSid, "r");
            $contenu_vignette = fread($fp, filesize("{$base_path}/temp/" . SESSid));
            if (!$fp || $contenu_vignette == "") {
                $erreur_vignette++;
            }
            fclose($fp);
            unlink("{$base_path}/temp/" . SESSid);
        } else {
            $contenu_vignette = '';
        }
    }
    return $contenu_vignette;
}
Exemple #19
0
 public function run($pdf, $opts)
 {
     // catch objects
     if (!isset($opts)) {
         $opts = '';
     }
     // get options
     $opts = json_decode($opts);
     // set up an object
     if (!$opts) {
         $opts = (object) array();
     }
     // default options
     if (!property_exists($opts, 'nocache')) {
         $opts->nocache = false;
     }
     if (!property_exists($opts, 'pagemaxwidth')) {
         $opts->pagemaxwidth = 1000;
     }
     if (!property_exists($opts, 'pagemaxheight')) {
         $opts->pagemaxheight = 1000;
     }
     if (!property_exists($opts, 'thumbmaxwidth')) {
         $opts->thumbmaxwidth = 100;
     }
     if (!property_exists($opts, 'thumbmaxheight')) {
         $opts->thumbmaxheight = 75;
     }
     // create a cache id
     $cachemod = md5($pdf);
     // does it exist in the cache, if so return it
     if (!$opts->nocache && file_exists($this->cachedir . '/' . $cachemod . '/json.txt')) {
         return json_decode(file_get_contents($this->cachedir . '/' . $cachemod . '/json.txt'));
     }
     try {
         // create our cache directory
         mkdir($this->cachedir . '/' . $cachemod, 0777, true);
         // filename
         $filename = $this->cachedir . '/' . $cachemod . '/' . basename($pdf);
         // download the file
         $bytes = file_put_contents($filename, file_get_contents($pdf));
         // make sure we downloaded something
         if ($bytes === FALSE) {
             $json = array('error' => false, 'errormsg' => 'Could not download the PDF specified');
             return $json;
         }
         // json to return
         $json = array('error' => false, 'pagecount' => 0, 'pdfurl' => $this->URL . $filename, 'thumbs' => array(), 'pages' => array(), 'geometry' => array('x' => 0, 'y' => 0));
         // set up imagick instance
         $im = new Imagick();
         // force resolution to screen
         $im->setResolution(72, 72);
         // read image
         $im->readImage($filename);
         // get image information
         $imageInfo = $im->identifyImage();
         // ensure its a pdf!
         if (!$imageInfo || strpos(strtolower($imageInfo['format']), 'pdf') === FALSE) {
             $json = array('error' => false, 'errormsg' => 'The file specified is not a PDF!');
             return $json;
         }
         // get geometry
         $geometry = $imageInfo['geometry'];
         $json['geometry'] = array('x' => $geometry['width'], 'y' => $geometry['height']);
         // resize ratio
         $ratio = 1;
         $thumbratio = 1;
         // landscape or portrait?
         if ($geometry['width'] > $geometry['height']) {
             if ($geometry['width'] > $opts->pagemaxwidth) {
                 $ratio = $opts->pagemaxwidth / $geometry['width'];
             }
         } else {
             if ($geometry['height'] > $opts->pagemaxheight) {
                 $ratio = $opts->pagemaxheight / $geometry['height'];
             }
         }
         //  thumb ratio
         if ($geometry['width'] > $geometry['height']) {
             if ($geometry['width'] > $opts->thumbmaxwidth) {
                 $thumbratio = $opts->thumbmaxwidth / $geometry['width'];
             }
         } else {
             if ($geometry['height'] > $opts->thumbmaxheight) {
                 $thumbratio = $opts->thumbmaxheight / $geometry['height'];
             }
         }
         // get the number of pages
         $json['pagecount'] = $im->getNumberImages();
         // loop over pagecount
         for ($i = 0; $i < $json['pagecount']; $i++) {
             // convert to jpg
             $im2 = new Imagick($filename . '[' . $i . ']');
             // png for big image
             //$im2->setCompression(Imagick::COMPRESSION_PNG);
             $im2->setImageFormat('png');
             $im2->setCompressionQuality(95.5);
             // main image max size
             $im2->resizeImage($geometry['width'] * $ratio, $geometry['height'] * $ratio, imagick::FILTER_UNDEFINED, 1);
             //write image on server
             $im2->writeImage($this->cachedir . '/' . $cachemod . '/page-' . $i . '.png');
             // jpg for thumb
             $im2->setCompression(Imagick::COMPRESSION_JPEG);
             $im2->setCompressionQuality(95);
             $im2->setImageFormat('jpg');
             // thumb resize
             $im2->resizeImage($geometry['width'] * $thumbratio, $geometry['height'] * $thumbratio, imagick::FILTER_UNDEFINED, 1);
             //write image on server
             $im2->writeImage($this->cachedir . '/' . $cachemod . '/thumb-' . $i . '.jpg');
             // tidy up
             $im2->clear();
             $im2->destroy();
             // add to json
             $json['thumbs'][] = $this->CACHEURL . $cachemod . '/thumb-' . $i . '.jpg';
             $json['pages'][] = $this->CACHEURL . $cachemod . '/page-' . $i . '.png';
         }
         // tidy up
         $im->clear();
         $im->destroy();
         // put json into file
         file_put_contents($this->cachedir . '/' . $cachemod . '/json.txt', json_encode($json));
         // return values
         return $json;
     } catch (exception $e) {
         return array('error' => true, 'errormsg' => $e->getMessage());
     }
 }
/**
 * Process an image.
 *
 * Returns an array of the $file, $results, $converted to tell us if an image changes formats, and the $original file if it did.
 *
 * @param   string $file		Full absolute path to the image file
 * @param   int $gallery_type		1=wordpress, 2=nextgen, 3=flagallery, 4=aux_images, 5=image editor, 6=imagestore
 * @param   boolean $converted		tells us if this is a resize and the full image was converted to a new format
 * @param   boolean $new		tells the optimizer that this is a new image, so it should attempt conversion regardless of previous results
 * @param   boolean $fullsize		tells the optimizer this is a full size image
 * @returns array
 */
function ewww_image_optimizer($file, $gallery_type = 4, $converted = false, $new = false, $fullsize = false)
{
    ewwwio_debug_message('<b>' . __FUNCTION__ . '()</b>');
    // if the plugin gets here without initializing, we need to run through some things first
    if (!defined('EWWW_IMAGE_OPTIMIZER_CLOUD')) {
        ewww_image_optimizer_cloud_init();
    }
    session_write_close();
    $bypass_optimization = apply_filters('ewww_image_optimizer_bypass', false, $file);
    if (true === $bypass_optimization) {
        // tell the user optimization was skipped
        $msg = __("Optimization skipped", EWWW_IMAGE_OPTIMIZER_DOMAIN);
        ewwwio_debug_message("optimization bypassed: {$file}");
        // send back the above message
        return array(false, $msg, $converted, $file);
    }
    // initialize the original filename
    $original = $file;
    $result = '';
    // check that the file exists
    if (FALSE === file_exists($file)) {
        // tell the user we couldn't find the file
        $msg = sprintf(__('Could not find %s', EWWW_IMAGE_OPTIMIZER_DOMAIN), $file);
        ewwwio_debug_message("file doesn't appear to exist: {$file}");
        // send back the above message
        return array(false, $msg, $converted, $original);
    }
    // check that the file is writable
    if (FALSE === is_writable($file)) {
        // tell the user we can't write to the file
        $msg = sprintf(__('%s is not writable', EWWW_IMAGE_OPTIMIZER_DOMAIN), $file);
        ewwwio_debug_message("couldn't write to the file {$file}");
        // send back the above message
        return array(false, $msg, $converted, $original);
    }
    if (function_exists('fileperms')) {
        $file_perms = substr(sprintf('%o', fileperms($file)), -4);
    }
    $file_owner = 'unknown';
    $file_group = 'unknown';
    if (function_exists('posix_getpwuid')) {
        $file_owner = posix_getpwuid(fileowner($file));
        $file_owner = $file_owner['name'];
    }
    if (function_exists('posix_getgrgid')) {
        $file_group = posix_getgrgid(filegroup($file));
        $file_group = $file_group['name'];
    }
    ewwwio_debug_message("permissions: {$file_perms}, owner: {$file_owner}, group: {$file_group}");
    $type = ewww_image_optimizer_mimetype($file, 'i');
    if (strpos($type, 'image') === FALSE && strpos($type, 'pdf') === FALSE) {
        ewwwio_debug_message('could not find any functions for mimetype detection');
        //otherwise we store an error message since we couldn't get the mime-type
        return array(false, __('Unknown type: ' . $type, EWWW_IMAGE_OPTIMIZER_DOMAIN), $converted, $original);
        $msg = __('Missing finfo_file(), getimagesize() and mime_content_type() PHP functions', EWWW_IMAGE_OPTIMIZER_DOMAIN);
        return array(false, $msg, $converted, $original);
    }
    if (!EWWW_IMAGE_OPTIMIZER_CLOUD) {
        // check to see if 'nice' exists
        $nice = ewww_image_optimizer_find_nix_binary('nice', 'n');
        if (!defined('EWWW_IMAGE_OPTIMIZER_NOEXEC')) {
            // Check if exec is disabled
            if (ewww_image_optimizer_exec_check()) {
                define('EWWW_IMAGE_OPTIMIZER_NOEXEC', true);
                ewwwio_debug_message('exec seems to be disabled');
                ewww_image_optimizer_disable_tools();
                // otherwise, query the php settings for safe mode
            } elseif (ewww_image_optimizer_safemode_check()) {
                define('EWWW_IMAGE_OPTIMIZER_NOEXEC', true);
                ewwwio_debug_message('safe mode appears to be enabled');
                ewww_image_optimizer_disable_tools();
            } else {
                define('EWWW_IMAGE_OPTIMIZER_NOEXEC', false);
            }
        }
    }
    $skip = ewww_image_optimizer_skip_tools();
    // if the user has disabled the utility checks
    if (EWWW_IMAGE_OPTIMIZER_CLOUD) {
        $skip['jpegtran'] = true;
        $skip['optipng'] = true;
        $skip['gifsicle'] = true;
        $skip['pngout'] = true;
        $skip['pngquant'] = true;
        $skip['webp'] = true;
    }
    if (ewww_image_optimizer_get_option('ewww_image_optimizer_metadata_skip_full') && $fullsize) {
        $keep_metadata = true;
    } else {
        $keep_metadata = false;
    }
    if (ewww_image_optimizer_get_option('ewww_image_optimizer_lossy_skip_full') && $fullsize) {
        $skip_lossy = true;
    } else {
        $skip_lossy = false;
    }
    if (ini_get('max_execution_time') < 90 && ewww_image_optimizer_stl_check()) {
        set_time_limit(0);
    }
    // if the full-size image was converted
    if ($converted) {
        ewwwio_debug_message('full-size image was converted, need to rebuild filename for meta');
        $filenum = $converted;
        // grab the file extension
        preg_match('/\\.\\w+$/', $file, $fileext);
        // strip the file extension
        $filename = str_replace($fileext[0], '', $file);
        // grab the dimensions
        preg_match('/-\\d+x\\d+(-\\d+)*$/', $filename, $fileresize);
        // strip the dimensions
        $filename = str_replace($fileresize[0], '', $filename);
        // reconstruct the filename with the same increment (stored in $converted) as the full version
        $refile = $filename . '-' . $filenum . $fileresize[0] . $fileext[0];
        // rename the file
        rename($file, $refile);
        ewwwio_debug_message("moved {$file} to {$refile}");
        // and set $file to the new filename
        $file = $refile;
        $original = $file;
    }
    // get the original image size
    $orig_size = filesize($file);
    ewwwio_debug_message("original filesize: {$orig_size}");
    if ($orig_size < ewww_image_optimizer_get_option('ewww_image_optimizer_skip_size')) {
        // tell the user optimization was skipped
        $msg = __("Optimization skipped", EWWW_IMAGE_OPTIMIZER_DOMAIN);
        ewwwio_debug_message("optimization bypassed due to filesize: {$file}");
        // send back the above message
        return array(false, $msg, $converted, $file);
    }
    if ($type == 'image/png' && ewww_image_optimizer_get_option('ewww_image_optimizer_skip_png_size') && $orig_size > ewww_image_optimizer_get_option('ewww_image_optimizer_skip_png_size')) {
        // tell the user optimization was skipped
        $msg = __("Optimization skipped", EWWW_IMAGE_OPTIMIZER_DOMAIN);
        ewwwio_debug_message("optimization bypassed due to filesize: {$file}");
        // send back the above message
        return array($file, $msg, $converted, $file);
    }
    // initialize $new_size with the original size, HOW ABOUT A ZERO...
    //$new_size = $orig_size;
    $new_size = 0;
    // set the optimization process to OFF
    $optimize = false;
    // toggle the convert process to ON
    $convert = true;
    // allow other plugins to mangle the image however they like prior to optimization
    do_action('ewww_image_optimizer_pre_optimization', $file, $type);
    // run the appropriate optimization/conversion for the mime-type
    switch ($type) {
        case 'image/jpeg':
            $png_size = 0;
            // if jpg2png conversion is enabled, and this image is in the wordpress media library
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_to_png') && $gallery_type == 1 || !empty($_GET['ewww_convert'])) {
                // generate the filename for a PNG
                // if this is a resize version
                if ($converted) {
                    // just change the file extension
                    $pngfile = preg_replace('/\\.\\w+$/', '.png', $file);
                    // if this is a full size image
                } else {
                    // get a unique filename for the png image
                    list($pngfile, $filenum) = ewww_image_optimizer_unique_filename($file, '.png');
                }
            } else {
                // otherwise, set it to OFF
                $convert = false;
                $pngfile = '';
            }
            // check for previous optimization, so long as the force flag is on and this isn't a new image that needs converting
            if (empty($_REQUEST['ewww_force']) && !($new && $convert)) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, $converted, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_level') > 10) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type, $convert, $pngfile, 'image/png', $skip_lossy);
                if ($converted) {
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($original);
                    }
                    $converted = $filenum;
                    ewww_image_optimizer_webp_create($file, $new_size, 'image/png', null, $orig_size != $new_size);
                } else {
                    ewww_image_optimizer_webp_create($file, $new_size, $type, null, $orig_size != $new_size);
                }
                break;
            }
            if ($convert) {
                $tools = ewww_image_optimizer_path_check(!$skip['jpegtran'], !$skip['optipng'], false, !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            } else {
                $tools = ewww_image_optimizer_path_check(!$skip['jpegtran'], false, false, false, false, !$skip['webp']);
            }
            // if jpegtran optimization is disabled
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_level') == 0) {
                // store an appropriate message in $result
                $result = __('JPG optimization is disabled', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                // otherwise, if we aren't skipping the utility verification and jpegtran doesn't exist
            } elseif (!$skip['jpegtran'] && !$tools['JPEGTRAN']) {
                // store an appropriate message in $result
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>jpegtran</em>');
                // otherwise, things should be good, so...
            } else {
                // set the optimization process to ON
                $optimize = true;
            }
            // if optimization is turned ON
            if ($optimize) {
                ewwwio_debug_message('attempting to optimize JPG...');
                // generate temporary file-names:
                $tempfile = $file . ".tmp";
                //non-progressive jpeg
                $progfile = $file . ".prog";
                // progressive jpeg
                // check to see if we are supposed to strip metadata (badly named)
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && !$keep_metadata) {
                    // don't copy metadata
                    $copy_opt = 'none';
                } else {
                    // copy all the metadata
                    $copy_opt = 'all';
                }
                // run jpegtran - non-progressive
                exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -outfile " . ewww_image_optimizer_escapeshellarg($tempfile) . " " . ewww_image_optimizer_escapeshellarg($file));
                // run jpegtran - progressive
                exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -progressive -outfile " . ewww_image_optimizer_escapeshellarg($progfile) . " " . ewww_image_optimizer_escapeshellarg($file));
                // check the filesize of the non-progressive JPG
                $non_size = ewww_image_optimizer_filesize($tempfile);
                // check the filesize of the progressive JPG
                $prog_size = ewww_image_optimizer_filesize($progfile);
                ewwwio_debug_message("optimized JPG (non-progresive) size: {$non_size}");
                ewwwio_debug_message("optimized JPG (progresive) size: {$prog_size}");
                if ($non_size === false || $prog_size === false) {
                    $result = __('Unable to write file', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                    $new_size = 0;
                } elseif (!$non_size || !$prog_size) {
                    $result = __('Optimization failed', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                    $new_size = 0;
                } else {
                    // if the progressive file is bigger
                    if ($prog_size > $non_size) {
                        // store the size of the non-progessive JPG
                        $new_size = $non_size;
                        if (is_file($progfile)) {
                            // delete the progressive file
                            unlink($progfile);
                        }
                        // if the progressive file is smaller or the same
                    } else {
                        // store the size of the progressive JPG
                        $new_size = $prog_size;
                        // replace the non-progressive with the progressive file
                        rename($progfile, $tempfile);
                    }
                }
                ewwwio_debug_message("optimized JPG size: {$new_size}");
                // if the best-optimized is smaller than the original JPG, and we didn't create an empty JPG
                if ($orig_size > $new_size && $new_size != 0 && ewww_image_optimizer_mimetype($tempfile, 'i') == $type) {
                    // replace the original with the optimized file
                    rename($tempfile, $file);
                    // store the results of the optimization
                    $result = "{$orig_size} vs. {$new_size}";
                    // if the optimization didn't produce a smaller JPG
                } else {
                    if (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                    // store the results
                    $result = 'unchanged';
                    $new_size = $orig_size;
                }
                // if conversion and optimization are both turned OFF, finish the JPG processing
            } elseif (!$convert) {
                ewww_image_optimizer_webp_create($file, $orig_size, $type, $tools['WEBP']);
                break;
            }
            // if the conversion process is turned ON, or if this is a resize and the full-size was converted
            if ($convert) {
                ewwwio_debug_message("attempting to convert JPG to PNG: {$pngfile}");
                if (empty($new_size)) {
                    $new_size = $orig_size;
                }
                // convert the JPG to PNG
                if (ewww_image_optimizer_gmagick_support()) {
                    try {
                        $gmagick = new Gmagick($file);
                        $gmagick->stripimage();
                        $gmagick->setimageformat('PNG');
                        $gmagick->writeimage($pngfile);
                    } catch (Exception $gmagick_error) {
                        ewwwio_debug_message($gmagick_error->getMessage());
                    }
                    $png_size = ewww_image_optimizer_filesize($pngfile);
                }
                if (!$png_size && ewww_image_optimizer_imagick_support()) {
                    try {
                        $imagick = new Imagick($file);
                        $imagick->stripImage();
                        $imagick->setImageFormat('PNG');
                        $imagick->writeImage($pngfile);
                    } catch (Exception $imagick_error) {
                        ewwwio_debug_message($imagick_error->getMessage());
                    }
                    $png_size = ewww_image_optimizer_filesize($pngfile);
                }
                if (!$png_size) {
                    $convert_path = '';
                    // retrieve version info for ImageMagick
                    if (PHP_OS != 'WINNT') {
                        $convert_path = ewww_image_optimizer_find_nix_binary('convert', 'i');
                    } elseif (PHP_OS == 'WINNT') {
                        $convert_path = ewww_image_optimizer_find_win_binary('convert', 'i');
                    }
                    if (!empty($convert_path)) {
                        ewwwio_debug_message('converting with ImageMagick');
                        exec($convert_path . " " . ewww_image_optimizer_escapeshellarg($file) . " -strip " . ewww_image_optimizer_escapeshellarg($pngfile));
                        $png_size = ewww_image_optimizer_filesize($pngfile);
                    }
                }
                if (!$png_size && ewww_image_optimizer_gd_support()) {
                    ewwwio_debug_message('converting with GD');
                    imagepng(imagecreatefromjpeg($file), $pngfile);
                    $png_size = ewww_image_optimizer_filesize($pngfile);
                }
                // if lossy optimization is ON and full-size exclusion is not active
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') == 40 && $tools['PNGQUANT'] && !$skip_lossy) {
                    ewwwio_debug_message('attempting lossy reduction');
                    exec("{$nice} " . $tools['PNGQUANT'] . " " . ewww_image_optimizer_escapeshellarg($pngfile));
                    $quantfile = preg_replace('/\\.\\w+$/', '-fs8.png', $pngfile);
                    if (is_file($quantfile) && filesize($pngfile) > filesize($quantfile)) {
                        ewwwio_debug_message("lossy reduction is better: original - " . filesize($pngfile) . " vs. lossy - " . filesize($quantfile));
                        rename($quantfile, $pngfile);
                    } elseif (is_file($quantfile)) {
                        ewwwio_debug_message("lossy reduction is worse: original - " . filesize($pngfile) . " vs. lossy - " . filesize($quantfile));
                        unlink($quantfile);
                    } else {
                        ewwwio_debug_message('pngquant did not produce any output');
                    }
                }
                // if optipng isn't disabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng')) {
                    // retrieve the optipng optimization level
                    $optipng_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_optipng_level');
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && preg_match('/0.7/', ewww_image_optimizer_tool_found($tools['OPTIPNG'], 'o')) && !$keep_metadata) {
                        $strip = '-strip all ';
                    } else {
                        $strip = '';
                    }
                    // if the PNG file was created
                    if (file_exists($pngfile)) {
                        ewwwio_debug_message('optimizing converted PNG with optipng');
                        // run optipng on the new PNG
                        exec("{$nice} " . $tools['OPTIPNG'] . " -o{$optipng_level} -quiet {$strip} " . ewww_image_optimizer_escapeshellarg($pngfile));
                    }
                }
                // if pngout isn't disabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout')) {
                    // retrieve the pngout optimization level
                    $pngout_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_pngout_level');
                    // if the PNG file was created
                    if (file_exists($pngfile)) {
                        ewwwio_debug_message('optimizing converted PNG with pngout');
                        // run pngout on the new PNG
                        exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($pngfile));
                    }
                }
                $png_size = ewww_image_optimizer_filesize($pngfile);
                ewwwio_debug_message("converted PNG size: {$png_size}");
                // if the PNG is smaller than the original JPG, and we didn't end up with an empty file
                if ($new_size > $png_size && $png_size != 0 && ewww_image_optimizer_mimetype($pngfile, 'i') == 'image/png') {
                    ewwwio_debug_message("converted PNG is better: {$png_size} vs. {$new_size}");
                    // store the size of the converted PNG
                    $new_size = $png_size;
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($file);
                    }
                    // store the location of the PNG file
                    $file = $pngfile;
                    // let webp know what we're dealing with now
                    $type = 'image/png';
                    // successful conversion and we store the increment
                    $converted = $filenum;
                } else {
                    ewwwio_debug_message('converted PNG is no good');
                    // otherwise delete the PNG
                    $converted = FALSE;
                    if (is_file($pngfile)) {
                        unlink($pngfile);
                    }
                }
            }
            ewww_image_optimizer_webp_create($file, $new_size, $type, $tools['WEBP'], $orig_size != $new_size);
            break;
        case 'image/png':
            $jpg_size = 0;
            // png2jpg conversion is turned on, and the image is in the wordpress media library
            if ((ewww_image_optimizer_get_option('ewww_image_optimizer_png_to_jpg') || !empty($_GET['ewww_convert'])) && $gallery_type == 1 && !$skip_lossy && (!ewww_image_optimizer_png_alpha($file) || ewww_image_optimizer_jpg_background())) {
                ewwwio_debug_message('PNG to JPG conversion turned on');
                // if the user set a fill background for transparency
                $background = '';
                if ($background = ewww_image_optimizer_jpg_background()) {
                    // set background color for GD
                    $r = hexdec('0x' . strtoupper(substr($background, 0, 2)));
                    $g = hexdec('0x' . strtoupper(substr($background, 2, 2)));
                    $b = hexdec('0x' . strtoupper(substr($background, 4, 2)));
                    // set the background flag for 'convert'
                    $background = "-background " . '"' . "#{$background}" . '"';
                } else {
                    $r = '';
                    $g = '';
                    $b = '';
                }
                // if the user manually set the JPG quality
                if ($quality = ewww_image_optimizer_jpg_quality()) {
                    // set the quality for GD
                    $gquality = $quality;
                    // set the quality flag for 'convert'
                    $cquality = "-quality {$quality}";
                } else {
                    $cquality = '';
                    $gquality = '92';
                }
                // if this is a resize version
                if ($converted) {
                    // just replace the file extension with a .jpg
                    $jpgfile = preg_replace('/\\.\\w+$/', '.jpg', $file);
                    // if this is a full version
                } else {
                    // construct the filename for the new JPG
                    list($jpgfile, $filenum) = ewww_image_optimizer_unique_filename($file, '.jpg');
                }
            } else {
                ewwwio_debug_message('PNG to JPG conversion turned off');
                // turn the conversion process OFF
                $convert = false;
                $jpgfile = '';
                $r = null;
                $g = null;
                $b = null;
                $gquality = null;
            }
            // check for previous optimization, so long as the force flag is on and this isn't a new image that needs converting
            if (empty($_REQUEST['ewww_force']) && !($new && $convert)) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, $converted, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') >= 20 && ewww_image_optimizer_get_option('ewww_image_optimizer_cloud_key')) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type, $convert, $jpgfile, 'image/jpeg', $skip_lossy, array('r' => $r, 'g' => $g, 'b' => $b, 'quality' => $gquality));
                if ($converted) {
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($original);
                    }
                    $converted = $filenum;
                    ewww_image_optimizer_webp_create($file, $new_size, 'image/jpeg', null, $orig_size != $new_size);
                } else {
                    ewww_image_optimizer_webp_create($file, $new_size, $type, null, $orig_size != $new_size);
                }
                break;
            }
            if ($convert) {
                $tools = ewww_image_optimizer_path_check(!$skip['jpegtran'], !$skip['optipng'], false, !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            } else {
                $tools = ewww_image_optimizer_path_check(false, !$skip['optipng'], false, !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            }
            // if pngout and optipng are disabled
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng') && ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout') || ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') == 0) {
                // tell the user all PNG tools are disabled
                $result = __('PNG optimization is disabled', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                // if the utility checking is on, optipng is enabled, but optipng cannot be found
            } elseif (!$skip['optipng'] && !$tools['OPTIPNG']) {
                // tell the user optipng is missing
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>optipng</em>');
                // if the utility checking is on, pngout is enabled, but pngout cannot be found
            } elseif (!$skip['pngout'] && !$tools['PNGOUT']) {
                // tell the user pngout is missing
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>pngout</em>');
            } else {
                // turn optimization on if we made it through all the checks
                $optimize = true;
            }
            // if optimization is turned on
            if ($optimize) {
                // if lossy optimization is ON and full-size exclusion is not active
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_png_level') == 40 && $tools['PNGQUANT'] && !$skip_lossy) {
                    ewwwio_debug_message('attempting lossy reduction');
                    exec("{$nice} " . $tools['PNGQUANT'] . " " . ewww_image_optimizer_escapeshellarg($file));
                    $quantfile = preg_replace('/\\.\\w+$/', '-fs8.png', $file);
                    if (is_file($quantfile) && filesize($file) > filesize($quantfile) && ewww_image_optimizer_mimetype($quantfile, 'i') == $type) {
                        ewwwio_debug_message("lossy reduction is better: original - " . filesize($file) . " vs. lossy - " . filesize($quantfile));
                        rename($quantfile, $file);
                    } elseif (is_file($quantfile)) {
                        ewwwio_debug_message("lossy reduction is worse: original - " . filesize($file) . " vs. lossy - " . filesize($quantfile));
                        unlink($quantfile);
                    } else {
                        ewwwio_debug_message('pngquant did not produce any output');
                    }
                }
                $tempfile = $file . '.tmp.png';
                copy($file, $tempfile);
                // if optipng is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng')) {
                    // retrieve the optimization level for optipng
                    $optipng_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_optipng_level');
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && preg_match('/0.7/', ewww_image_optimizer_tool_found($tools['OPTIPNG'], 'o')) && !$keep_metadata) {
                        $strip = '-strip all ';
                    } else {
                        $strip = '';
                    }
                    // run optipng on the PNG file
                    exec("{$nice} " . $tools['OPTIPNG'] . " -o{$optipng_level} -quiet {$strip} " . ewww_image_optimizer_escapeshellarg($tempfile));
                }
                // if pngout is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout')) {
                    // retrieve the optimization level for pngout
                    $pngout_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_pngout_level');
                    // run pngout on the PNG file
                    exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($tempfile));
                }
                // retrieve the filesize of the temporary PNG
                $new_size = ewww_image_optimizer_filesize($tempfile);
                // if the new PNG is smaller
                if ($orig_size > $new_size && $new_size != 0 && ewww_image_optimizer_mimetype($tempfile, 'i') == $type) {
                    // replace the original with the optimized file
                    rename($tempfile, $file);
                    // store the results of the optimization
                    $result = "{$orig_size} vs. {$new_size}";
                    // if the optimization didn't produce a smaller PNG
                } else {
                    if (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                    // store the results
                    $result = 'unchanged';
                    $new_size = $orig_size;
                }
                // if conversion and optimization are both disabled we are done here
            } elseif (!$convert) {
                ewwwio_debug_message('calling webp, but neither convert or optimize');
                ewww_image_optimizer_webp_create($file, $orig_size, $type, $tools['WEBP']);
                break;
            }
            // retrieve the new filesize of the PNG
            $new_size = ewww_image_optimizer_filesize($file);
            // if conversion is on and the PNG doesn't have transparency or the user set a background color to replace transparency
            //if ( $convert && ( ! ewww_image_optimizer_png_alpha( $file ) || ewww_image_optimizer_jpg_background() ) ) {
            if ($convert) {
                ewwwio_debug_message("attempting to convert PNG to JPG: {$jpgfile}");
                if (empty($new_size)) {
                    $new_size = $orig_size;
                }
                $magick_background = ewww_image_optimizer_jpg_background();
                if (empty($magick_background)) {
                    $magick_background = '000000';
                }
                // convert the PNG to a JPG with all the proper options
                if (ewww_image_optimizer_gmagick_support()) {
                    try {
                        if (ewww_image_optimizer_png_alpha($file)) {
                            $gmagick_overlay = new Gmagick($file);
                            $gmagick = new Gmagick();
                            $gmagick->newimage($gmagick_overlay->getimagewidth(), $gmagick_overlay->getimageheight(), '#' . $magick_background);
                            $gmagick->compositeimage($gmagick_overlay, 1, 0, 0);
                        } else {
                            $gmagick = new Gmagick($file);
                        }
                        $gmagick->setimageformat('JPG');
                        $gmagick->setcompressionquality($gquality);
                        $gmagick->writeimage($jpgfile);
                    } catch (Exception $gmagick_error) {
                        ewwwio_debug_message($gmagick_error->getMessage());
                    }
                    $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                }
                if (!$jpg_size && ewww_image_optimizer_imagick_support()) {
                    try {
                        $imagick = new Imagick($file);
                        if (ewww_image_optimizer_png_alpha($file)) {
                            $imagick->setImageBackgroundColor(new ImagickPixel('#' . $magick_background));
                            $imagick->setImageAlphaChannel(11);
                        }
                        $imagick->setImageFormat('JPG');
                        $imagick->setCompressionQuality($gquality);
                        $imagick->writeImage($jpgfile);
                    } catch (Exception $imagick_error) {
                        ewwwio_debug_message($imagick_error->getMessage());
                    }
                    $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                }
                if (!$jpg_size) {
                    // retrieve version info for ImageMagick
                    $convert_path = ewww_image_optimizer_find_nix_binary('convert', 'i');
                    if (!empty($convert_path)) {
                        ewwwio_debug_message('converting with ImageMagick');
                        ewwwio_debug_message("using command: {$convert_path} {$background} -alpha remove {$cquality} {$file} {$jpgfile}");
                        exec("{$convert_path} {$background} -alpha remove {$cquality} " . ewww_image_optimizer_escapeshellarg($file) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
                        $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                    }
                }
                if (!$jpg_size && ewww_image_optimizer_gd_support()) {
                    ewwwio_debug_message('converting with GD');
                    // retrieve the data from the PNG
                    $input = imagecreatefrompng($file);
                    // retrieve the dimensions of the PNG
                    list($width, $height) = getimagesize($file);
                    // create a new image with those dimensions
                    $output = imagecreatetruecolor($width, $height);
                    if ($r === '') {
                        $r = 255;
                        $g = 255;
                        $b = 255;
                    }
                    // allocate the background color
                    $rgb = imagecolorallocate($output, $r, $g, $b);
                    // fill the new image with the background color
                    imagefilledrectangle($output, 0, 0, $width, $height, $rgb);
                    // copy the original image to the new image
                    imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
                    // output the JPG with the quality setting
                    imagejpeg($output, $jpgfile, $gquality);
                }
                $jpg_size = ewww_image_optimizer_filesize($jpgfile);
                if ($jpg_size) {
                    ewwwio_debug_message("converted JPG filesize: {$jpg_size}");
                } else {
                    ewwwio_debug_message('unable to convert to JPG');
                }
                // next we need to optimize that JPG if jpegtran is enabled
                if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpg_level') == 10 && file_exists($jpgfile)) {
                    // generate temporary file-names:
                    $tempfile = $jpgfile . ".tmp";
                    //non-progressive jpeg
                    $progfile = $jpgfile . ".prog";
                    // progressive jpeg
                    // check to see if we are supposed to strip metadata (badly named)
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && !$keep_metadata) {
                        // don't copy metadata
                        $copy_opt = 'none';
                    } else {
                        // copy all the metadata
                        $copy_opt = 'all';
                    }
                    // run jpegtran - non-progressive
                    exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -outfile " . ewww_image_optimizer_escapeshellarg($tempfile) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
                    // run jpegtran - progressive
                    exec("{$nice} " . $tools['JPEGTRAN'] . " -copy {$copy_opt} -optimize -progressive -outfile " . ewww_image_optimizer_escapeshellarg($progfile) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
                    // check the filesize of the non-progressive JPG
                    $non_size = ewww_image_optimizer_filesize($tempfile);
                    ewwwio_debug_message("non-progressive JPG filesize: {$non_size}");
                    // check the filesize of the progressive JPG
                    $prog_size = ewww_image_optimizer_filesize($progfile);
                    ewwwio_debug_message("progressive JPG filesize: {$prog_size}");
                    // if the progressive file is bigger
                    if ($prog_size > $non_size) {
                        // store the size of the non-progessive JPG
                        $opt_jpg_size = $non_size;
                        if (is_file($progfile)) {
                            // delete the progressive file
                            unlink($progfile);
                        }
                        ewwwio_debug_message('keeping non-progressive JPG');
                        // if the progressive file is smaller or the same
                    } else {
                        // store the size of the progressive JPG
                        $opt_jpg_size = $prog_size;
                        // replace the non-progressive with the progressive file
                        rename($progfile, $tempfile);
                        ewwwio_debug_message('keeping progressive JPG');
                    }
                    // if the best-optimized is smaller than the original JPG, and we didn't create an empty JPG
                    if ($jpg_size > $opt_jpg_size && $opt_jpg_size != 0) {
                        // replace the original with the optimized file
                        rename($tempfile, $jpgfile);
                        // store the size of the optimized JPG
                        $jpg_size = $opt_jpg_size;
                        ewwwio_debug_message('optimized JPG was smaller than un-optimized version');
                        // if the optimization didn't produce a smaller JPG
                    } elseif (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                }
                ewwwio_debug_message("converted JPG size: {$jpg_size}");
                // if the new JPG is smaller than the original PNG
                if ($new_size > $jpg_size && $jpg_size != 0 && ewww_image_optimizer_mimetype($jpgfile, 'i') == 'image/jpeg') {
                    // store the size of the JPG as the new filesize
                    $new_size = $jpg_size;
                    // if the user wants originals delted after a conversion
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original PNG
                        unlink($file);
                    }
                    // update the $file location to the new JPG
                    $file = $jpgfile;
                    // let webp know what we're dealing with now
                    $type = 'image/jpeg';
                    // successful conversion, so we store the increment
                    $converted = $filenum;
                } else {
                    $converted = FALSE;
                    if (is_file($jpgfile)) {
                        // otherwise delete the new JPG
                        unlink($jpgfile);
                    }
                }
            }
            ewww_image_optimizer_webp_create($file, $new_size, $type, $tools['WEBP'], $orig_size != $new_size);
            break;
        case 'image/gif':
            // if gif2png is turned on, and the image is in the wordpress media library
            if ((ewww_image_optimizer_get_option('ewww_image_optimizer_gif_to_png') || !empty($_GET['ewww_convert'])) && $gallery_type == 1 && !ewww_image_optimizer_is_animated($file)) {
                // generate the filename for a PNG
                // if this is a resize version
                if ($converted) {
                    // just change the file extension
                    $pngfile = preg_replace('/\\.\\w+$/', '.png', $file);
                    // if this is the full version
                } else {
                    // construct the filename for the new PNG
                    list($pngfile, $filenum) = ewww_image_optimizer_unique_filename($file, '.png');
                }
            } else {
                // turn conversion OFF
                $convert = false;
                $pngfile = '';
            }
            // check for previous optimization, so long as the force flag is on and this isn't a new image that needs converting
            if (empty($_REQUEST['ewww_force']) && !($new && $convert)) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, $converted, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_cloud_key') && ewww_image_optimizer_get_option('ewww_image_optimizer_gif_level') == 10) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type, $convert, $pngfile, 'image/png', $skip_lossy);
                if ($converted) {
                    // check to see if the user wants the originals deleted
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original JPG
                        unlink($original);
                    }
                    $converted = $filenum;
                    ewww_image_optimizer_webp_create($file, $new_size, 'image/png', null, $orig_size != $new_size);
                }
                break;
            }
            if ($convert) {
                $tools = ewww_image_optimizer_path_check(false, !$skip['optipng'], !$skip['gifsicle'], !$skip['pngout'], !$skip['pngquant'], !$skip['webp']);
            } else {
                $tools = ewww_image_optimizer_path_check(false, false, !$skip['gifsicle'], false, false, false);
            }
            // if gifsicle is disabled
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_gif_level') == 0) {
                // return an appropriate message
                $result = __('GIF optimization is disabled', EWWW_IMAGE_OPTIMIZER_DOMAIN);
                // if utility checking is on, and gifsicle is not installed
            } elseif (!$skip['gifsicle'] && !$tools['GIFSICLE']) {
                // return an appropriate message
                $result = sprintf(__('%s is missing', EWWW_IMAGE_OPTIMIZER_DOMAIN), '<em>gifsicle</em>');
            } else {
                // otherwise, turn optimization ON
                $optimize = true;
            }
            // if optimization is turned ON
            if ($optimize) {
                $tempfile = $file . '.tmp';
                //temporary GIF output
                // run gifsicle on the GIF
                exec("{$nice} " . $tools['GIFSICLE'] . " -O3 --careful -o {$tempfile} " . ewww_image_optimizer_escapeshellarg($file));
                // retrieve the filesize of the temporary GIF
                $new_size = ewww_image_optimizer_filesize($tempfile);
                // if the new GIF is smaller
                if ($orig_size > $new_size && $new_size != 0 && ewww_image_optimizer_mimetype($tempfile, 'i') == $type) {
                    // replace the original with the optimized file
                    rename($tempfile, $file);
                    // store the results of the optimization
                    $result = "{$orig_size} vs. {$new_size}";
                    // if the optimization didn't produce a smaller GIF
                } else {
                    if (is_file($tempfile)) {
                        // delete the optimized file
                        unlink($tempfile);
                    }
                    // store the results
                    $result = 'unchanged';
                    $new_size = $orig_size;
                }
                // if conversion and optimization are both turned OFF, we are done here
            } elseif (!$convert) {
                break;
            }
            // get the new filesize for the GIF
            $new_size = ewww_image_optimizer_filesize($file);
            // if conversion is ON and the GIF isn't animated
            if ($convert && !ewww_image_optimizer_is_animated($file)) {
                if (empty($new_size)) {
                    $new_size = $orig_size;
                }
                // if optipng is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_optipng') && $tools['OPTIPNG']) {
                    // retrieve the optipng optimization level
                    $optipng_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_optipng_level');
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_jpegtran_copy') && preg_match('/0.7/', ewww_image_optimizer_tool_found($tools['OPTIPNG'], 'o')) && !$keep_metadata) {
                        $strip = '-strip all ';
                    } else {
                        $strip = '';
                    }
                    // run optipng on the GIF file
                    exec("{$nice} " . $tools['OPTIPNG'] . " -out " . ewww_image_optimizer_escapeshellarg($pngfile) . " -o{$optipng_level} -quiet {$strip} " . ewww_image_optimizer_escapeshellarg($file));
                }
                // if pngout is enabled
                if (!ewww_image_optimizer_get_option('ewww_image_optimizer_disable_pngout') && $tools['PNGOUT']) {
                    // retrieve the pngout optimization level
                    $pngout_level = (int) ewww_image_optimizer_get_option('ewww_image_optimizer_pngout_level');
                    // if $pngfile exists (which means optipng was run already)
                    if (file_exists($pngfile)) {
                        // run pngout on the PNG file
                        exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($pngfile));
                    } else {
                        // run pngout on the GIF file
                        exec("{$nice} " . $tools['PNGOUT'] . " -s{$pngout_level} -q " . ewww_image_optimizer_escapeshellarg($file) . " " . ewww_image_optimizer_escapeshellarg($pngfile));
                    }
                }
                // retrieve the filesize of the PNG
                $png_size = ewww_image_optimizer_filesize($pngfile);
                // if the new PNG is smaller than the original GIF
                if ($new_size > $png_size && $png_size != 0 && ewww_image_optimizer_mimetype($pngfile, 'i') == 'image/png') {
                    // store the PNG size as the new filesize
                    $new_size = $png_size;
                    // if the user wants original GIFs deleted after successful conversion
                    if (ewww_image_optimizer_get_option('ewww_image_optimizer_delete_originals') == TRUE) {
                        // delete the original GIF
                        unlink($file);
                    }
                    // update the $file location with the new PNG
                    $file = $pngfile;
                    // let webp know what we're dealing with now
                    $type = 'image/png';
                    // normally this would be at the end of the section, but we only want to do webp if the image was successfully converted to a png
                    ewww_image_optimizer_webp_create($file, $new_size, $type, $tools['WEBP'], $orig_size != $new_size);
                    // successful conversion (for now), so we store the increment
                    $converted = $filenum;
                } else {
                    $converted = FALSE;
                    if (is_file($pngfile)) {
                        unlink($pngfile);
                    }
                }
            }
            break;
        case 'application/pdf':
            if (empty($_REQUEST['ewww_force'])) {
                if ($results_msg = ewww_image_optimizer_check_table($file, $orig_size)) {
                    return array($file, $results_msg, false, $original);
                }
            }
            if (ewww_image_optimizer_get_option('ewww_image_optimizer_pdf_level') > 0) {
                list($file, $converted, $result, $new_size) = ewww_image_optimizer_cloud_optimizer($file, $type);
            }
            break;
        default:
            // if not a JPG, PNG, or GIF, tell the user we don't work with strangers
            return array($file, __('Unknown type: ' . $type, EWWW_IMAGE_OPTIMIZER_DOMAIN), $converted, $original);
    }
    // allow other plugins to run operations on the images after optimization.
    // NOTE: it is recommended to do any image modifications prior to optimization, otherwise you risk un-optimizing your images here.
    do_action('ewww_image_optimizer_post_optimization', $file, $type);
    // if their cloud api license limit has been exceeded
    if ($result == 'exceeded') {
        return array($file, __('License exceeded', EWWW_IMAGE_OPTIMIZER_DOMAIN), $converted, $original);
    }
    if (!empty($new_size)) {
        // Set correct file permissions
        $stat = stat(dirname($file));
        $perms = $stat['mode'] & 0666;
        //same permissions as parent folder, strip off the executable bits
        @chmod($file, $perms);
        $results_msg = ewww_image_optimizer_update_table($file, $new_size, $orig_size, $new);
        ewwwio_memory(__FUNCTION__);
        return array($file, $results_msg, $converted, $original);
    }
    ewwwio_memory(__FUNCTION__);
    // otherwise, send back the filename, the results (some sort of error message), the $converted flag, and the name of the original image
    return array($file, $result, $converted, $original);
}
Exemple #21
0
 /**
  * Puts an image in the page. 
  * The upper-left corner must be given. 
  * The dimensions can be specified in different ways:<ul>
  * <li>explicit width and height (expressed in user unit)</li>
  * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
  * The format can be specified explicitly or inferred from the file extension.<br />
  * It is possible to put a link on the image.<br />
  * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  * @param string $file Name of the file containing the image.
  * @param float $x Abscissa of the upper-left corner.
  * @param float $y Ordinate of the upper-left corner.
  * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  * @param mixed $link URL or identifier returned by AddLink().
  * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
  * @param int $dpi dot-per-inch resolution used on resize
  * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  * @param boolean $ismask true if this image is a mask, false otherwise
  * @param mixed $imgmask image object returned by this function or false
  * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
  * @return image information
  * @access public
  * @since 1.1
  */
 public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300, $palign = '', $ismask = false, $imgmask = false, $border = 0)
 {
     if ($x === '') {
         $x = $this->x;
     }
     if ($y === '') {
         $y = $this->y;
     }
     // get image dimensions
     $imsize = @getimagesize($file);
     if ($imsize === FALSE) {
         // encode spaces on filename
         $file = str_replace(' ', '%20', $file);
         $imsize = @getimagesize($file);
         if ($imsize === FALSE) {
             $this->Error('[Image] No such file or directory in ' . $file);
         }
     }
     // get original image width and height in pixels
     list($pixw, $pixh) = $imsize;
     // calculate image width and height on document
     if ($w <= 0 and $h <= 0) {
         // convert image size to document unit
         $w = $pixw / ($this->imgscale * $this->k);
         $h = $pixh / ($this->imgscale * $this->k);
     } elseif ($w <= 0) {
         $w = $h * $pixw / $pixh;
     } elseif ($h <= 0) {
         $h = $w * $pixh / $pixw;
     }
     // calculate new minimum dimensions in pixels
     $neww = round($w * $this->k * $dpi / $this->dpi);
     $newh = round($h * $this->k * $dpi / $this->dpi);
     // check if resize is necessary (resize is used only to reduce the image)
     if ($neww * $newh >= $pixw * $pixh) {
         $resize = false;
     }
     // check if image has been already added on document
     if (!in_array($file, $this->imagekeys)) {
         //First use of image, get info
         if ($type == '') {
             $fileinfo = pathinfo($file);
             if (isset($fileinfo['extension']) and !empty($fileinfo['extension'])) {
                 $type = $fileinfo['extension'];
             } else {
                 $this->Error('Image file has no extension and no type was specified: ' . $file);
             }
         }
         $type = strtolower($type);
         if ($type == 'jpg') {
             $type = 'jpeg';
         }
         $mqr = get_magic_quotes_runtime();
         set_magic_quotes_runtime(0);
         // Specific image handlers
         $mtd = '_parse' . $type;
         // GD image handler function
         $gdfunction = 'imagecreatefrom' . $type;
         $info = false;
         if (method_exists($this, $mtd) and !($resize and function_exists($gdfunction))) {
             // TCPDF image functions
             $info = $this->{$mtd}($file);
             if ($info == 'pngalpha') {
                 return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
             }
         }
         if (!$info) {
             if (function_exists($gdfunction)) {
                 // GD library
                 $img = $gdfunction($file);
                 if ($resize) {
                     $imgr = imagecreatetruecolor($neww, $newh);
                     imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
                     $info = $this->_toJPEG($imgr);
                 } else {
                     $info = $this->_toJPEG($img);
                 }
             } elseif (extension_loaded('imagick')) {
                 // ImageMagick library
                 $img = new Imagick();
                 $img->readImage($file);
                 if ($resize) {
                     $img->resizeImage($neww, $newh, 10, 1, false);
                 }
                 $img->setCompressionQuality($this->jpeg_quality);
                 $img->setImageFormat('jpeg');
                 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
                 $img->writeImage($tempname);
                 $info = $this->_parsejpeg($tempname);
                 unlink($tempname);
                 $img->destroy();
             } else {
                 return;
             }
         }
         if ($info === false) {
             //If false, we cannot process image
             return;
         }
         set_magic_quotes_runtime($mqr);
         if ($ismask) {
             // force grayscale
             $info['cs'] = 'DeviceGray';
         }
         $info['i'] = $this->numimages + 1;
         if ($imgmask !== false) {
             $info['masked'] = $imgmask;
         }
         // add image to document
         $this->setImageBuffer($file, $info);
     } else {
         $info = $this->getImageBuffer($file);
     }
     // Check whether we need a new page first as this does not fit
     if ($y + $h > $this->PageBreakTrigger and !$this->InFooter and $this->AcceptPageBreak()) {
         // Automatic page break
         $this->AddPage($this->CurOrientation);
         // Reset Y coordinate to the top of next page
         $y = $this->GetY() + $this->cMargin;
     }
     // set bottomcoordinates
     $this->img_rb_y = $y + $h;
     // set alignment
     if ($this->rtl) {
         if ($palign == 'L') {
             $ximg = $this->lMargin;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         } elseif ($palign == 'C') {
             $ximg = ($this->w - $x - $w) / 2;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         } else {
             $ximg = $this->w - $x - $w;
             // set left side coordinate
             $this->img_rb_x = $ximg;
         }
     } else {
         if ($palign == 'R') {
             $ximg = $this->w - $this->rMargin - $w;
             // set left side coordinate
             $this->img_rb_x = $ximg;
         } elseif ($palign == 'C') {
             $ximg = ($this->w - $x - $w) / 2;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         } else {
             $ximg = $x;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         }
     }
     if ($ismask) {
         // embed hidden, ouside the canvas
         $xkimg = $this->pagedim[$this->page]['w'] + 10;
     } else {
         $xkimg = $ximg * $this->k;
     }
     $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q', $w * $this->k, $h * $this->k, $xkimg, ($this->h - ($y + $h)) * $this->k, $info['i']));
     if (!empty($border)) {
         $bx = $x;
         $by = $y;
         $this->x = $ximg;
         $this->y = $y;
         $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
         $this->x = $bx;
         $this->y = $by;
     }
     if ($link) {
         $this->Link($ximg, $y, $w, $h, $link, 0);
     }
     // set pointer to align the successive text/objects
     switch ($align) {
         case 'T':
             $this->y = $y;
             $this->x = $this->img_rb_x;
             break;
         case 'M':
             $this->y = $y + round($h / 2);
             $this->x = $this->img_rb_x;
             break;
         case 'B':
             $this->y = $this->img_rb_y;
             $this->x = $this->img_rb_x;
             break;
         case 'N':
             $this->SetY($this->img_rb_y);
             break;
         default:
             break;
     }
     $this->endlinex = $this->img_rb_x;
     return $info['i'];
 }
Exemple #22
0
 /**
  * Creates a new image given an original path, a new path, a target width and height.
  * Optionally crops image to exactly match given width and height.
  * @param string $originalPath The path to the original image
  * @param string $newpath The path to the new image to be created
  * @param int $width The maximum width of the new image
  * @param int $height The maximum height of the new image
  * @param bool $crop = false Set to true to resize and crop the image, set to false to just resize the image 
  * @return bool
  * @example Resizing from 200x200 to 100x50 with $crop = false will result in a 50 x 50 image (same aspect ratio as source, scaled down to a quarter of size)
  * @example Resizing from 200x200 to 100x50 with $crop = true will result in a 100 x 50 image (same aspect ratio as source, scaled down to a half of size and cropped in height)
  * @example Resizing from 200x200 to 1000x1000 with either $crop = false or $crop = true in a copy of the original image (200x200)
  */
 public function create($originalPath, $newPath, $width, $height, $crop = false)
 {
     // first, we grab the original image. We shouldn't ever get to this function unless the image is valid
     $imageSize = @getimagesize($originalPath);
     if ($imageSize === false) {
         return false;
     }
     $oWidth = $imageSize[0];
     $oHeight = $imageSize[1];
     $finalWidth = 0;
     //For cropping, this is really "scale to width before chopping extra height"
     $finalHeight = 0;
     //For cropping, this is really "scale to height before chopping extra width"
     $do_crop_x = false;
     $do_crop_y = false;
     $crop_src_x = 0;
     $crop_src_y = 0;
     // first, if what we're uploading is actually smaller than width and height, we do nothing
     if ($oWidth < $width && $oHeight < $height) {
         $finalWidth = $oWidth;
         $finalHeight = $oHeight;
         $width = $oWidth;
         $height = $oHeight;
     } else {
         if ($crop && ($height >= $oHeight && $width <= $oWidth)) {
             //crop to width only -- don't scale anything
             $finalWidth = $oWidth;
             $finalHeight = $oHeight;
             $height = $oHeight;
             $do_crop_x = true;
         } else {
             if ($crop && ($width >= $oWidth && $height <= $oHeight)) {
                 //crop to height only -- don't scale anything
                 $finalHeight = $oHeight;
                 $finalWidth = $oWidth;
                 $width = $oWidth;
                 $do_crop_y = true;
             } else {
                 // otherwise, we do some complicated stuff
                 // first, we divide original width and height by new width and height, and find which difference is greater
                 $wDiff = $oWidth / $width;
                 $hDiff = $height != 0 ? $oHeight / $height : 0;
                 if (!$crop && $wDiff > $hDiff) {
                     //no cropping, just resize down based on target width
                     $finalWidth = $width;
                     $finalHeight = $wDiff != 0 ? $oHeight / $wDiff : 0;
                 } else {
                     if (!$crop) {
                         //no cropping, just resize down based on target height
                         $finalWidth = $hDiff != 0 ? $oWidth / $hDiff : 0;
                         $finalHeight = $height;
                     } else {
                         if ($crop && $wDiff > $hDiff) {
                             //resize down to target height, THEN crop off extra width
                             $finalWidth = $hDiff != 0 ? $oWidth / $hDiff : 0;
                             $finalHeight = $height;
                             $do_crop_x = true;
                         } else {
                             if ($crop) {
                                 //resize down to target width, THEN crop off extra height
                                 $finalWidth = $width;
                                 $finalHeight = $wDiff != 0 ? $oHeight / $wDiff : 0;
                                 $do_crop_y = true;
                             }
                         }
                     }
                 }
             }
         }
     }
     //Calculate cropping to center image
     if ($do_crop_x) {
         /*
         //Get half the difference between scaled width and target width,
         // and crop by starting the copy that many pixels over from the left side of the source (scaled) image.
         $nudge = ($width / 10); //I have *no* idea why the width isn't centering exactly -- this seems to fix it though.
         $crop_src_x = ($finalWidth / 2.00) - ($width / 2.00) + $nudge;
         */
         $crop_src_x = round(($oWidth - $width * $oHeight / $height) * 0.5);
     }
     if ($do_crop_y) {
         /*
         //Calculate cropping...
         //Get half the difference between scaled height and target height,
         // and crop by starting the copy that many pixels down from the top of the source (scaled) image.
         $crop_src_y = ($finalHeight / 2.00) - ($height / 2.00);
         */
         $crop_src_y = round(($oHeight - $height * $oWidth / $width) * 0.5);
     }
     $processed = false;
     if (class_exists('Imagick')) {
         try {
             $image = new Imagick();
             $imageRead = false;
             if ($crop) {
                 $image->setSize($finalWidth, $finalHeight);
                 if ($image->readImage($originalPath) === true) {
                     $image->cropThumbnailImage($width, $height);
                     $imageRead = true;
                 }
             } else {
                 $image->setSize($width, $height);
                 if ($image->readImage($originalPath) === true) {
                     $image->thumbnailImage($width, $height, true);
                     $imageRead = true;
                 }
             }
             if ($imageRead) {
                 if ($image->getCompression() == imagick::COMPRESSION_JPEG) {
                     $image->setCompressionQuality($this->jpegCompression);
                 }
                 if ($image->writeImage($newPath) === true) {
                     $processed = true;
                 }
             }
         } catch (Exception $x) {
         }
     }
     if (!$processed) {
         //create "canvas" to put new resized and/or cropped image into
         if ($crop) {
             $image = @imageCreateTrueColor($width, $height);
         } else {
             $image = @imageCreateTrueColor($finalWidth, $finalHeight);
         }
         if ($image === false) {
             return false;
         }
         $im = false;
         switch ($imageSize[2]) {
             case IMAGETYPE_GIF:
                 $im = @imageCreateFromGIF($originalPath);
                 break;
             case IMAGETYPE_JPEG:
                 $im = @imageCreateFromJPEG($originalPath);
                 break;
             case IMAGETYPE_PNG:
                 $im = @imageCreateFromPNG($originalPath);
                 break;
             default:
                 @imagedestroy($image);
                 return false;
         }
         if ($im === false) {
             @imagedestroy($image);
             return false;
         }
         // Better transparency - thanks for the ideas and some code from mediumexposure.com
         if ($imageSize[2] == IMAGETYPE_GIF || $imageSize[2] == IMAGETYPE_PNG) {
             $trnprt_indx = imagecolortransparent($im);
             // If we have a specific transparent color
             if ($trnprt_indx >= 0 && $trnprt_indx < imagecolorstotal($im)) {
                 // Get the original image's transparent color's RGB values
                 $trnprt_color = imagecolorsforindex($im, $trnprt_indx);
                 // Allocate the same color in the new image resource
                 $trnprt_indx = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                 // Completely fill the background of the new image with allocated color.
                 imagefill($image, 0, 0, $trnprt_indx);
                 // Set the background color for new image to transparent
                 imagecolortransparent($image, $trnprt_indx);
             } else {
                 if ($imageSize[2] == IMAGETYPE_PNG) {
                     // Turn off transparency blending (temporarily)
                     imagealphablending($image, false);
                     // Create a new transparent color for image
                     $color = imagecolorallocatealpha($image, 0, 0, 0, 127);
                     // Completely fill the background of the new image with allocated color.
                     imagefill($image, 0, 0, $color);
                     // Restore transparency blending
                     imagesavealpha($image, true);
                 }
             }
         }
         $res = @imageCopyResampled($image, $im, 0, 0, $crop_src_x, $crop_src_y, $finalWidth, $finalHeight, $oWidth, $oHeight);
         @imagedestroy($im);
         if ($res === false) {
             @imagedestroy($image);
             return false;
         }
         $res2 = false;
         switch ($imageSize[2]) {
             case IMAGETYPE_GIF:
                 $res2 = @imageGIF($image, $newPath);
                 break;
             case IMAGETYPE_JPEG:
                 $res2 = @imageJPEG($image, $newPath, $this->jpegCompression);
                 break;
             case IMAGETYPE_PNG:
                 $res2 = @imagePNG($image, $newPath);
                 break;
         }
         @imagedestroy($image);
         if ($res2 === false) {
             return false;
         }
     }
     @chmod($newPath, FILE_PERMISSIONS_MODE);
     return true;
 }
Exemple #23
0
 /**
  * Transform an image using the Imagick PHP extension
  *
  * @param File $image File associated with this thumbnail
  * @param array $params Array with scaler params
  *
  * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
  */
 protected function transformImageMagickExt($image, $params)
 {
     global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea, $wgJpegPixelFormat;
     try {
         $im = new Imagick();
         $im->readImage($params['srcPath']);
         if ($params['mimeType'] == 'image/jpeg') {
             // Sharpening, see bug 6193
             if (($params['physicalWidth'] + $params['physicalHeight']) / ($params['srcWidth'] + $params['srcHeight']) < $wgSharpenReductionThreshold) {
                 // Hack, since $wgSharpenParameter is written specifically for the command line convert
                 list($radius, $sigma) = explode('x', $wgSharpenParameter);
                 $im->sharpenImage($radius, $sigma);
             }
             $qualityVal = isset($params['quality']) ? (string) $params['quality'] : null;
             $im->setCompressionQuality($qualityVal ?: 80);
             if ($params['interlace']) {
                 $im->setInterlaceScheme(Imagick::INTERLACE_JPEG);
             }
             if ($wgJpegPixelFormat) {
                 $factors = $this->imageMagickSubsampling($wgJpegPixelFormat);
                 $im->setSamplingFactors($factors);
             }
         } elseif ($params['mimeType'] == 'image/png') {
             $im->setCompressionQuality(95);
             if ($params['interlace']) {
                 $im->setInterlaceScheme(Imagick::INTERLACE_PNG);
             }
         } elseif ($params['mimeType'] == 'image/gif') {
             if ($this->getImageArea($image) > $wgMaxAnimatedGifArea) {
                 // Extract initial frame only; we're so big it'll
                 // be a total drag. :P
                 $im->setImageScene(0);
             } elseif ($this->isAnimatedImage($image)) {
                 // Coalesce is needed to scale animated GIFs properly (bug 1017).
                 $im = $im->coalesceImages();
             }
             // GIF interlacing is only available since 6.3.4
             $v = Imagick::getVersion();
             preg_match('/ImageMagick ([0-9]+\\.[0-9]+\\.[0-9]+)/', $v['versionString'], $v);
             if ($params['interlace'] && version_compare($v[1], '6.3.4') >= 0) {
                 $im->setInterlaceScheme(Imagick::INTERLACE_GIF);
             }
         }
         $rotation = isset($params['disableRotation']) ? 0 : $this->getRotation($image);
         list($width, $height) = $this->extractPreRotationDimensions($params, $rotation);
         $im->setImageBackgroundColor(new ImagickPixel('white'));
         // Call Imagick::thumbnailImage on each frame
         foreach ($im as $i => $frame) {
             if (!$frame->thumbnailImage($width, $height, false)) {
                 return $this->getMediaTransformError($params, "Error scaling frame {$i}");
             }
         }
         $im->setImageDepth(8);
         if ($rotation) {
             if (!$im->rotateImage(new ImagickPixel('white'), 360 - $rotation)) {
                 return $this->getMediaTransformError($params, "Error rotating {$rotation} degrees");
             }
         }
         if ($this->isAnimatedImage($image)) {
             wfDebug(__METHOD__ . ": Writing animated thumbnail\n");
             // This is broken somehow... can't find out how to fix it
             $result = $im->writeImages($params['dstPath'], true);
         } else {
             $result = $im->writeImage($params['dstPath']);
         }
         if (!$result) {
             return $this->getMediaTransformError($params, "Unable to write thumbnail to {$params['dstPath']}");
         }
     } catch (ImagickException $e) {
         return $this->getMediaTransformError($params, $e->getMessage());
     }
     return false;
 }
Exemple #24
0
 /**
  * Puts an image in the page.
  * The upper-left corner must be given.
  * The dimensions can be specified in different ways:<ul>
  * <li>explicit width and height (expressed in user unit)</li>
  * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
  * The format can be specified explicitly or inferred from the file extension.<br />
  * It is possible to put a link on the image.<br />
  * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  * @param string $file Name of the file containing the image.
  * @param float $x Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  * @param float $y Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  * @param mixed $link URL or identifier returned by AddLink().
  * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  * @param mixed $resize If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
  * @param int $dpi dot-per-inch resolution used on resize
  * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  * @param boolean $ismask true if this image is a mask, false otherwise
  * @param mixed $imgmask image object returned by this function or false
  * @param mixed $border Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
  * @param boolean $hidden if true do not display the image.
  * @param boolean $fitonpage if true the image is resized to not exceed page dimensions.
  * @return image information
  * @access public
  * @since 1.1
  */
 public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300, $palign = '', $ismask = false, $imgmask = false, $border = 0, $fitbox = false, $hidden = false, $fitonpage = false)
 {
     if ($x === '') {
         $x = $this->x;
     }
     if ($y === '') {
         $y = $this->y;
     }
     // check page for no-write regions and adapt page margins if necessary
     $this->checkPageRegions($h, $x, $y);
     $cached_file = false;
     // true when the file is cached
     // get image dimensions
     $imsize = @getimagesize($file);
     if ($imsize === FALSE) {
         // try to encode spaces on filename
         $file = str_replace(' ', '%20', $file);
         $imsize = @getimagesize($file);
         if ($imsize === FALSE) {
             if (function_exists('curl_init')) {
                 // try to get remote file data using cURL
                 $cs = curl_init();
                 // curl session
                 curl_setopt($cs, CURLOPT_URL, $file);
                 curl_setopt($cs, CURLOPT_BINARYTRANSFER, true);
                 curl_setopt($cs, CURLOPT_FAILONERROR, true);
                 curl_setopt($cs, CURLOPT_RETURNTRANSFER, true);
                 curl_setopt($cs, CURLOPT_CONNECTTIMEOUT, 5);
                 curl_setopt($cs, CURLOPT_TIMEOUT, 30);
                 $imgdata = curl_exec($cs);
                 curl_close($cs);
                 if ($imgdata !== FALSE) {
                     // copy image to cache
                     $file = tempnam(K_PATH_CACHE, 'img_');
                     $fp = fopen($file, 'w');
                     fwrite($fp, $imgdata);
                     fclose($fp);
                     unset($imgdata);
                     $cached_file = true;
                     $imsize = @getimagesize($file);
                     if ($imsize === FALSE) {
                         unlink($file);
                         $cached_file = false;
                     }
                 }
             } elseif ($w > 0 and $h > 0) {
                 // get measures from specified data
                 $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
                 $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
                 $imsize = array($pw, $ph);
             }
         }
     }
     if ($imsize === FALSE) {
         $this->Error('[Image] Unable to get image: ' . $file);
     }
     // get original image width and height in pixels
     list($pixw, $pixh) = $imsize;
     // calculate image width and height on document
     if ($w <= 0 and $h <= 0) {
         // convert image size to document unit
         $w = $this->pixelsToUnits($pixw);
         $h = $this->pixelsToUnits($pixh);
     } elseif ($w <= 0) {
         $w = $h * $pixw / $pixh;
     } elseif ($h <= 0) {
         $h = $w * $pixh / $pixw;
     } elseif ($fitbox and $w > 0 and $h > 0) {
         // scale image dimensions proportionally to fit within the ($w, $h) box
         if ($w * $pixh / ($h * $pixw) < 1) {
             $h = $w * $pixh / $pixw;
         } else {
             $w = $h * $pixw / $pixh;
         }
     }
     // fit the image on available space
     $this->fitBlock($w, $h, $x, $y, $fitonpage);
     // calculate new minimum dimensions in pixels
     $neww = round($w * $this->k * $dpi / $this->dpi);
     $newh = round($h * $this->k * $dpi / $this->dpi);
     // check if resize is necessary (resize is used only to reduce the image)
     $newsize = $neww * $newh;
     $pixsize = $pixw * $pixh;
     if (intval($resize) == 2) {
         $resize = true;
     } elseif ($newsize >= $pixsize) {
         $resize = false;
     }
     // check if image has been already added on document
     $newimage = true;
     if (in_array($file, $this->imagekeys)) {
         $newimage = false;
         // get existing image data
         $info = $this->getImageBuffer($file);
         // check if the newer image is larger
         $oldsize = $info['w'] * $info['h'];
         if ($oldsize < $newsize and $resize or $oldsize < $pixsize and !$resize) {
             $newimage = true;
         }
     }
     if ($newimage) {
         //First use of image, get info
         $type = strtolower($type);
         if ($type == '') {
             $type = $this->getImageFileType($file, $imsize);
         } elseif ($type == 'jpg') {
             $type = 'jpeg';
         }
         $mqr = $this->get_mqr();
         $this->set_mqr(false);
         // Specific image handlers
         $mtd = '_parse' . $type;
         // GD image handler function
         $gdfunction = 'imagecreatefrom' . $type;
         $info = false;
         if (method_exists($this, $mtd) and !($resize and function_exists($gdfunction))) {
             // TCPDF image functions
             $info = $this->{$mtd}($file);
             if ($info == 'pngalpha') {
                 return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
             }
         }
         if (!$info) {
             if (function_exists($gdfunction)) {
                 // GD library
                 $img = $gdfunction($file);
                 if ($resize) {
                     $imgr = imagecreatetruecolor($neww, $newh);
                     if ($type == 'gif' or $type == 'png') {
                         $imgr = $this->_setGDImageTransparency($imgr, $img);
                     }
                     imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
                     if ($type == 'gif' or $type == 'png') {
                         $info = $this->_toPNG($imgr);
                     } else {
                         $info = $this->_toJPEG($imgr);
                     }
                 } else {
                     if ($type == 'gif' or $type == 'png') {
                         $info = $this->_toPNG($img);
                     } else {
                         $info = $this->_toJPEG($img);
                     }
                 }
             } elseif (extension_loaded('imagick')) {
                 // ImageMagick library
                 $img = new Imagick();
                 if ($type == 'SVG') {
                     // get SVG file content
                     $svgimg = file_get_contents($file);
                     // get width and height
                     $regs = array();
                     if (preg_match('/<svg([^\\>]*)>/si', $svgimg, $regs)) {
                         $svgtag = $regs[1];
                         $tmp = array();
                         if (preg_match('/[\\s]+width[\\s]*=[\\s]*"([^"]*)"/si', $svgtag, $tmp)) {
                             $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
                             $owu = sprintf('%.3F', $ow * $dpi / 72) . $this->pdfunit;
                             $svgtag = preg_replace('/[\\s]+width[\\s]*=[\\s]*"[^"]*"/si', ' width="' . $owu . '"', $svgtag, 1);
                         } else {
                             $ow = $w;
                         }
                         $tmp = array();
                         if (preg_match('/[\\s]+height[\\s]*=[\\s]*"([^"]*)"/si', $svgtag, $tmp)) {
                             $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
                             $ohu = sprintf('%.3F', $oh * $dpi / 72) . $this->pdfunit;
                             $svgtag = preg_replace('/[\\s]+height[\\s]*=[\\s]*"[^"]*"/si', ' height="' . $ohu . '"', $svgtag, 1);
                         } else {
                             $oh = $h;
                         }
                         $tmp = array();
                         if (!preg_match('/[\\s]+viewBox[\\s]*=[\\s]*"[\\s]*([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]*"/si', $svgtag, $tmp)) {
                             $vbw = $ow * $this->imgscale * $this->k;
                             $vbh = $oh * $this->imgscale * $this->k;
                             $vbox = sprintf(' viewBox="0 0 %.3F %.3F" ', $vbw, $vbh);
                             $svgtag = $vbox . $svgtag;
                         }
                         $svgimg = preg_replace('/<svg([^\\>]*)>/si', '<svg' . $svgtag . '>', $svgimg, 1);
                     }
                     $img->readImageBlob($svgimg);
                 } else {
                     $img->readImage($file);
                 }
                 if ($resize) {
                     $img->resizeImage($neww, $newh, 10, 1, false);
                 }
                 $img->setCompressionQuality($this->jpeg_quality);
                 $img->setImageFormat('jpeg');
                 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
                 $img->writeImage($tempname);
                 $info = $this->_parsejpeg($tempname);
                 unlink($tempname);
                 $img->destroy();
             } else {
                 return;
             }
         }
         if ($info === false) {
             //If false, we cannot process image
             return;
         }
         $this->set_mqr($mqr);
         if ($ismask) {
             // force grayscale
             $info['cs'] = 'DeviceGray';
         }
         $info['i'] = $this->numimages;
         if (!in_array($file, $this->imagekeys)) {
             ++$info['i'];
         }
         if ($imgmask !== false) {
             $info['masked'] = $imgmask;
         }
         // add image to document
         $this->setImageBuffer($file, $info);
     }
     if ($cached_file) {
         // remove cached file
         unlink($file);
     }
     // set alignment
     $this->img_rb_y = $y + $h;
     // set alignment
     if ($this->rtl) {
         if ($palign == 'L') {
             $ximg = $this->lMargin;
         } elseif ($palign == 'C') {
             $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
         } elseif ($palign == 'R') {
             $ximg = $this->w - $this->rMargin - $w;
         } else {
             $ximg = $x - $w;
         }
         $this->img_rb_x = $ximg;
     } else {
         if ($palign == 'L') {
             $ximg = $this->lMargin;
         } elseif ($palign == 'C') {
             $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
         } elseif ($palign == 'R') {
             $ximg = $this->w - $this->rMargin - $w;
         } else {
             $ximg = $x;
         }
         $this->img_rb_x = $ximg + $w;
     }
     if ($ismask or $hidden) {
         // image is not displayed
         return $info['i'];
     }
     $xkimg = $ximg * $this->k;
     $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%u Do Q', $w * $this->k, $h * $this->k, $xkimg, ($this->h - ($y + $h)) * $this->k, $info['i']));
     if (!empty($border)) {
         $bx = $this->x;
         $by = $this->y;
         $this->x = $ximg;
         if ($this->rtl) {
             $this->x += $w;
         }
         $this->y = $y;
         $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
         $this->x = $bx;
         $this->y = $by;
     }
     if ($link) {
         $this->Link($ximg, $y, $w, $h, $link, 0);
     }
     // set pointer to align the next text/objects
     switch ($align) {
         case 'T':
             $this->y = $y;
             $this->x = $this->img_rb_x;
             break;
         case 'M':
             $this->y = $y + round($h / 2);
             $this->x = $this->img_rb_x;
             break;
         case 'B':
             $this->y = $this->img_rb_y;
             $this->x = $this->img_rb_x;
             break;
         case 'N':
             $this->SetY($this->img_rb_y);
             break;
         default:
             break;
     }
     $this->endlinex = $this->img_rb_x;
     if ($this->inxobj) {
         // we are inside an XObject template
         $this->xobjects[$this->xobjid]['images'][] = $info['i'];
     }
     return $info['i'];
 }
Exemple #25
0
 /**
  * Puts an image in the page.
  * The upper-left corner must be given.
  * The dimensions can be specified in different ways:<ul>
  * <li>explicit width and height (expressed in user unit)</li>
  * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
  * The format can be specified explicitly or inferred from the file extension.<br />
  * It is possible to put a link on the image.<br />
  * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  * @param string $file Name of the file containing the image.
  * @param float $x Abscissa of the upper-left corner.
  * @param float $y Ordinate of the upper-left corner.
  * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  * @param mixed $link URL or identifier returned by AddLink().
  * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  * @param mixed $resize If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
  * @param int $dpi dot-per-inch resolution used on resize
  * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  * @param boolean $ismask true if this image is a mask, false otherwise
  * @param mixed $imgmask image object returned by this function or false
  * @param mixed $border Indicates if borders must be drawn around the image. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
  * @param boolean $fitbox If true scale image dimensions proportionally to fit within the ($w, $h) box.
  * @param boolean $hidden if true do not display the image.
  * @param boolean $fitonpage if true the image is resized to not exceed page dimensions.
  * @return image information
  * @access public
  * @since 1.1
  */
 public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300, $palign = '', $ismask = false, $imgmask = false, $border = 0, $fitbox = false, $hidden = false, $fitonpage = false)
 {
     if ($x === '') {
         $x = $this->x;
     }
     if ($y === '') {
         $y = $this->y;
     }
     // get image dimensions
     $imsize = @getimagesize($file);
     if ($imsize === FALSE) {
         // encode spaces on filename
         $file = str_replace(' ', '%20', $file);
         $imsize = @getimagesize($file);
         if ($imsize === FALSE) {
             $this->Error('[Image] No such file or directory in ' . $file);
         }
     }
     // get original image width and height in pixels
     list($pixw, $pixh) = $imsize;
     // calculate image width and height on document
     if ($w <= 0 and $h <= 0) {
         // convert image size to document unit
         $w = $this->pixelsToUnits($pixw);
         $h = $this->pixelsToUnits($pixh);
     } elseif ($w <= 0) {
         $w = $h * $pixw / $pixh;
     } elseif ($h <= 0) {
         $h = $w * $pixh / $pixw;
     } elseif ($fitbox and $w > 0 and $h > 0) {
         // scale image dimensions proportionally to fit within the ($w, $h) box
         if ($w * $pixh / ($h * $pixw) < 1) {
             $h = $w * $pixh / $pixw;
         } else {
             $w = $h * $pixw / $pixh;
         }
     }
     // Check whether we need a new page first as this does not fit
     $prev_x = $this->x;
     if ($this->checkPageBreak($h, $y)) {
         $y = $this->y;
         if ($this->rtl) {
             $x += $prev_x - $this->x;
         } else {
             $x += $this->x - $prev_x;
         }
     }
     // resize image to be contained on a single page
     if ($fitonpage) {
         $ratio_wh = $w / $h;
         if ($y + $h > $this->PageBreakTrigger) {
             $h = $this->PageBreakTrigger - $y;
             $w = $h * $ratio_wh;
         }
         if ($x + $w > $this->w - $this->rMargin) {
             $w = $this->w - $this->rMargin - $x;
             $h = $w / $ratio_wh;
         }
     }
     // calculate new minimum dimensions in pixels
     $neww = round($w * $this->k * $dpi / $this->dpi);
     $newh = round($h * $this->k * $dpi / $this->dpi);
     // check if resize is necessary (resize is used only to reduce the image)
     $newsize = $neww * $newh;
     $pixsize = $pixw * $pixh;
     if (intval($resize) == 2) {
         $resize = true;
     } elseif ($newsize >= $pixsize) {
         $resize = false;
     }
     // check if image has been already added on document
     $newimage = true;
     if (in_array($file, $this->imagekeys)) {
         $newimage = false;
         // get existing image data
         $info = $this->getImageBuffer($file);
         // check if the newer image is larger
         $oldsize = $info['w'] * $info['h'];
         if ($oldsize < $newsize and $resize or $oldsize < $pixsize and !$resize) {
             $newimage = true;
         }
     }
     if ($newimage) {
         //First use of image, get info
         if ($type == '') {
             $type = $this->getImageFileType($file, $imsize);
         }
         $mqr = $this->get_mqr();
         $this->set_mqr(false);
         // Specific image handlers
         $mtd = '_parse' . $type;
         // GD image handler function
         $gdfunction = 'imagecreatefrom' . $type;
         $info = false;
         if (method_exists($this, $mtd) and !($resize and function_exists($gdfunction))) {
             // TCPDF image functions
             $info = $this->{$mtd}($file);
             if ($info == 'pngalpha') {
                 return $this->ImagePngAlpha($file, $x, $y, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign);
             }
         }
         if (!$info) {
             if (function_exists($gdfunction)) {
                 // GD library
                 $img = $gdfunction($file);
                 if ($resize) {
                     $imgr = imagecreatetruecolor($neww, $newh);
                     if ($type == 'gif' or $type == 'png') {
                         $imgr = $this->_setGDImageTransparency($imgr, $img);
                     }
                     imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
                     if ($type == 'gif' or $type == 'png') {
                         $info = $this->_toPNG($imgr);
                     } else {
                         $info = $this->_toJPEG($imgr);
                     }
                 } else {
                     if ($type == 'gif' or $type == 'png') {
                         $info = $this->_toPNG($img);
                     } else {
                         $info = $this->_toJPEG($img);
                     }
                 }
             } elseif (extension_loaded('imagick')) {
                 // ImageMagick library
                 $img = new Imagick();
                 $img->readImage($file);
                 if ($resize) {
                     $img->resizeImage($neww, $newh, 10, 1, false);
                 }
                 $img->setCompressionQuality($this->jpeg_quality);
                 $img->setImageFormat('jpeg');
                 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
                 $img->writeImage($tempname);
                 $info = $this->_parsejpeg($tempname);
                 unlink($tempname);
                 $img->destroy();
             } else {
                 return;
             }
         }
         if ($info === false) {
             //If false, we cannot process image
             return;
         }
         $this->set_mqr($mqr);
         if ($ismask) {
             // force grayscale
             $info['cs'] = 'DeviceGray';
         }
         $info['i'] = $this->numimages;
         if (!in_array($file, $this->imagekeys)) {
             ++$info['i'];
         }
         if ($imgmask !== false) {
             $info['masked'] = $imgmask;
         }
         // add image to document
         $this->setImageBuffer($file, $info);
     }
     // set bottomcoordinates
     $this->img_rb_y = $y + $h;
     // set alignment
     if ($this->rtl) {
         if ($palign == 'L') {
             $ximg = $this->lMargin;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         } elseif ($palign == 'C') {
             $ximg = ($this->w - $x - $w) / 2;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         } else {
             $ximg = $this->w - $x - $w;
             // set left side coordinate
             $this->img_rb_x = $ximg;
         }
     } else {
         if ($palign == 'R') {
             $ximg = $this->w - $this->rMargin - $w;
             // set left side coordinate
             $this->img_rb_x = $ximg;
         } elseif ($palign == 'C') {
             $ximg = ($this->w - $x - $w) / 2;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         } else {
             $ximg = $x;
             // set right side coordinate
             $this->img_rb_x = $ximg + $w;
         }
     }
     if ($ismask or $hidden) {
         // image is not displayed
         return $info['i'];
     }
     $xkimg = $ximg * $this->k;
     $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q', $w * $this->k, $h * $this->k, $xkimg, ($this->h - ($y + $h)) * $this->k, $info['i']));
     if (!empty($border)) {
         $bx = $x;
         $by = $y;
         $this->x = $ximg;
         $this->y = $y;
         $this->Cell($w, $h, '', $border, 0, '', 0, '', 0);
         $this->x = $bx;
         $this->y = $by;
     }
     if ($link) {
         $this->Link($ximg, $y, $w, $h, $link, 0);
     }
     // set pointer to align the successive text/objects
     switch ($align) {
         case 'T':
             $this->y = $y;
             $this->x = $this->img_rb_x;
             break;
         case 'M':
             $this->y = $y + round($h / 2);
             $this->x = $this->img_rb_x;
             break;
         case 'B':
             $this->y = $this->img_rb_y;
             $this->x = $this->img_rb_x;
             break;
         case 'N':
             $this->SetY($this->img_rb_y);
             break;
         default:
             break;
     }
     $this->endlinex = $this->img_rb_x;
     return $info['i'];
 }
 /**
  * Used by custom RenderImage method to output the final image.
  * Uses $this->strImageType to determine type of image to be rendered.
  * This version is to be used when rendering an image using the Imagick library.
  * 
  * If strPath is not set, output to the screen.  If it is, save to strPath.
  *
  * @param Imagick $objFinalImage image as an instance of the Imagick class
  * @param string $strPath
  */
 protected function RenderImageMagickHelper($objFinalImage, $strPath)
 {
     // Output the Image (if path isn't specified, output to buffer.  Otherwise, output to disk)
     if (!$strPath) {
         $strPath = $this->strImagickTempFilePath . '/image_' . str_replace('.', '_', microtime(true));
         // Output to a temporary location
         switch ($this->strImageType) {
             case QImageType::Gif:
                 $strPath .= '.gif';
                 $objFinalImage->setImageFormat('gif');
                 header('Content-Type: image/gif');
                 break;
             case QImageType::AnimatedGif:
                 $strPath .= '.gif';
                 $objFinalImage->setImageFormat('gif');
                 header('Content-Type: image/gif');
                 break;
             case QImageType::Jpeg:
                 $strPath .= '.jpg';
                 $objFinalImage->setImageFormat('jpeg');
                 $objFinalImage->setCompressionQuality($this->intJpegQuality);
                 header('Content-Type: image/jpeg');
                 break;
             default:
                 $strPath .= '.png';
                 $objFinalImage->setImageFormat('png');
                 header('Content-Type: image/png');
                 break;
         }
         if ($this->strImageType == QImageType::AnimatedGif) {
             file_put_contents($strPath, $objFinalImage->GetImagesBlob());
         } else {
             $objFinalImage->writeImage($strPath);
         }
         QApplication::$ProcessOutput = false;
         header('Cache-Control: cache');
         header('Expires: Wed, 20 Mar 2019 05:00:00 GMT');
         header('Pragma: cache');
         print file_get_contents($strPath);
         unlink($strPath);
     } else {
         // Make Directory
         QApplication::MakeDirectory(dirname($strPath), 0777);
         // Output to Disk
         switch ($this->strImageType) {
             case QImageType::Gif:
                 $objFinalImage->setImageFormat('gif');
                 break;
             case QImageType::AnimatedGif:
                 $objFinalImage->setImageFormat('gif');
                 break;
             case QImageType::Jpeg:
                 $objFinalImage->setImageFormat('jpeg');
                 $objFinalImage->setCompressionQuality($this->intJpegQuality);
                 break;
             default:
                 $objFinalImage->setImageFormat('png');
                 break;
         }
         $objFinalImage->writeImage($strPath);
         chmod($strPath, 0777);
     }
     $objFinalImage->Destroy();
 }
Exemple #27
0
 /**
  * Transform an image using the Imagick PHP extension
  *
  * @param $image File File associated with this thumbnail
  * @param $params array Array with scaler params
  *
  * @return MediaTransformError Error object if error occured, false (=no error) otherwise
  */
 protected function transformImageMagickExt($image, $params)
 {
     global $wgSharpenReductionThreshold, $wgSharpenParameter, $wgMaxAnimatedGifArea;
     try {
         $im = new Imagick();
         $im->readImage($params['srcPath']);
         if ($params['mimeType'] == 'image/jpeg') {
             // Sharpening, see bug 6193
             if (($params['physicalWidth'] + $params['physicalHeight']) / ($params['srcWidth'] + $params['srcHeight']) < $wgSharpenReductionThreshold) {
                 // Hack, since $wgSharpenParamater is written specifically for the command line convert
                 list($radius, $sigma) = explode('x', $wgSharpenParameter);
                 $im->sharpenImage($radius, $sigma);
             }
             $im->setCompressionQuality(80);
         } elseif ($params['mimeType'] == 'image/png') {
             $im->setCompressionQuality(95);
         } elseif ($params['mimeType'] == 'image/gif') {
             if ($this->getImageArea($image, $params['srcWidth'], $params['srcHeight']) > $wgMaxAnimatedGifArea) {
                 // Extract initial frame only; we're so big it'll
                 // be a total drag. :P
                 $im->setImageScene(0);
             } elseif ($this->isAnimatedImage($image)) {
                 // Coalesce is needed to scale animated GIFs properly (bug 1017).
                 $im = $im->coalesceImages();
             }
         }
         $rotation = $this->getRotation($image);
         list($width, $height) = $this->extractPreRotationDimensions($params, $rotation);
         $im->setImageBackgroundColor(new ImagickPixel('white'));
         // Call Imagick::thumbnailImage on each frame
         foreach ($im as $i => $frame) {
             if (!$frame->thumbnailImage($width, $height, false)) {
                 return $this->getMediaTransformError($params, "Error scaling frame {$i}");
             }
         }
         $im->setImageDepth(8);
         if ($rotation) {
             if (!$im->rotateImage(new ImagickPixel('white'), 360 - $rotation)) {
                 return $this->getMediaTransformError($params, "Error rotating {$rotation} degrees");
             }
         }
         if ($this->isAnimatedImage($image)) {
             wfDebug(__METHOD__ . ": Writing animated thumbnail\n");
             // This is broken somehow... can't find out how to fix it
             $result = $im->writeImages($params['dstPath'], true);
         } else {
             $result = $im->writeImage($params['dstPath']);
         }
         if (!$result) {
             return $this->getMediaTransformError($params, "Unable to write thumbnail to {$params['dstPath']}");
         }
     } catch (ImagickException $e) {
         return $this->getMediaTransformError($params, $e->getMessage());
     }
     return false;
 }
Exemple #28
0
 /**
  * 风尚单品第一张图上传
  * */
 public static function fashionitemsupload($upfile, $upload11)
 {
     $uptypes = array('image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png');
     $error = "";
     $max_file_size = 5240000;
     //上传文件大小限制, 单位BYTE
     $random = rand(0, 9);
     $imgtype = "";
     switch ($_FILES[$upfile]['type']) {
         case "image/gif":
             $imgtype = ".gif";
             break;
         case "image/jpeg":
             $imgtype = ".jpg";
             break;
         case "image/pjpeg":
             $imgtype = ".jpg";
             break;
         case "image/x-png":
             $imgtype = ".png";
             break;
         case "image/png":
             $imgtype = ".png";
             break;
     }
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $file = $_FILES[$upfile];
         if ($file['name'] == "") {
             $error = "文件为空";
         } else {
             if ($max_file_size < $file["size"]) {
                 $error = "文件太大";
             } else {
                 if (!in_array($file["type"], $uptypes)) {
                     $error = "只能上传图像";
                 } else {
                     $error = $destination_folder = $upload11 . date('YmdHis') . $random . $imgtype;
                     $name = $upload11 . 'zancun' . $imgtype;
                     if (move_uploaded_file($_FILES[$upfile]["tmp_name"], $destination_folder)) {
                         //				    			echo "上传图片成功";
                         //echo "W_00".$_FILES[$upfile]["tmp_name"];
                         /* 图片路径 */
                         $filepath = $error;
                         /* 输出图片路径 */
                         $refilepath_m = $filepath . ".m.jpg";
                         //990*368的.m.jpg和尺寸小图234*87的.s.jpg
                         $refilepath_s = $filepath . ".s.jpg";
                         //定义画布大小
                         $canvas = new Imagick($error);
                         $canvas->thumbnailImage(990, 368, true);
                         $canvas->setImageFormat('jpeg');
                         $canvas->setCompressionQuality(100);
                         $canvas->writeImage($refilepath_m);
                         $canvas->destroy();
                         $canvas2 = new Imagick($error);
                         $canvas2->thumbnailImage(234, 87, true);
                         $canvas2->setImageFormat('jpeg');
                         $canvas2->setCompressionQuality(100);
                         $canvas2->writeImage($refilepath_s);
                         $canvas2->destroy();
                         //
                     } else {
                         $error = "上传图片失败";
                     }
                 }
             }
         }
     }
     return $error;
 }
Exemple #29
0
 /**
  * Puts an image in the page.
  * The upper-left corner must be given.
  * The dimensions can be specified in different ways:<ul>
  * <li>explicit width and height (expressed in user unit)</li>
  * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
  * The format can be specified explicitly or inferred from the file extension.<br />
  * It is possible to put a link on the image.<br />
  * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  * @param $file (string) Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg').
  * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  * @param $link (mixed) URL or identifier returned by AddLink().
  * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  * @param $resize (mixed) If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
  * @param $dpi (int) dot-per-inch resolution used on resize
  * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  * @param $ismask (boolean) true if this image is a mask, false otherwise
  * @param $imgmask (mixed) image object returned by this function or false
  * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  * @param $fitbox (mixed) If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom).
  * @param $hidden (boolean) If true do not display the image.
  * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  * @param $altimgs (array) Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
  * @return image information
  * @public
  * @since 1.1
  */
 public function Image($file, $x = '', $y = '', $w = 0, $h = 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300, $palign = '', $ismask = false, $imgmask = false, $border = 0, $fitbox = false, $hidden = false, $fitonpage = false, $alt = false, $altimgs = array())
 {
     if ($this->state != 2) {
         return;
     }
     if ($x === '') {
         $x = $this->x;
     }
     if ($y === '') {
         $y = $this->y;
     }
     // check page for no-write regions and adapt page margins if necessary
     list($x, $y) = $this->checkPageRegions($h, $x, $y);
     $exurl = '';
     // external streams
     $imsize = FALSE;
     // check if we are passing an image as file or string
     if ($file[0] === '@') {
         // image from string
         $imgdata = substr($file, 1);
     } else {
         // image file
         if ($file[0] === '*') {
             // image as external stream
             $file = substr($file, 1);
             $exurl = $file;
         }
         // check if is local file
         if (!@file_exists($file)) {
             // encode spaces on filename (file is probably an URL)
             $file = str_replace(' ', '%20', $file);
         }
         if (@file_exists($file)) {
             // get image dimensions
             $imsize = @getimagesize($file);
         }
         if ($imsize === FALSE) {
             $imgdata = TCPDF_STATIC::fileGetContents($file);
         }
     }
     if (isset($imgdata) and $imgdata !== FALSE) {
         // copy image to cache
         $file = TCPDF_STATIC::getObjFilename('img');
         $fp = fopen($file, 'w');
         fwrite($fp, $imgdata);
         fclose($fp);
         unset($imgdata);
         $imsize = @getimagesize($file);
         if ($imsize === FALSE) {
             unlink($file);
         } else {
             $this->cached_files[] = $file;
         }
     }
     if ($imsize === FALSE) {
         if ($w > 0 and $h > 0) {
             // get measures from specified data
             $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
             $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
             $imsize = array($pw, $ph);
         } else {
             $this->Error('[Image] Unable to get image: ' . $file);
         }
     }
     // file hash
     $filehash = md5($this->file_id . $file);
     // get original image width and height in pixels
     list($pixw, $pixh) = $imsize;
     // calculate image width and height on document
     if ($w <= 0 and $h <= 0) {
         // convert image size to document unit
         $w = $this->pixelsToUnits($pixw);
         $h = $this->pixelsToUnits($pixh);
     } elseif ($w <= 0) {
         $w = $h * $pixw / $pixh;
     } elseif ($h <= 0) {
         $h = $w * $pixh / $pixw;
     } elseif ($fitbox !== false and $w > 0 and $h > 0) {
         if (strlen($fitbox) !== 2) {
             // set default alignment
             $fitbox = '--';
         }
         // scale image dimensions proportionally to fit within the ($w, $h) box
         if ($w * $pixh / ($h * $pixw) < 1) {
             // store current height
             $oldh = $h;
             // calculate new height
             $h = $w * $pixh / $pixw;
             // height difference
             $hdiff = $oldh - $h;
             // vertical alignment
             switch (strtoupper($fitbox[1])) {
                 case 'T':
                     break;
                 case 'M':
                     $y += $hdiff / 2;
                     break;
                 case 'B':
                     $y += $hdiff;
                     break;
             }
         } else {
             // store current width
             $oldw = $w;
             // calculate new width
             $w = $h * $pixw / $pixh;
             // width difference
             $wdiff = $oldw - $w;
             // horizontal alignment
             switch (strtoupper($fitbox[0])) {
                 case 'L':
                     if ($this->rtl) {
                         $x -= $wdiff;
                     }
                     break;
                 case 'C':
                     if ($this->rtl) {
                         $x -= $wdiff / 2;
                     } else {
                         $x += $wdiff / 2;
                     }
                     break;
                 case 'R':
                     if (!$this->rtl) {
                         $x += $wdiff;
                     }
                     break;
             }
         }
     }
     // fit the image on available space
     list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
     // calculate new minimum dimensions in pixels
     $neww = round($w * $this->k * $dpi / $this->dpi);
     $newh = round($h * $this->k * $dpi / $this->dpi);
     // check if resize is necessary (resize is used only to reduce the image)
     $newsize = $neww * $newh;
     $pixsize = $pixw * $pixh;
     if (intval($resize) == 2) {
         $resize = true;
     } elseif ($newsize >= $pixsize) {
         $resize = false;
     }
     // check if image has been already added on document
     $newimage = true;
     if (in_array($file, $this->imagekeys)) {
         $newimage = false;
         // get existing image data
         $info = $this->getImageBuffer($file);
         if (substr($file, 0, -34) != K_PATH_CACHE . 'msk') {
             // check if the newer image is larger
             $oldsize = $info['w'] * $info['h'];
             if ($oldsize < $newsize and $resize or $oldsize < $pixsize and !$resize) {
                 $newimage = true;
             }
         }
     } elseif (substr($file, 0, -34) != K_PATH_CACHE . 'msk') {
         // check for cached images with alpha channel
         $tempfile_plain = K_PATH_CACHE . 'mskp_' . $filehash;
         $tempfile_alpha = K_PATH_CACHE . 'mska_' . $filehash;
         if (in_array($tempfile_plain, $this->imagekeys)) {
             // get existing image data
             $info = $this->getImageBuffer($tempfile_plain);
             // check if the newer image is larger
             $oldsize = $info['w'] * $info['h'];
             if ($oldsize < $newsize and $resize or $oldsize < $pixsize and !$resize) {
                 $newimage = true;
             } else {
                 $newimage = false;
                 // embed mask image
                 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
                 // embed image, masked with previously embedded mask
                 return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
             }
         }
     }
     if ($newimage) {
         //First use of image, get info
         $type = strtolower($type);
         if ($type == '') {
             $type = TCPDF_IMAGES::getImageFileType($file, $imsize);
         } elseif ($type == 'jpg') {
             $type = 'jpeg';
         }
         $mqr = TCPDF_STATIC::get_mqr();
         TCPDF_STATIC::set_mqr(false);
         // Specific image handlers (defined on TCPDF_IMAGES CLASS)
         $mtd = '_parse' . $type;
         // GD image handler function
         $gdfunction = 'imagecreatefrom' . $type;
         $info = false;
         if (method_exists('TCPDF_IMAGES', $mtd) and !($resize and (function_exists($gdfunction) or extension_loaded('imagick')))) {
             // TCPDF image functions
             $info = TCPDF_IMAGES::$mtd($file);
             if ($info === 'pngalpha' or isset($info['trns']) and !empty($info['trns'])) {
                 return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
             }
         }
         if ($info === false and function_exists($gdfunction)) {
             try {
                 // GD library
                 $img = $gdfunction($file);
                 if ($resize) {
                     $imgr = imagecreatetruecolor($neww, $newh);
                     if ($type == 'gif' or $type == 'png') {
                         $imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
                     }
                     imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
                     if ($type == 'gif' or $type == 'png') {
                         $info = TCPDF_IMAGES::_toPNG($imgr);
                     } else {
                         $info = TCPDF_IMAGES::_toJPEG($imgr, $this->jpeg_quality);
                     }
                 } else {
                     if ($type == 'gif' or $type == 'png') {
                         $info = TCPDF_IMAGES::_toPNG($img);
                     } else {
                         $info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality);
                     }
                 }
             } catch (Exception $e) {
                 $info = false;
             }
         }
         if ($info === false and extension_loaded('imagick')) {
             try {
                 // ImageMagick library
                 $img = new Imagick();
                 if ($type == 'SVG') {
                     // get SVG file content
                     $svgimg = TCPDF_STATIC::fileGetContents($file);
                     if ($svgimg !== FALSE) {
                         // get width and height
                         $regs = array();
                         if (preg_match('/<svg([^\\>]*)>/si', $svgimg, $regs)) {
                             $svgtag = $regs[1];
                             $tmp = array();
                             if (preg_match('/[\\s]+width[\\s]*=[\\s]*"([^"]*)"/si', $svgtag, $tmp)) {
                                 $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
                                 $owu = sprintf('%F', $ow * $dpi / 72) . $this->pdfunit;
                                 $svgtag = preg_replace('/[\\s]+width[\\s]*=[\\s]*"[^"]*"/si', ' width="' . $owu . '"', $svgtag, 1);
                             } else {
                                 $ow = $w;
                             }
                             $tmp = array();
                             if (preg_match('/[\\s]+height[\\s]*=[\\s]*"([^"]*)"/si', $svgtag, $tmp)) {
                                 $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
                                 $ohu = sprintf('%F', $oh * $dpi / 72) . $this->pdfunit;
                                 $svgtag = preg_replace('/[\\s]+height[\\s]*=[\\s]*"[^"]*"/si', ' height="' . $ohu . '"', $svgtag, 1);
                             } else {
                                 $oh = $h;
                             }
                             $tmp = array();
                             if (!preg_match('/[\\s]+viewBox[\\s]*=[\\s]*"[\\s]*([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]+([0-9\\.]+)[\\s]*"/si', $svgtag, $tmp)) {
                                 $vbw = $ow * $this->imgscale * $this->k;
                                 $vbh = $oh * $this->imgscale * $this->k;
                                 $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
                                 $svgtag = $vbox . $svgtag;
                             }
                             $svgimg = preg_replace('/<svg([^\\>]*)>/si', '<svg' . $svgtag . '>', $svgimg, 1);
                         }
                         $img->readImageBlob($svgimg);
                     }
                 } else {
                     $img->readImage($file);
                 }
                 if ($resize) {
                     $img->resizeImage($neww, $newh, 10, 1, false);
                 }
                 $img->setCompressionQuality($this->jpeg_quality);
                 $img->setImageFormat('jpeg');
                 $tempname = TCPDF_STATIC::getObjFilename('jpg');
                 $img->writeImage($tempname);
                 $info = TCPDF_IMAGES::_parsejpeg($tempname);
                 unlink($tempname);
                 $img->destroy();
             } catch (Exception $e) {
                 $info = false;
             }
         }
         if ($info === false) {
             // unable to process image
             return;
         }
         TCPDF_STATIC::set_mqr($mqr);
         if ($ismask) {
             // force grayscale
             $info['cs'] = 'DeviceGray';
         }
         if ($imgmask !== false) {
             $info['masked'] = $imgmask;
         }
         if (!empty($exurl)) {
             $info['exurl'] = $exurl;
         }
         // array of alternative images
         $info['altimgs'] = $altimgs;
         // add image to document
         $info['i'] = $this->setImageBuffer($file, $info);
     }
     // set alignment
     $this->img_rb_y = $y + $h;
     // set alignment
     if ($this->rtl) {
         if ($palign == 'L') {
             $ximg = $this->lMargin;
         } elseif ($palign == 'C') {
             $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
         } elseif ($palign == 'R') {
             $ximg = $this->w - $this->rMargin - $w;
         } else {
             $ximg = $x - $w;
         }
         $this->img_rb_x = $ximg;
     } else {
         if ($palign == 'L') {
             $ximg = $this->lMargin;
         } elseif ($palign == 'C') {
             $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
         } elseif ($palign == 'R') {
             $ximg = $this->w - $this->rMargin - $w;
         } else {
             $ximg = $x;
         }
         $this->img_rb_x = $ximg + $w;
     }
     if ($ismask or $hidden) {
         // image is not displayed
         return $info['i'];
     }
     $xkimg = $ximg * $this->k;
     if (!$alt) {
         // only non-alternative immages will be set
         $this->_out(sprintf('q %F 0 0 %F %F %F cm /I%u Do Q', $w * $this->k, $h * $this->k, $xkimg, ($this->h - ($y + $h)) * $this->k, $info['i']));
     }
     if (!empty($border)) {
         $bx = $this->x;
         $by = $this->y;
         $this->x = $ximg;
         if ($this->rtl) {
             $this->x += $w;
         }
         $this->y = $y;
         $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
         $this->x = $bx;
         $this->y = $by;
     }
     if ($link) {
         $this->Link($ximg, $y, $w, $h, $link, 0);
     }
     // set pointer to align the next text/objects
     switch ($align) {
         case 'T':
             $this->y = $y;
             $this->x = $this->img_rb_x;
             break;
         case 'M':
             $this->y = $y + round($h / 2);
             $this->x = $this->img_rb_x;
             break;
         case 'B':
             $this->y = $this->img_rb_y;
             $this->x = $this->img_rb_x;
             break;
         case 'N':
             $this->SetY($this->img_rb_y);
             break;
         default:
             break;
     }
     $this->endlinex = $this->img_rb_x;
     if ($this->inxobj) {
         // we are inside an XObject template
         $this->xobjects[$this->xobjid]['images'][] = $info['i'];
     }
     return $info['i'];
 }
 public function doUpload($key, $sw = 0, $sh = 0)
 {
     $config = Zend_Registry::get('config');
     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);
             $path_n = APPLICATION_PATH . "/images/thumbnail/" . $uniqid . ".jpg";
             $url_n = $config->app->base_url . "/images/thumbnail/" . $uniqid . ".jpg";
             if ($sw == 0 && $sh == 0) {
                 $sw = $iw;
                 $sh = $ih;
                 $path_n = APPLICATION_PATH . "/images/" . $uniqid . ".jpg";
                 $url_n = $config->app->base_url . "/images/" . $uniqid . ".jpg";
             }
             if ($sw == $iw && $sh == $ih) {
                 $fh = fopen($path_n, '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('jpeg');
                 $fh = fopen($path_n, 'wb');
                 fwrite($fh, $im2->getImagesBlob());
                 fclose($fh);
             } else {
                 $ww = intval($iw * $sh / $ih);
                 $hh = intval($ih * $sw / $iw);
                 if ($sw == 0 && $sh == 0) {
                     $ww = 1;
                     $hh = 1;
                     $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('jpeg');
                 } else {
                     //for thumbnail set compression to 90
                     $image->scaleImage($ww, $sh);
                     $im2 = new Imagick();
                     $im2->setCompression(Imagick::COMPRESSION_JPEG);
                     $im2->setCompressionQuality(90);
                     $im2->newImage($sw, $sh, "none");
                     $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, intval(($sw - $ww) / 2), 0);
                     $im2->setImageFormat('jpeg');
                 }
                 /*
                                     $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('jpeg');
                 */
                 $fh = fopen($path_n, 'wb');
                 fwrite($fh, $im2->getImagesBlob());
                 fclose($fh);
             }
             return $url_n;
         } catch (Exception $e) {
             return null;
         }
     } else {
         return null;
     }
 }