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;
 }
Ejemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function crop(PointInterface $start, BoxInterface $size)
 {
     if (!$start->in($this->getSize())) {
         throw new OutOfBoundsException('Crop coordinates must start at ' . 'minimum 0, 0 position from top left corner, crop height and ' . 'width must be positive integers and must not exceed the ' . 'current image borders');
     }
     try {
         $this->imagick->cropImage($size->getWidth(), $size->getHeight(), $start->getX(), $start->getY());
         // Reset canvas for gif format
         $this->imagick->setImagePage(0, 0, 0, 0);
     } catch (\ImagickException $e) {
         throw new RuntimeException('Crop operation failed', $e->getCode(), $e);
     }
     return $this;
 }
Ejemplo n.º 3
0
 /**
  * Rotate the image.
  * @param int $degrees
  */
 protected function _rotate($degrees)
 {
     if ($this->im->rotateImage(new \ImagickPixel('transparent'), $degrees)) {
         $this->width = $this->im->getImageWidth();
         $this->height = $this->im->getImageHeight();
         $this->im->setImagePage($this->width, $this->height, 0, 0);
     }
 }
Ejemplo n.º 4
0
 /**
  * @param int $width
  * @param int $height
  * @param int $offsetX
  * @param int $offsetY
  *
  * @return static
  */
 public function crop($width, $height, $offsetX = 0, $offsetY = 0)
 {
     $this->_image->cropImage($width, $height, $offsetX, $offsetY);
     $this->_image->setImagePage($width, $height, 0, 0);
     $this->_width = $this->_image->getImageWidth();
     $this->_height = $this->_image->getImageHeight();
     return $this;
 }
Ejemplo n.º 5
0
 /**
  * @param  $x
  * @param  $y
  * @param  $width
  * @param  $height
  * @return Pimcore_Image_Adapter_Imagick
  */
 public function crop($x, $y, $width, $height)
 {
     $this->resource->cropImage($width, $height, $x, $y);
     $this->resource->setImagePage($width, $height, 0, 0);
     $this->setWidth($width);
     $this->setHeight($height);
     $this->reinitializeImage();
     return $this;
 }
Ejemplo n.º 6
0
 /**
  * Crop the current image.
  *
  * @param integer $x1  x for the top left corner
  * @param integer $y1  y for the top left corner
  * @param integer $x2  x for the bottom right corner of the cropped image.
  * @param integer $y2  y for the bottom right corner of the cropped image.
  */
 public function crop($x1, $y1, $x2, $y2)
 {
     try {
         $result = $this->_imagick->cropImage($x2 - $x1, $y2 - $y1, $x1, $y1);
         $this->_imagick->setImagePage(0, 0, 0, 0);
     } catch (ImagickException $e) {
         throw new Horde_Image_Exception($e);
     }
     $this->clearGeometry();
 }
Ejemplo n.º 7
0
 /**
  * @param  $x
  * @param  $y
  * @param  $width
  * @param  $height
  * @return self
  */
 public function crop($x, $y, $width, $height)
 {
     $this->preModify();
     $this->resource->cropImage($width, $height, $x, $y);
     $this->resource->setImagePage($width, $height, 0, 0);
     $this->setWidth($width);
     $this->setHeight($height);
     $this->postModify();
     return $this;
 }
Ejemplo n.º 8
0
 /**
  * @see	\wcf\system\image\adapter\IImageAdapter::clip()
  */
 public function clip($originX, $originY, $width, $height)
 {
     if ($this->imagick->getImageFormat() == 'GIF') {
         $this->imagick = $this->imagick->coalesceImages();
         do {
             $this->imagick->cropImage($width, $height, $originX, $originY);
             $this->imagick->setImagePage($width, $height, 0, 0);
         } while ($this->imagick->nextImage());
     } else {
         $this->imagick->cropImage($width, $height, $originX, $originY);
     }
 }
 /**
  * Rotates current image counter-clockwise by $angle.
  *
  * @since 3.5.0
  * @access public
  *
  * @param float $angle
  * @return true|WP_Error
  */
 public function rotate($angle)
 {
     /**
      * $angle is 360-$angle because Imagick rotates clockwise
      * (GD rotates counter-clockwise)
      */
     try {
         $this->image->rotateImage(new ImagickPixel('none'), 360 - $angle);
         // Since this changes the dimensions of the image, update the size.
         $result = $this->update_size();
         if (is_wp_error($result)) {
             return $result;
         }
         $this->image->setImagePage($this->size['width'], $this->size['height'], 0, 0);
     } catch (Exception $e) {
         return new WP_Error('image_rotate_error', $e->getMessage());
     }
     return true;
 }
Ejemplo n.º 10
0
 /**
  * Generate a derivative image with Imagick.
  */
 public function createImage($sourcePath, $destPath, $type, $sizeConstraint, $mimeType)
 {
     $page = (int) $this->getOption('page', 0);
     try {
         $imagick = new Imagick($sourcePath . '[' . $page . ']');
     } catch (ImagickException $e) {
         _log("Imagick failed to open the file. Details:\n{$e}", Zend_Log::ERR);
         return false;
     }
     $origX = $imagick->getImageWidth();
     $origY = $imagick->getImageHeight();
     $imagick->setImagePage($origX, $origY, 0, 0);
     $imagick->setBackgroundColor('white');
     $imagick->setImageBackgroundColor('white');
     $imagick = $imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
     if ($type != 'square_thumbnail') {
         $imagick->thumbnailImage($sizeConstraint, $sizeConstraint, true);
     } else {
         // We could use cropThumbnailImage here but it lacks support for
         // the gravity setting
         if ($origX < $origY) {
             $newX = $sizeConstraint;
             $newY = $origY * ($sizeConstraint / $origX);
             $offsetX = 0;
             $offsetY = $this->_getCropOffsetY($newY, $sizeConstraint);
         } else {
             $newY = $sizeConstraint;
             $newX = $origX * ($sizeConstraint / $origY);
             $offsetY = 0;
             $offsetX = $this->_getCropOffsetX($newX, $sizeConstraint);
         }
         $imagick->thumbnailImage($newX, $newY);
         $imagick->cropImage($sizeConstraint, $sizeConstraint, $offsetX, $offsetY);
         $imagick->setImagePage($sizeConstraint, $sizeConstraint, 0, 0);
     }
     $imagick->writeImage($destPath);
     $imagick->clear();
     return true;
 }
 /**
  * @param int $size
  *
  * @return $this
  */
 public function createThumbnail($size)
 {
     list($originalX, $originalY) = $this->getGeometry();
     $resizeCropX = 0;
     $resizeCropY = 0;
     if ($originalX > $originalY) {
         $resizeX = $originalY;
         $resizeY = $originalY;
         $resizeCropX = ($originalX - $resizeX) / 2;
     } elseif ($originalY > $originalX) {
         $resizeX = $originalX;
         $resizeY = $originalX;
         $resizeCropY = ($originalY - $resizeY) / 2;
     } else {
         $resizeX = $originalX;
         $resizeY = $originalY;
     }
     $this->im->cropImage($resizeX, $resizeY, $resizeCropX, $resizeCropY);
     $this->im->setImagePage($resizeX, $resizeY, 0, 0);
     $this->scaleImageMax($size, $size);
     return $this;
 }
Ejemplo n.º 12
0
 private function make_thumbnail_Imagick($src_path, $width, $height, $dest)
 {
     $image = new Imagick($src_path);
     # Select the first frame to handle animated images properly
     if (is_callable(array($image, 'setIteratorIndex'))) {
         $image->setIteratorIndex(0);
     }
     // устанавливаем качество
     $format = $image->getImageFormat();
     if ($format == 'JPEG' || $format == 'JPG') {
         $image->setImageCompression(Imagick::COMPRESSION_JPEG);
     }
     $image->setImageCompressionQuality(85);
     $h = $image->getImageHeight();
     $w = $image->getImageWidth();
     // если не указана одна из сторон задаем ей пропорциональное значение
     if (!$width) {
         $width = round($w * ($height / $h));
     }
     if (!$height) {
         $height = round($h * ($width / $w));
     }
     list($dx, $dy, $wsrc, $hsrc) = $this->crop_coordinates($height, $h, $width, $w);
     // обрезаем оригинал
     $image->cropImage($wsrc, $hsrc, $dx, $dy);
     $image->setImagePage($wsrc, $hsrc, 0, 0);
     // Strip out unneeded meta data
     $image->stripImage();
     // уменьшаем под размер
     $image->scaleImage($width, $height);
     $image->writeImage($dest);
     chmod($dest, 0755);
     $image->clear();
     $image->destroy();
     return true;
 }
Ejemplo n.º 13
0
 function waterMarkFont()
 {
     if ($this->param['water_mark_color']) {
         $color = $this->param['water_mark_color'];
     } else {
         $color = '#000000';
     }
     $r = hexdec(substr($color, 1, 2));
     $g = hexdec(substr($color, 3, 2));
     $b = hexdec(substr($color, 5, 2));
     $draw = new ImagickDraw();
     $draw->setFillColor(new ImagickPixel($color));
     //设置填充颜色
     $draw->setFont($this->param['water_mark_font']);
     //设置文本字体,要求ttf或者ttc字体,可以绝对或者相对路径
     $draw->setFontSize($this->param['water_mark_fontsize']);
     //设置字号
     switch ($this->param['water_mark_pos']) {
         case 0:
         case 1:
             $gravity = Imagick::GRAVITY_NORTHWEST;
             //'NorthWest';
             break;
         case 2:
             $gravity = Imagick::GRAVITY_NORTH;
             //'North';
             break;
         case 3:
             $gravity = Imagick::GRAVITY_NORTHEAST;
             //'NorthEast';
             break;
         case 4:
             $gravity = Imagick::GRAVITY_WEST;
             //'West';
             break;
         case 5:
             $gravity = Imagick::GRAVITY_CENTER;
             //'Center';
             break;
         case 6:
             $gravity = Imagick::GRAVITY_EAST;
             //'East';
             break;
         case 7:
             $gravity = Imagick::GRAVITY_SOUTHWEST;
             //'SouthWest';
             break;
         case 8:
             $gravity = Imagick::GRAVITY_SOUTH;
             //'South';
             break;
         case 9:
             $gravity = Imagick::GRAVITY_SOUTHEAST;
             break;
     }
     $draw->setGravity($gravity);
     if ($this->image_type == 'GIF') {
         $color_transparent = new ImagickPixel("transparent");
         $dest = new Imagick();
         foreach ($this->image as $frame) {
             $page = $frame->getImagePage();
             $tmp = new Imagick();
             $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif');
             $tmp->compositeImage($frame, Imagick::COMPOSITE_OVER, $page['x'], $page['y']);
             $tmp->annotateImage($draw, 0, 0, $this->param['water_mark_angle'], $this->param['water_mark_string']);
             $dest->addImage($tmp);
             $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0);
             $dest->setImageDelay($frame->getImageDelay());
             $dest->setImageDispose($frame->getImageDispose());
         }
         $dest->coalesceImages();
         $this->image->destroy();
         $this->image = $dest;
     } else {
         if ($this->param['water_mark_opacity']) {
             $draw->setFillOpacity($this->param['water_mark_opacity'] / 100);
         }
         $this->image->annotateImage($draw, 0, 0, $this->param['water_mark_angle'], $this->param['water_mark_string']);
     }
 }
Ejemplo n.º 14
0
}
//calculate the position from the source image if we need to crop and where
//we need to put into the target image.
$dst_x = $src_x = $dst_y = $src_y = 0;
if ($_POST["imageX"] > 0) {
    $dst_x = abs($_POST["imageX"]);
} else {
    $src_x = abs($_POST["imageX"]);
}
if ($_POST["imageY"] > 0) {
    $dst_y = abs($_POST["imageY"]);
} else {
    $src_y = abs($_POST["imageY"]);
}
//This fix the page of the image so it crops fine!
$img->setimagepage(0, 0, 0, 0);
//crop the image with the viewed into the viewport
$img->cropImage($viewPortW, $viewPortH, $src_x, $src_y);
//create the viewport to put the cropped image
$viewport = new Imagick();
$viewport->newImage($viewPortW, $viewPortH, '#' . $colorHEX);
$viewport->setImageFormat($ext);
$viewport->setImageColorspace($img->getImageColorspace());
$viewport->compositeImage($img, $img->getImageCompose(), $dst_x, $dst_y);
//crop the selection from the viewport
$viewport->setImagePage(0, 0, 0, 0);
$viewport->cropImage($_POST["selectorW"], $_POST["selectorH"], $selectorX, $selectorY);
$targetFile = 'tmp/test_' . time() . "." . $ext;
//save the image into the disk
$viewport->writeImage($targetFile);
echo $targetFile;
Ejemplo n.º 15
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);
                     /*
                      * Remove the canvas
                      * See: http://php.net/manual/en/imagick.cropthumbnailimage.php#106710
                      */
                     $image->setImagePage(0, 0, 0, 0);
                     $imageRead = true;
                 }
             } else {
                 $image->setSize($width, $height);
                 if ($image->readImage($originalPath) === true) {
                     $image->thumbnailImage($finalWidth, $finalHeight);
                     $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;
 }
Ejemplo n.º 16
0
};
$frames = array_map($getFilename, range($startFrame, $endFrame, $frameSkip));
echo "There are " . count($frames) . " frames \n";
$frameDelay = $frameSkip * 100 / $frameRate;
$animation = new Imagick();
foreach ($frames as $frame) {
    echo "Adding file {$frame}\n";
    $imagickFrame = new Imagick($frame);
    //$frame->readImage($frame);
    //reduceNoiseImage
    $imagickFrame->despeckleImage();
    //$imagickFrame->reduceNoiseImage(0);
    $imagickFrame->resizeImage(0, $height, \Imagick::FILTER_LANCZOS, 2, false);
    $geo = $imagickFrame->getImageGeometry();
    $imagickFrame->cropImage($width, $height, ($geo['width'] - $width) / 2, 0);
    $imagickFrame->setImagePage($imagickFrame->getimageWidth(), $imagickFrame->getimageheight(), 0, 0);
    //$imagickFrame->gaussianBlurImage(1, 0.5);
    //$imagickFrame->orderedPosterizeImage("o8x8");
    //"o8x8,8"
    //"o8x8,10"
    //    $identifyInfo = $imagickFrame->identifyimage();
    //    var_dump($identifyInfo);
    $imagickFrame->writeImage($frame . "debug.gif");
    //if (false) {
    $paletteImage = clone $imagickFrame;
    $paletteImage->quantizeImage(256, Imagick::COLORSPACE_YIQ, 0, false, false);
    //$imagickFrame->setImageDepth(8);
    //$imagickFrame->quantizeImage(15,Imagick::COLORSPACE_TRANSPARENT,0,false,false);
    //Imagick::mapImage ( Imagick $map , bool $dither )
    $imagickFrame->remapImage($paletteImage, Imagick::DITHERMETHOD_FLOYDSTEINBERG);
    //}
Ejemplo n.º 17
0
/**
 * Resize using PHP imagick extension
 *
 * Writes resized version of an already uploaded image
 *
 *
 * @param string $input_name The name of the file input field on the submission form
 * @param string $output_name The name of the file to be written
 * @param int $maxwidth The maximum width of the resized image
 * @param int $maxheight The maximum height of the resized image
 * @param TRUE|FALSE $square If set to TRUE, will take the smallest of maxwidth and maxheight and use it to set the dimensions on all size; the image will be cropped.
 * @return bool TRUE on success
 */
function tp_imagick_resize($input_name, $output_name, $maxwidth, $maxheight, $square = FALSE, $x1 = 0, $y1 = 0, $x2 = 0, $y2 = 0)
{
    // Get the size information from the image
    $imgsizearray = getimagesize($input_name);
    if (!$imgsizearray) {
        return FALSE;
    }
    // Get width and height
    $width = $imgsizearray[0];
    $height = $imgsizearray[1];
    $params = tp_im_calc_resize_params($width, $height, $maxwidth, $maxheight, $square, $x1, $y1, $x2, $y2);
    if (!$params) {
        return FALSE;
    }
    $new_width = $params['new_width'];
    $new_height = $params['new_height'];
    $region_width = $params['region_width'];
    $region_height = $params['region_height'];
    $widthoffset = $params['width_offset'];
    $heightoffset = $params['height_offset'];
    try {
        $img = new Imagick($input_name);
    } catch (ImagickException $e) {
        return FALSE;
    }
    $img->cropImage($region_width, $region_height, $widthoffset, $heightoffset);
    // use the default IM filter (windowing filter), I think 1 means default blurring or number of lobes
    $img->resizeImage($new_width, $new_height, imagick::FILTER_LANCZOS, 1);
    $img->setImagePage($new_width, $new_height, 0, 0);
    if ($img->writeImage($output_name) != TRUE) {
        $img->destroy();
        return FALSE;
    }
    $img->destroy();
    return TRUE;
}
Ejemplo n.º 18
0
 public function getMediaThumbnail(Request $request, Response $response, $arguments)
 {
     try {
         $imagick = new \Imagick();
         $imagick->setResolution(144, 144);
         $imagick->setBackgroundColor('#ffffff');
         $imagick->readImage('uploads/' . $arguments['filename'] . '[0]');
         $imagick->scaleImage(640, 0);
         $imagick->cropImage(640, 480, 0, 0);
         $imagick->setImagePage(0, 0, 0, 0);
         $imagick = $imagick->flattenImages();
         $imagick->setImageFormat('jpeg');
         $imageData = $imagick->getImageBlob();
         return $response->withHeader('Content-Type', 'image/jpeg')->write($imageData);
     } catch (\Exception $e) {
         return $response->withStatus(404);
     }
 }
Ejemplo n.º 19
0
 /**
  * 截取图片
  *
  * @param int $x 开始坐标x
  * @param int $y 坐标y
  * @param int $width
  * @param int $height
  * @param string $savepath 文件存放路径,未提供则修改当前
  */
 public function watchmark($x, $y, $savepath = NULL)
 {
     if (!$this->waterImage instanceof \Imagick) {
         throw new MediaException('Watermark source is invalid.');
     }
     if ($format == 'GIF') {
         $format = $this->getImageFormat();
         $transparent = new \ImagickPixel("rgba(0, 0, 0, 0)");
         // 透明色
         $tmpImage = new \Imagick();
         foreach ($this->image as $frame) {
             $page = $frame->getImagePage();
             $tmp = new \Imagick();
             $tmp->newImage($page['width'], $page['height'], $transparent, $format);
             $tmp->compositeImage($frame, \Imagick::COMPOSITE_DEFAULT, $page['x'], $page['y']);
             if (min($this->getOriginalSize()) > $this->waterStart) {
                 $tmp->compositeImage($this->waterImage, \Imagick::COMPOSITE_DEFAULT, $x, $y);
             }
             $tmpImage->addImage($tmp);
             $tmpImage->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0);
             $tmpImage->setImageDelay($frame->getImageDelay());
             $tmpImage->setImageDispose($frame->getImageDispose());
         }
     } else {
         $tmpImage = new \Imagick();
         $tmpImage->addimage($this->image);
         if (min($this->getOriginalSize()) > $this->waterStart) {
             $tmpImage->compositeImage($this->waterImage, \Imagick::COMPOSITE_DEFAULT, $x, $y);
         }
     }
     if ($savepath == NULL) {
         //缩放当前
         $this->image = $tmpImage;
     } else {
         //写入储存
         $this->writeToPath($savepath, $tmpImage);
     }
     return $this;
 }
Ejemplo n.º 20
0
function ImagickResizeImage($srcFile, $destFile, $new_w, $new_h, $zhenshu = false)
{
    if ($new_w <= 0 || $new_h <= 0 || !file_exists($srcFile)) {
        return false;
    }
    $src = new Imagick($srcFile);
    $image_format = strtolower($src->getImageFormat());
    if ($image_format != 'jpeg' && $image_format != 'gif' && $image_format != 'png' && $image_format != 'jpg' && $image_format != 'bmp') {
        return false;
    }
    //如果是 jpg jpeg
    if ($image_format != 'gif') {
        $dest = $src;
        $dest->thumbnailImage($new_w, $new_h, true);
        $dest->writeImage($destFile);
        $dest->clear();
        //gif需要以帧一帧的处理
    } else {
        $dest = new Imagick();
        $color_transparent = new ImagickPixel("transparent");
        //透明色
        $gif_i = 1;
        foreach ($src as $img) {
            $page = $img->getImagePage();
            $tmp = new Imagick();
            $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif');
            $tmp->compositeImage($img, Imagick::COMPOSITE_OVER, $page['x'], $page['y']);
            $tmp->thumbnailImage($new_w, $new_h, true);
            $dest->addImage($tmp);
            $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0);
            $dest->setImageDelay($img->getImageDelay());
            $dest->setImageDispose($img->getImageDispose());
            if ($zhenshu > 0) {
                if ($zhenshu <= $gif_i) {
                    break;
                }
                $gif_i++;
            }
        }
        $dest->coalesceImages();
        $dest->writeImages($destFile, true);
        $dest->clear();
    }
}
 private function _imageickThumb($url, $type, $new_w = 765, $new_h = 1000, $self = false, $trim = false)
 {
     $srcFile = $url;
     if ($self) {
         $destFile = $url;
     } else {
         $destFile = $type;
     }
     if ($new_w <= 0 || !file_exists($srcFile)) {
         return false;
     }
     $src = new Imagick($srcFile);
     $image_format = strtolower($src->getImageFormat());
     if ($image_format != 'jpeg' && $image_format != 'gif' && $image_forumat != 'bmp' && $image_format != 'png' && $image_format != 'jpg') {
         return false;
     }
     $src_page = $src->getImagePage();
     $src_w = $src_page['width'];
     $rate_w = $new_w / $src_w;
     if ($rate_w >= 1) {
         return false;
     }
     if ($new_h == -1) {
         $new_h = $rate_w * $src_page['height'];
     }
     //如果是 jpg jpeg gif
     if ($image_format != 'gif') {
         $dest = $src;
         if (!$trim) {
             $dest->thumbnailImage($new_w, $new_h, true);
         } else {
             $dest->cropthumbnailImage($new_w, $new_h);
         }
         $dest->writeImage($destFile);
         $dest->clear();
         //gif需要以帧一帧的处理
     } else {
         $dest = new Imagick();
         $color_transparent = new ImagickPixel("transparent");
         //透明色
         foreach ($src as $img) {
             $page = $img->getImagePage();
             if ($new_h == -1) {
                 $new_h = $new_w / $page['width'] * $src_page['hight'];
             }
             $tmp = new Imagick();
             $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif');
             $tmp->compositeImage($img, Imagick::COMPOSITE_OVER, $page['x'], $page['y']);
             if (!$trim) {
                 $tmp->thumbnailImage($new_w, $new_h, true);
             } else {
                 $tmp->cropthumbnailImage($new_w, $new_h);
             }
             $dest->addImage($tmp);
             $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0);
             $dest->setImageDelay($img->getImageDelay());
             $dest->setImageDispose($img->getImageDispose());
         }
         $dest->coalesceImages();
         $dest->writeImages($destFile, true);
         $dest->clear();
     }
 }
Ejemplo n.º 22
0
/**
 * Decode a single OMR Page and return data array.
 * This function requires ImageMagick library and zbarimg (http://zbar.sourceforge.net/).
 * @param $image (string) image file to be decoded (scanned OMR page at 200 DPI with full color range).
 * @return array of answers data or false in case of error.
 */
function F_decodeOMRPage($image)
{
    require_once '../config/tce_config.php';
    // decode barcode containing first question number
    $command = K_OMR_PATH_ZBARIMG . ' --raw -Sdisable -Scode128.enable -q ' . escapeshellarg($image);
    $qstart = exec($command);
    $qstart = intval($qstart);
    if ($qstart == 0) {
        return false;
    }
    $img = new Imagick();
    $img->readImage($image);
    $imginfo = $img->identifyImage();
    if ($imginfo['type'] == 'TrueColor') {
        // remove red color
        $img->separateImageChannel(Imagick::CHANNEL_RED);
    } else {
        // desaturate image
        $img->modulateImage(100, 0, 100);
    }
    // get image width and height
    $w = $imginfo['geometry']['width'];
    $h = $imginfo['geometry']['height'];
    if ($h > $w) {
        // crop header and footer
        $y = round(($h - $w) / 2);
        $img->cropImage($w, $w, 0, $y);
        $img->setImagePage(0, 0, 0, 0);
    }
    // trim image
    $imgtmp = $img->clone();
    $color = '#808080';
    $img->blackthresholdImage("{$color}");
    $img->whitethresholdImage("{$color}");
    $img->trimImage(85);
    $imgpage = $img->getImagePage();
    $w = $img->getImageWidth();
    $h = $img->getImageHeight();
    $img = $imgtmp->clone();
    $imgtmp->clear();
    $img->cropImage($w, $h, $imgpage['x'], $imgpage['y']);
    $img->setImagePage(0, 0, 0, 0);
    // increase contrast
    $img->normalizeImage(Imagick::CHANNEL_ALL);
    $img->enhanceImage();
    $img->despeckleImage();
    // straighten image
    $img->deskewImage(40);
    $img->setImagePage(0, 0, 0, 0);
    // trim image (remove white border)
    $imgtmp = $img->clone();
    $color = '#808080';
    $img->blackthresholdImage("{$color}");
    $img->whitethresholdImage("{$color}");
    $img->trimImage(85);
    $imgpage = $img->getImagePage();
    $w = $img->getImageWidth();
    $h = $img->getImageHeight();
    $img = $imgtmp->clone();
    $imgtmp->clear();
    $img->cropImage($w, $h, $imgpage['x'], $imgpage['y']);
    $img->setImagePage(0, 0, 0, 0);
    // resize image
    $img->resizeImage(1028, 1052, Imagick::FILTER_CUBIC, 1);
    $img->setImagePage(0, 0, 0, 0);
    // binarize image
    $color = '#c0c0c0';
    $img->blackthresholdImage("{$color}");
    $img->whitethresholdImage("{$color}");
    // scan block width
    $blkw = 16;
    // starting column in pixels
    $scol = 106;
    // starting row in pixels
    $srow = 49;
    // column distance in pixels between two answers
    $dcol = 75.364;
    // column distance in pixels between True/false circles
    $dtf = 25;
    // row distance in pixels between two questions
    $drow = 32.38;
    // verify image pattern
    $imgtmp = $img->clone();
    $imgtmp->cropImage(1028, 10, 0, 10);
    $imgtmp->setImagePage(0, 0, 0, 0);
    // create reference block pattern
    $impref = new Imagick();
    $impref->newImage(3, 10, new ImagickPixel('black'));
    $psum = 0;
    for ($c = 0; $c < 12; ++$c) {
        $x = round(112 + $c * $dcol);
        // get square region inside the current grid position
        $imreg = $img->getImageRegion(3, 10, $x, 0);
        $imreg->setImagePage(0, 0, 0, 0);
        // get root-mean-square-error with reference image
        $rmse = $imreg->compareImages($impref, Imagick::METRIC_ROOTMEANSQUAREDERROR);
        // cont reference blocks
        $psum += round(1.25 - $rmse[1]) . "\n";
    }
    $imreg->clear();
    $impref->clear();
    if ($psum != 12) {
        return false;
    }
    // create reference block
    $imref = new Imagick();
    $imref->newImage($blkw, $blkw, new ImagickPixel('black'));
    // array to be returned
    $omrdata = array();
    // for each row (question)
    for ($r = 0; $r < 30; ++$r) {
        $omrdata[$r + $qstart] = array();
        $y = round($srow + $r * $drow);
        // for each column (answer)
        for ($c = 0; $c < 12; ++$c) {
            // read true option
            $x = round($scol + $c * $dcol);
            // get square region inside the current grid position
            $imreg = $img->getImageRegion($blkw, $blkw, $x, $y);
            $imreg->setImagePage(0, 0, 0, 0);
            // get root-mean-square-error with reference image
            $rmse = $imreg->compareImages($imref, Imagick::METRIC_ROOTMEANSQUAREDERROR);
            // true option
            $opt_true = 2 * round(1.25 - $rmse[1]);
            // read false option
            $x += $dtf;
            // get square region inside the current grid position
            $imreg = $img->getImageRegion($blkw, $blkw, $x, $y);
            $imreg->setImagePage(0, 0, 0, 0);
            // get root-mean-square-error with reference image
            $rmse = $imreg->compareImages($imref, Imagick::METRIC_ROOTMEANSQUAREDERROR);
            // false option
            $opt_false = round(1.25 - $rmse[1]);
            // set array to be returned (-1 = unset, 0 = false, 1 = true)
            $val = $opt_true + $opt_false - 1;
            if ($val > 1) {
                $val = 1;
            }
            $omrdata[$r + $qstart][$c + 1] = $val;
        }
    }
    $imreg->clear();
    $imref->clear();
    return $omrdata;
}
Ejemplo n.º 23
0
 public function resize_to($width = 100, $height = 100, $fit = 'center', $fill_color = array(255, 255, 255, 0))
 {
     switch ($fit) {
         case 'force':
             if ($this->type == 'gif') {
                 $image = $this->image;
                 $canvas = new Imagick();
                 $images = $image->coalesceImages();
                 foreach ($images as $frame) {
                     $img = new Imagick();
                     $img->readImageBlob($frame);
                     $img->thumbnailImage($width, $height, false);
                     $canvas->addImage($img);
                     $canvas->setImageDelay($img->getImageDelay());
                 }
                 $image->destroy();
                 $this->image = $canvas;
             } else {
                 $this->image->thumbnailImage($width, $height, false);
             }
             break;
         case 'scale':
             if ($this->type == 'gif') {
                 $image = $this->image;
                 $images = $image->coalesceImages();
                 $canvas = new Imagick();
                 foreach ($images as $frame) {
                     $img = new Imagick();
                     $img->readImageBlob($frame);
                     $img->thumbnailImage($width, $height, true);
                     $canvas->addImage($img);
                     $canvas->setImageDelay($img->getImageDelay());
                 }
                 $image->destroy();
                 $this->image = $canvas;
             } else {
                 $this->image->thumbnailImage($width, $height, true);
             }
             break;
         case 'scale_fill':
             $size = $this->image->getImagePage();
             $src_width = $size['width'];
             $src_height = $size['height'];
             $x = 0;
             $y = 0;
             $dst_width = $width;
             $dst_height = $height;
             if ($src_width * $height > $src_height * $width) {
                 $dst_height = intval($width * $src_height / $src_width);
                 $y = intval(($height - $dst_height) / 2);
             } else {
                 $dst_width = intval($height * $src_width / $src_height);
                 $x = intval(($width - $dst_width) / 2);
             }
             $image = $this->image;
             $canvas = new Imagick();
             $color = 'rgba(' . $fill_color[0] . ',' . $fill_color[1] . ',' . $fill_color[2] . ',' . $fill_color[3] . ')';
             if ($this->type == 'gif') {
                 $images = $image->coalesceImages();
                 foreach ($images as $frame) {
                     $frame->thumbnailImage($width, $height, true);
                     $draw = new ImagickDraw();
                     $draw->composite($frame->getImageCompose(), $x, $y, $dst_width, $dst_height, $frame);
                     $img = new Imagick();
                     $img->newImage($width, $height, $color, 'gif');
                     $img->drawImage($draw);
                     $canvas->addImage($img);
                     $canvas->setImageDelay($img->getImageDelay());
                     $canvas->setImagePage($width, $height, 0, 0);
                 }
             } else {
                 $image->thumbnailImage($width, $height, true);
                 $draw = new ImagickDraw();
                 $draw->composite($image->getImageCompose(), $x, $y, $dst_width, $dst_height, $image);
                 $canvas->newImage($width, $height, $color, $this->get_type());
                 $canvas->drawImage($draw);
                 $canvas->setImagePage($width, $height, 0, 0);
             }
             $image->destroy();
             $this->image = $canvas;
             break;
         default:
             $size = $this->image->getImagePage();
             $src_width = $size['width'];
             $src_height = $size['height'];
             $crop_x = 0;
             $crop_y = 0;
             $crop_w = $src_width;
             $crop_h = $src_height;
             if ($src_width * $height > $src_height * $width) {
                 $crop_w = intval($src_height * $width / $height);
             } else {
                 $crop_h = intval($src_width * $height / $width);
             }
             switch ($fit) {
                 case 'north_west':
                     $crop_x = 0;
                     $crop_y = 0;
                     break;
                 case 'north':
                     $crop_x = intval(($src_width - $crop_w) / 2);
                     $crop_y = 0;
                     break;
                 case 'north_east':
                     $crop_x = $src_width - $crop_w;
                     $crop_y = 0;
                     break;
                 case 'west':
                     $crop_x = 0;
                     $crop_y = intval(($src_height - $crop_h) / 2);
                     break;
                 case 'center':
                     $crop_x = intval(($src_width - $crop_w) / 2);
                     $crop_y = intval(($src_height - $crop_h) / 2);
                     break;
                 case 'east':
                     $crop_x = $src_width - $crop_w;
                     $crop_y = intval(($src_height - $crop_h) / 2);
                     break;
                 case 'south_west':
                     $crop_x = 0;
                     $crop_y = $src_height - $crop_h;
                     break;
                 case 'south':
                     $crop_x = intval(($src_width - $crop_w) / 2);
                     $crop_y = $src_height - $crop_h;
                     break;
                 case 'south_east':
                     $crop_x = $src_width - $crop_w;
                     $crop_y = $src_height - $crop_h;
                     break;
                 default:
                     $crop_x = intval(($src_width - $crop_w) / 2);
                     $crop_y = intval(($src_height - $crop_h) / 2);
             }
             $image = $this->image;
             $canvas = new Imagick();
             if ($this->type == 'gif') {
                 $images = $image->coalesceImages();
                 foreach ($images as $frame) {
                     $img = new Imagick();
                     $img->readImageBlob($frame);
                     $img->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
                     $img->thumbnailImage($width, $height, true);
                     $canvas->addImage($img);
                     $canvas->setImageDelay($img->getImageDelay());
                     $canvas->setImagePage($width, $height, 0, 0);
                 }
             } else {
                 $image->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
                 $image->thumbnailImage($width, $height, true);
                 $canvas->addImage($image);
                 $canvas->setImagePage($width, $height, 0, 0);
             }
             $image->destroy();
             $this->image = $canvas;
     }
 }
Ejemplo n.º 24
0
 private static function _imagick()
 {
     //if (!extension_loaded('imagick')) {
     if (!class_exists('Imagick')) {
         if (!extension_loaded('gd')) {
             return array('status' => self::RESULT_FAILED, 'message' => "Extension 'imagick' is not loaded. Fallback extension 'gd' is also not loaded.");
         }
         return array('status' => self::RESULT_WARNING, 'message' => "Extension 'imagick' is not loaded. 'gd' is used as fallback.");
     }
     $im = new Imagick();
     $im->readImage(dirname(__FILE__) . '/Config/testImage.jpg');
     $im->scaleImage(10, 10);
     $im->setImagePage(0, 0, 0, 0);
     $im->setImageColorspace(Imagick::COLORSPACE_RGB);
     $im->getImageBlob();
     $im->destroy();
     $im = new Imagick();
     $im->readImage(dirname(__FILE__) . '/Config/testImage.png');
     $im->scaleImage(10, 10);
     $im->setImagePage(0, 0, 0, 0);
     $im->setImageColorspace(Imagick::COLORSPACE_RGB);
     $im->getImageBlob();
     $im->destroy();
     return array('status' => self::RESULT_OK);
 }
Ejemplo n.º 25
0
 /**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     $media = $this->media;
     \Log::info('ATTEMPT Process Image ' . $media->id . ': ' . microtime());
     if ($media) {
         \Log::info('START Process Image ' . $media->id . ': ' . microtime());
         if (class_exists("Imagick")) {
             $sizes = \Config::get('media.sizes');
             $createdSizes = ['o'];
             $img = new \Imagick($media->filePath('o'));
             $imgProps = $img->getImageGeometry();
             $dimensions = ['o' => ['width' => $imgProps['width'], 'height' => $imgProps['height']]];
             foreach ($sizes as $size => $settings) {
                 \Log::info('START Size ' . $size . ': ' . microtime());
                 $img = new \Imagick($media->filePath('o'));
                 $imgProps = $img->getImageGeometry();
                 if ($imgProps['width'] >= $settings['length'] || $imgProps['height'] >= $settings['length']) {
                     $imgRatio = $imgProps['width'] / $imgProps['height'];
                     if ($settings['aspectRatio'] != 'source') {
                         list($aspectWidth, $aspectHeight) = explode(':', $settings['aspectRatio']);
                         $cropRatio = $aspectWidth / $aspectHeight;
                         if ($cropRatio == 1) {
                             $newWidth = $newHeight = $settings['length'];
                         } else {
                             if ($cropRatio > 1) {
                                 $newWidth = $settings['length'];
                                 $newHeight = $settings['length'] / $cropRatio;
                             } else {
                                 $newWidth = $settings['length'] / $cropRatio;
                                 $newHeight = $settings['length'];
                             }
                         }
                         if ($imgRatio >= $cropRatio) {
                             $img->resizeImage(999999, $newHeight, \Imagick::FILTER_BOX, 1, TRUE);
                         } else {
                             $img->resizeImage($newWidth, 999999, \Imagick::FILTER_BOX, 1, TRUE);
                         }
                         $imgProps = $img->getImageGeometry();
                         $newX = ($imgProps['width'] - $newWidth) / 2;
                         $newY = ($imgProps['height'] - $newHeight) / 2;
                         $img->cropImage($newWidth, $newHeight, $newX, $newY);
                         $img->setImagePage(0, 0, 0, 0);
                         // Fixes a bug(?) where cropping leaves behind blank canvas
                     } else {
                         $img->resizeImage($settings['length'], $settings['length'], \Imagick::FILTER_BOX, 1, TRUE);
                     }
                     if ($img->writeImage($media->filePath($size))) {
                         $createdSizes[] = $size;
                         $dimensions[$size] = ['width' => $imgProps['width'], 'height' => $imgProps['height']];
                         \Log::info('Saved Size ' . $size . ': ' . microtime());
                     } else {
                         \Log::info('Error Saving Size ' . $size . ': ' . microtime());
                     }
                     \Log::info('END Size ' . $size . ': ' . microtime());
                 }
             }
             $media->dimensions = $dimensions;
             $media->processed = 1;
             $media->save();
         }
         \Log::info('END Process Image ' . $media->id . ': ' . microtime());
     }
 }
Ejemplo n.º 26
0
 public function thumb($width, $height, $type = THINKIMAGE_THUMB_SCALE)
 {
     if (empty($this->img)) {
         throw new Exception("没有可以被缩略的图像资源");
     }
     $w = $this->info["width"];
     $h = $this->info["height"];
     switch ($type) {
         case THINKIMAGE_THUMB_SCALE:
             if ($w < $width && $h < $height) {
                 return NULL;
             }
             $scale = min($width / $w, $height / $h);
             $x = $y = 0;
             $width = $w * $scale;
             $height = $h * $scale;
             break;
         case THINKIMAGE_THUMB_CENTER:
             $scale = max($width / $w, $height / $h);
             $w = $width / $scale;
             $h = $height / $scale;
             $x = ($this->info["width"] - $w) / 2;
             $y = ($this->info["height"] - $h) / 2;
             break;
         case THINKIMAGE_THUMB_NORTHWEST:
             $scale = max($width / $w, $height / $h);
             $x = $y = 0;
             $w = $width / $scale;
             $h = $height / $scale;
             break;
         case THINKIMAGE_THUMB_SOUTHEAST:
             $scale = max($width / $w, $height / $h);
             $w = $width / $scale;
             $h = $height / $scale;
             $x = $this->info["width"] - $w;
             $y = $this->info["height"] - $h;
             break;
         case THINKIMAGE_THUMB_FILLED:
             if ($w < $width && $h < $height) {
                 $scale = 1;
             } else {
                 $scale = min($width / $w, $height / $h);
             }
             $neww = $w * $scale;
             $newh = $h * $scale;
             $posx = ($width - $w * $scale) / 2;
             $posy = ($height - $h * $scale) / 2;
             $newimg = new Imagick();
             $newimg->newImage($width, $height, "white", $this->info["type"]);
             if ("gif" == $this->info["type"]) {
                 $imgs = $this->img->coalesceImages();
                 $img = new Imagick();
                 $this->img->destroy();
                 do {
                     $image = $this->_fill($newimg, $posx, $posy, $neww, $newh, $imgs);
                     $img->addImage($image);
                     $img->setImageDelay($imgs->getImageDelay());
                     $img->setImagePage($width, $height, 0, 0);
                     $image->destroy();
                 } while ($imgs->nextImage());
                 $this->img->destroy();
                 $this->img = $img->deconstructImages();
                 $imgs->destroy();
                 $img->destroy();
             } else {
                 $img = $this->_fill($newimg, $posx, $posy, $neww, $newh);
                 $this->img->destroy();
                 $this->img = $img;
             }
             $this->info["width"] = $width;
             $this->info["height"] = $height;
             return NULL;
         case THINKIMAGE_THUMB_FIXED:
             $x = $y = 0;
             break;
         default:
             throw new Exception("不支持的缩略图裁剪类型");
     }
     $this->crop($w, $h, $x, $y, $width, $height);
 }
Ejemplo n.º 27
0
 public function preciseCrop($destPath, $coords)
 {
     $image = new \Imagick($this->path);
     $image->setImagePage(0, 0, 0, 0);
     // Reset virtual canvas, like +repage
     $image->cropImage($coords['width'], $coords['height'], $coords['x'], $coords['y']);
     $image->setImagePage(0, 0, 0, 0);
     // Reset virtual canvas, like +repage
     // Imagick will copy metadata to the destination file
     $image->writeImage($destPath);
     $image->destroy();
 }
Ejemplo n.º 28
0
$save_image_link = 'imagick-resize-900x600-from-jpg.png';
// png compression for imagick does not work!!!
$save_result = $Imagick->writeImage($processed_images_fullpath . $save_image_link);
var_dump($save_result);
echo '<a href="' . $processed_images_folder . $save_image_link . '">resized image</a>' . "\n";
$image_data = getimagesize($processed_images_fullpath . $save_image_link);
echo '<pre>' . print_r($image_data, true) . '</pre>';
echo '<hr>' . "\n\n";
// resize 8 (save to .gif)
$save_image_link = 'imagick-resize-900x600-from-jpg.gif';
$save_result = $Imagick->writeImage($processed_images_fullpath . $save_image_link);
$Imagick->clear();
var_dump($save_result);
echo '<a href="' . $processed_images_folder . $save_image_link . '">resized image</a>' . "\n";
$image_data = getimagesize($processed_images_fullpath . $save_image_link);
echo '<pre>' . print_r($image_data, true) . '</pre>';
echo '<hr>' . "\n\n";
// resize 9 (crop and save to .gif)
$Imagick = new \Imagick(realpath($source_image_jpg));
$Imagick->cropImage($crop_width, $crop_height, 0, 0);
$save_image_link = 'imagick-crop-460x460-from-jpg.gif';
$Imagick->setImagePage(0, 0, 0, 0);
// required to save as gif even from other format.
$save_result = $Imagick->writeImage($processed_images_fullpath . $save_image_link);
$Imagick->clear();
var_dump($save_result);
echo '<a href="' . $processed_images_folder . $save_image_link . '">cropped image</a>' . "\n";
$image_data = getimagesize($processed_images_fullpath . $save_image_link);
echo '<pre>' . print_r($image_data, true) . '</pre>';
echo '<hr>' . "\n\n";
include __DIR__ . DIRECTORY_SEPARATOR . 'include-memory-usage.php';
Ejemplo n.º 29
0
 /**
  * 生成缩略图
  * @param  integer $width  缩略图最大宽度
  * @param  integer $height 缩略图最大高度
  * @param  integer $type   缩略图裁剪类型
  */
 public function thumb($width, $height, $type = Image::IMAGE_THUMB_SCALE)
 {
     if (empty($this->img)) {
         throw new Exception('没有可以被缩略的图像资源');
     }
     //原图宽度和高度
     $w = $this->info['width'];
     $h = $this->info['height'];
     /* 计算缩略图生成的必要参数 */
     switch ($type) {
         /* 等比例缩放 */
         case Image::IMAGE_THUMB_SCALING:
             //原图尺寸小于缩略图尺寸则不进行缩略
             if ($w < $width && $h < $height) {
                 return;
             }
             //计算缩放比例
             $scale = min($width / $w, $height / $h);
             //设置缩略图的坐标及宽度和高度
             $x = $y = 0;
             $width = $w * $scale;
             $height = $h * $scale;
             break;
             /* 居中裁剪 */
         /* 居中裁剪 */
         case Image::IMAGE_THUMB_CENTER:
             //计算缩放比例
             $scale = max($width / $w, $height / $h);
             //设置缩略图的坐标及宽度和高度
             $w = $width / $scale;
             $h = $height / $scale;
             $x = ($this->info['width'] - $w) / 2;
             $y = ($this->info['height'] - $h) / 2;
             break;
             /* 左上角裁剪 */
         /* 左上角裁剪 */
         case Image::IMAGE_THUMB_NORTHWEST:
             //计算缩放比例
             $scale = max($width / $w, $height / $h);
             //设置缩略图的坐标及宽度和高度
             $x = $y = 0;
             $w = $width / $scale;
             $h = $height / $scale;
             break;
             /* 右下角裁剪 */
         /* 右下角裁剪 */
         case Image::IMAGE_THUMB_SOUTHEAST:
             //计算缩放比例
             $scale = max($width / $w, $height / $h);
             //设置缩略图的坐标及宽度和高度
             $w = $width / $scale;
             $h = $height / $scale;
             $x = $this->info['width'] - $w;
             $y = $this->info['height'] - $h;
             break;
             /* 填充 */
         /* 填充 */
         case Image::IMAGE_THUMB_FILLED:
             //计算缩放比例
             if ($w < $width && $h < $height) {
                 $scale = 1;
             } else {
                 $scale = min($width / $w, $height / $h);
             }
             //设置缩略图的坐标及宽度和高度
             $neww = $w * $scale;
             $newh = $h * $scale;
             $posx = ($width - $w * $scale) / 2;
             $posy = ($height - $h * $scale) / 2;
             //创建一张新图像
             $newimg = new Imagick();
             $newimg->newImage($width, $height, 'white', $this->info['type']);
             if ('gif' == $this->info['type']) {
                 $imgs = $this->img->coalesceImages();
                 $img = new Imagick();
                 $this->img->destroy();
                 //销毁原图
                 //循环填充每一帧
                 do {
                     //填充图像
                     $image = $this->_fill($newimg, $posx, $posy, $neww, $newh, $imgs);
                     $img->addImage($image);
                     $img->setImageDelay($imgs->getImageDelay());
                     $img->setImagePage($width, $height, 0, 0);
                     $image->destroy();
                     //销毁零时图片
                 } while ($imgs->nextImage());
                 //压缩图片
                 $this->img->destroy();
                 $this->img = $img->deconstructImages();
                 $imgs->destroy();
                 //销毁零时图片
                 $img->destroy();
                 //销毁零时图片
             } else {
                 //填充图像
                 $img = $this->_fill($newimg, $posx, $posy, $neww, $newh);
                 //销毁原图
                 $this->img->destroy();
                 $this->img = $img;
             }
             //设置新图像属性
             $this->info['width'] = $width;
             $this->info['height'] = $height;
             return;
             /* 固定 */
         /* 固定 */
         case Image::IMAGE_THUMB_FIXED:
             $x = $y = 0;
             break;
         default:
             throw new Exception('不支持的缩略图裁剪类型');
     }
     /* 裁剪图像 */
     $this->crop($w, $h, $x, $y, $width, $height);
 }
Ejemplo n.º 30
0
 /**
  * 对图片进行裁剪
  *
  * @param float $lx x起点(百分比模式,1为原图大小,如0.25)
  * @param float $rx x终点(百分比模式,1为原图大小,如0.75)
  * @param float $by y起点(百分比模式,1为原图大小,如0.25)
  * @param float $ty y终点(百分比模式,1为原图大小,如0.75)
  * @return bool
  * @author Sauwe
  */
 public function crop($lx = 0.25, $rx = 0.75, $by = 0.25, $ty = 0.75)
 {
     $lx = floatval($lx);
     $rx = floatval($rx);
     $by = floatval($by);
     $ty = floatval($ty);
     if ($rx < $lx or $ty < $by) {
         $this->_errno = SAE_ErrParameter;
         $this->_errmsg = "rx must greater than lx, ty must greater than by";
         return false;
     }
     if ($this->notValid()) {
         return false;
     }
     try {
         $im = new Imagick();
         $im->readImageBlob($this->_img_data);
         $width = ($rx - $lx) * $im->getImageWidth();
         $height = ($ty - $by) * $im->getImageHeight();
         $x = $lx * $im->getImageWidth();
         $y = $by * $im->getImageHeight();
         if ($im->cropImage($width, $height, $x, $y)) {
             if ($im->setImagePage(0, 0, 0, 0)) {
                 $this->_img_data = $im->getImageBlob();
                 return true;
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } catch (Exception $e) {
         $this->_errno = SAE_ErrUnknown;
         $this->_errmsg = $e->getMessage();
         return false;
     }
 }