/** * {@inheritdoc} */ public function animate($format, $delay, $loops) { if ('gif' !== strtolower($format)) { throw new InvalidArgumentException('Animated picture is currently only supported on gif'); } if (!is_int($loops) || $loops < 0) { throw new InvalidArgumentException('Loops must be a positive integer.'); } if (null !== $delay && (!is_int($delay) || $delay < 0)) { throw new InvalidArgumentException('Delay must be either null or a positive integer.'); } try { foreach ($this as $offset => $layer) { $this->resource->setIteratorIndex($offset); $this->resource->setFormat($format); if (null !== $delay) { $this->resource->setImageDelay($delay / 10); $this->resource->setImageTicksPerSecond(100); } $this->resource->setImageIterations($loops); $this->resource->setImage($layer->getImagick()); } } catch (\ImagickException $e) { throw new RuntimeException('Failed to animate layers', $e->getCode(), $e); } return $this; }
/** * Render the image to data string. * @param string $format * @param integer|null $quality * @return string */ protected function _render($format, $quality) { $format = $this->getFormat($format, $quality); $this->im->setFormat($format); if (isset($quality)) { $this->im->setImageCompressionQuality($quality); } return (string) $this->im; }
/** * Функция создания квадратного изображения с кадрированием. * @param string $sourceFile - путь до исходного файла * @param string $destinationFile - путь файла, в который сохраняется результат * @param integer $width * @param integer $height * @return */ function resizeImagick($sourceFile, $destinationFile, $width, $height, $resultType = 'gif') { $info = getimagesize($sourceFile); $destinationFile = $destinationFile; if (false === in_array($info[2], array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG))) { return false; } $originalWidth = $info[0]; $originalHeight = $info[1]; $ratio_orig = $originalWidth / $originalHeight; if ($width / $height > $ratio_orig) { $width = round($height * $ratio_orig); } else { $height = round($width / $ratio_orig); } if ($originalWidth < $width) { $height = $originalHeight; $width = $originalWidth; } $newWidth = $width; $newHeight = $height; $biggestSideSize = max($newWidth, $newHeight); # создаём новый пустой объект $newFileObj = new \Imagick(); # оригинальное изображение $im = new \Imagick($sourceFile); switch ($info[2]) { case IMAGETYPE_GIF: $im->setFormat("gif"); foreach ($im as $animation) { $animation->thumbnailImage($newWidth, $newHeight); //Выполняется resize до 200 пикселей поширине и сколько получится по высоте (с соблюдением пропорций конечно) $animation->setImagePage($animation->getImageWidth(), $animation->getImageHeight(), 0, 0); } $im->writeImages($destinationFile, true); return image_type_to_extension($info[2], false); break; case IMAGETYPE_PNG: $im = $im->coalesceImages(); $im->setFormat("gif"); $im->thumbnailImage($newWidth, $newHeight); $im->writeImages($destinationFile, true); return image_type_to_extension($info[2], false); break; case IMAGETYPE_JPEG: $im = $im->coalesceImages(); $im->setFormat("gif"); $im->thumbnailImage($newWidth, $newHeight); $im->writeImages($destinationFile, true); return image_type_to_extension($info[2], false); break; default: die($info[2] . 'd'); } }
function getSilhouette(\Imagick $imagick) { $character = new \Imagick(); $character->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "canvas:white"); $canvas = new \Imagick(); $canvas->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "canvas:black"); $character->compositeimage($imagick, \Imagick::COMPOSITE_COPYOPACITY, 0, 0); $canvas->compositeimage($character, \Imagick::COMPOSITE_ATOP, 0, 0); $canvas->setFormat('png'); return $canvas; }
/** * Generate the animated gif * * @return string binary image data */ private function createAnimation($images) { $animation = new \Imagick(); $animation->setFormat('gif'); foreach ($images as $image) { $frame = new \Imagick(); $frame->readImageBlob($image); $animation->addImage($frame); $animation->setImageDelay(50); } return $animation->getImagesBlob(); }
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); }
/** * {@inheritdoc} */ public function animate($format, $delay, $loops) { if ('gif' !== strtolower($format)) { throw new InvalidArgumentException('Animated picture is currently only supported on gif'); } foreach (array('Loops' => $loops, 'Delay' => $delay) as $name => $value) { if (!is_int($value) || $value < 0) { throw new InvalidArgumentException(sprintf('%s must be a positive integer.', $name)); } } try { foreach ($this as $offset => $layer) { $this->resource->setIteratorIndex($offset); $this->resource->setFormat($format); $this->resource->setImageDelay($delay / 10); $this->resource->setImageTicksPerSecond(100); $this->resource->setImageIterations($loops); } } catch (\ImagickException $e) { throw new RuntimeException('Failed to animate layers', $e->getCode(), $e); } return $this; }
function renderCustomImage() { $size = 400; $imagick1 = new \Imagick(); //$imagick1->newPseudoImage($size, $size, 'gradient:black-white'); $imagick1->setColorspace(\Imagick::COLORSPACE_GRAY); //$imagick1->setColorspace(\Imagick::COLORSPACE_RGB); //$imagick1->setColorspace(\Imagick::COLORSPACE_SRGB); $imagick1->setColorspace(\Imagick::COLORSPACE_CMYK); $imagick1->newPseudoImage($size, $size, 'gradient:gray(100%)-gray(0%)'); $imagick1->setFormat('png'); //analyzeImage($imagick1); header("Content-Type: image/png"); echo $imagick1->getImageBlob(); }
protected function _generateImage($text, $filePath) { $image = new Imagick(); $draw = new ImagickDraw(); $draw->setFont('lib/SwiftOtter/OpenSans-Regular.ttf'); $draw->setFontSize('13'); $metrics = $image->queryFontMetrics($draw, $text, false); $width = 100; $padding = 10; if (isset($metrics['textWidth'])) { $width = $metrics['textWidth'] + $padding * 2; } $image->newImage($width, 17, new ImagickPixel('#f98b25')); $draw->setFillColor('#ffffff'); $image->annotateImage($draw, $padding / 2 + 3, $padding + 3, 0, $text); $draw->setFillColor('#a04300'); $image->borderImage('#a04300', 1, 1); $image->setFormat('gif'); $image->writeImage($filePath); return $image; }
/** * @param string $file * @param int $quality * * @throws \ManaPHP\Image\Adapter\Exception */ public function save($file, $quality = 80) { $file = $this->alias->resolve($file); $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $this->_image->setFormat($ext); if ($ext === 'gif') { $this->_image->optimizeImageLayers(); } else { if ($ext === 'jpg' || $ext === 'jpeg') { $this->_image->setImageCompression(\Imagick::COMPRESSION_JPEG); $this->_image->setImageCompressionQuality($quality); } } $dir = dirname($file); if (!@mkdir($dir, 0755, true) && !is_dir($dir)) { throw new ImagickException('create `:dir` image directory failed: :message', ['dir' => $dir, 'message' => error_get_last()['message']]); } if (!$this->_image->writeImage($file)) { throw new ImagickException('save `:file` image file failed', ['file' => $file]); } }
<?php $imagick = new \Imagick(); $desiredWidth = 300; $desiredWidth = 2 * intval($desiredWidth / 2); $imagick->newpseudoimage($desiredWidth / 2, 1, "gradient:white-black"); $imagick->setFormat('png'); $imagick->setImageVirtualPixelMethod(\Imagick::VIRTUALPIXELMETHOD_MIRROR); $originalWidth = $imagick->getImageWidth(); //Now scale, rotate, translate (aka affine project) it //to be how you want $points = array($originalWidth / $desiredWidth, 0, 0, 1, 0, 0); //Make the image be the desired width. $imagick->sampleimage($desiredWidth, $imagick->getImageHeight()); $imagick->distortImage(\Imagick::DISTORTION_AFFINEPROJECTION, $points, false); header("Content-Type: image/png"); echo $imagick->getImageBlob();
protected function addImagePngAlpha($file, $x, $y, $w, $h, $byte) { // generate images $img = imagecreatefrompng($file); if ($img === false) { return; } // FIXME The pixel transformation doesn't work well with 8bit PNGs $eight_bit = ($byte & 4) !== 4; $wpx = imagesx($img); $hpx = imagesy($img); imagesavealpha($img, false); // create temp alpha file $tempfile_alpha = tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_alpha); $tempfile_alpha = "{$tempfile_alpha}.png"; // create temp plain file $tempfile_plain = tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_plain); $tempfile_plain = "{$tempfile_plain}.png"; $imgalpha = imagecreate($wpx, $hpx); imagesavealpha($imgalpha, false); // generate gray scale palette (0 -> 255) for ($c = 0; $c < 256; ++$c) { imagecolorallocate($imgalpha, $c, $c, $c); } // Use PECL gmagick + Graphics Magic to process transparent PNG images if (extension_loaded("gmagick")) { $gmagick = new Gmagick($file); $gmagick->setimageformat('png'); // Get opacity channel (negative of alpha channel) $alpha_channel_neg = clone $gmagick; $alpha_channel_neg->separateimagechannel(Gmagick::CHANNEL_OPACITY); // Negate opacity channel $alpha_channel = new Gmagick(); $alpha_channel->newimage($wpx, $hpx, "#FFFFFF", "png"); $alpha_channel->compositeimage($alpha_channel_neg, Gmagick::COMPOSITE_DIFFERENCE, 0, 0); $alpha_channel->separateimagechannel(Gmagick::CHANNEL_RED); $alpha_channel->writeimage($tempfile_alpha); // Cast to 8bit+palette $imgalpha_ = imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); // Make opaque image $color_channels = new Gmagick(); $color_channels->newimage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeimage($tempfile_plain); $imgplain = imagecreatefrompng($tempfile_plain); } elseif (extension_loaded("imagick")) { $imagick = new Imagick($file); $imagick->setFormat('png'); // Get opacity channel (negative of alpha channel) $alpha_channel = clone $imagick; $alpha_channel->separateImageChannel(Imagick::CHANNEL_ALPHA); $alpha_channel->negateImage(true); $alpha_channel->writeImage($tempfile_alpha); // Cast to 8bit+palette $imgalpha_ = imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); // Make opaque image $color_channels = new Imagick(); $color_channels->newImage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeImage($tempfile_plain); $imgplain = imagecreatefrompng($tempfile_plain); } else { // allocated colors cache $allocated_colors = array(); // extract alpha channel for ($xpx = 0; $xpx < $wpx; ++$xpx) { for ($ypx = 0; $ypx < $hpx; ++$ypx) { $color = imagecolorat($img, $xpx, $ypx); $col = imagecolorsforindex($img, $color); $alpha = $col['alpha']; if ($eight_bit) { // with gamma correction $gammacorr = 2.2; $pixel = pow((127 - $alpha) * 255 / 127 / 255, $gammacorr) * 255; } else { // without gamma correction $pixel = (127 - $alpha) * 2; $key = $col['red'] . $col['green'] . $col['blue']; if (!isset($allocated_colors[$key])) { $pixel_img = imagecolorallocate($img, $col['red'], $col['green'], $col['blue']); $allocated_colors[$key] = $pixel_img; } else { $pixel_img = $allocated_colors[$key]; } imagesetpixel($img, $xpx, $ypx, $pixel_img); } imagesetpixel($imgalpha, $xpx, $ypx, $pixel); } } // extract image without alpha channel $imgplain = imagecreatetruecolor($wpx, $hpx); imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($img); imagepng($imgalpha, $tempfile_alpha); imagepng($imgplain, $tempfile_plain); } // embed mask image $this->addImagePng($tempfile_alpha, $x, $y, $w, $h, $imgalpha, true); imagedestroy($imgalpha); // embed image, masked with previously embedded mask $this->addImagePng($tempfile_plain, $x, $y, $w, $h, $imgplain, false, true); imagedestroy($imgplain); // remove temp files unlink($tempfile_alpha); unlink($tempfile_plain); }
/** * Return raw image data. * * @param string $pathToImage * * @return \Imagick */ public function getImageData($pathToImage) { $imagick = new \Imagick(); $imagick->setResolution($this->resolution, $this->resolution); $imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1)); $imagick->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN); $imagick->setFormat($this->determineOutputFormat($pathToImage)); return $imagick; }
} else { $favorites = 0; } if ($row['FAVORITES'] == NULL) { $favorites = 0; } if ($row['FILE'] != "gif") { $thumb_fn = $setting['image_output'] . 'thumbnails/' . $row['ID'] . '.jpg'; } else { $thumb_fn = $setting['image_output'] . 'thumbnails/' . $row['ID'] . '.gif'; } if (!file_exists($thumb_fn)) { $image = new Imagick(); $image->readImage($setting['image_output'] . $row['ID'] . "." . $row['FILE']); if ($row['FILE'] != "gif") { $image->setFormat("jpg"); $image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality($setting['thumbnail_quality']); $image->thumbnailImage($setting['thumbnail_size'], 0); $image->writeImage($thumb_fn); } else { $image->setFormat("gif"); $image = $image->coalesceImages(); foreach ($image as $frame) { $frame->thumbnailImage($setting['thumbnail_size'], 0); $frame->setImagePage($setting['thumbnail_size'], 0, 0, 0); } $image = $image->deconstructImages(); $image->writeImages($thumb_fn, true); } $image->clear();
/** * {@inheritdoc} */ public function animate(array $frames, $delay = 20) { $gif = new \Imagick(); $gif->setFormat('gif'); foreach ($frames as $im) { if ($im instanceof Imanee) { $frame = $im->getResource()->getResource(); } else { $frame = new \Imagick($im); } $frame->setImageDelay($delay); $gif->addImage($frame); } $imagickResource = new ImagickResource(); $imagickResource->setResource($gif); $imanee = new Imanee(); $imanee->setResource($imagickResource); $imanee->setFormat('gif'); return $imanee; }
public function make_block9($files, $save = null, $rawData = true) { if (!(count($files) >= 9)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '參數錯誤,files count:' . count($files), '參數 files 數量一定要大於 9!'); } if (!$save) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '錯誤的儲存路徑,save' . $save, '請再次確認儲存路徑!'); } $newImage = new Imagick(); $newImage->newImage(266, 200, new ImagickPixel('white')); $newImage->setFormat(pathinfo($save, PATHINFO_EXTENSION)); $positions = array(array('left' => 2, 'top' => 2, 'width' => 130, 'height' => 130), array('left' => 134, 'top' => 2, 'width' => 64, 'height' => 64), array('left' => 200, 'top' => 2, 'width' => 64, 'height' => 64), array('left' => 134, 'top' => 68, 'width' => 64, 'height' => 64), array('left' => 200, 'top' => 68, 'width' => 64, 'height' => 64), array('left' => 2, 'top' => 134, 'width' => 64, 'height' => 64), array('left' => 68, 'top' => 134, 'width' => 64, 'height' => 64), array('left' => 134, 'top' => 134, 'width' => 64, 'height' => 64), array('left' => 200, 'top' => 134, 'width' => 64, 'height' => 64)); for ($i = 0; $i < 9; $i++) { $newImage->compositeImage(ImageUtility::create($files[$i])->getImage(), imagick::COMPOSITE_DEFAULT, $positions[$i]['left'], $positions[$i]['top']); } return $newImage->writeImages($save, $rawData); }
protected function addImagePngAlpha($file, $x, $y, $w, $h, $byte) { $img = imagecreatefrompng($file); if ($img === false) { return; } $eight_bit = ($byte & 4) !== 4; $wpx = imagesx($img); $hpx = imagesy($img); imagesavealpha($img, false); $tempfile_alpha = tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_alpha); $tempfile_alpha = "{$tempfile_alpha}.png"; $tempfile_plain = tempnam($this->tmp, "cpdf_img_"); @unlink($tempfile_plain); $tempfile_plain = "{$tempfile_plain}.png"; $imgalpha = imagecreate($wpx, $hpx); imagesavealpha($imgalpha, false); for ($c = 0; $c < 256; ++$c) { imagecolorallocate($imgalpha, $c, $c, $c); } if (extension_loaded("gmagick")) { $gmagick = new Gmagick($file); $gmagick->setimageformat('png'); $alpha_channel_neg = clone $gmagick; $alpha_channel_neg->separateimagechannel(Gmagick::CHANNEL_OPACITY); $alpha_channel = new Gmagick(); $alpha_channel->newimage($wpx, $hpx, "#FFFFFF", "png"); $alpha_channel->compositeimage($alpha_channel_neg, Gmagick::COMPOSITE_DIFFERENCE, 0, 0); $alpha_channel->separateimagechannel(Gmagick::CHANNEL_RED); $alpha_channel->writeimage($tempfile_alpha); $imgalpha_ = imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); $color_channels = new Gmagick(); $color_channels->newimage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeimage($gmagick, Gmagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeimage($tempfile_plain); $imgplain = imagecreatefrompng($tempfile_plain); } elseif (extension_loaded("imagick")) { $imagick = new Imagick($file); $imagick->setFormat('png'); $alpha_channel = clone $imagick; $alpha_channel->separateImageChannel(Imagick::CHANNEL_ALPHA); $alpha_channel->negateImage(true); $alpha_channel->writeImage($tempfile_alpha); $imgalpha_ = imagecreatefrompng($tempfile_alpha); imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($imgalpha_); imagepng($imgalpha, $tempfile_alpha); $color_channels = new Imagick(); $color_channels->newImage($wpx, $hpx, "#FFFFFF", "png"); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYRED, 0, 0); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYGREEN, 0, 0); $color_channels->compositeImage($imagick, Imagick::COMPOSITE_COPYBLUE, 0, 0); $color_channels->writeImage($tempfile_plain); $imgplain = imagecreatefrompng($tempfile_plain); } else { $allocated_colors = array(); for ($xpx = 0; $xpx < $wpx; ++$xpx) { for ($ypx = 0; $ypx < $hpx; ++$ypx) { $color = imagecolorat($img, $xpx, $ypx); $col = imagecolorsforindex($img, $color); $alpha = $col['alpha']; if ($eight_bit) { $gammacorr = 2.2; $pixel = pow((127 - $alpha) * 255 / 127 / 255, $gammacorr) * 255; } else { $pixel = (127 - $alpha) * 2; $key = $col['red'] . $col['green'] . $col['blue']; if (!isset($allocated_colors[$key])) { $pixel_img = imagecolorallocate($img, $col['red'], $col['green'], $col['blue']); $allocated_colors[$key] = $pixel_img; } else { $pixel_img = $allocated_colors[$key]; } imagesetpixel($img, $xpx, $ypx, $pixel_img); } imagesetpixel($imgalpha, $xpx, $ypx, $pixel); } } $imgplain = imagecreatetruecolor($wpx, $hpx); imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx); imagedestroy($img); imagepng($imgalpha, $tempfile_alpha); imagepng($imgplain, $tempfile_plain); } $this->addImagePng($tempfile_alpha, $x, $y, $w, $h, $imgalpha, true); imagedestroy($imgalpha); $this->addImagePng($tempfile_plain, $x, $y, $w, $h, $imgplain, false, true); imagedestroy($imgplain); unlink($tempfile_alpha); unlink($tempfile_plain); }
if (!CheckTourSession()) { print get_text('CrackError'); exit; } $Errore = 0; $Answer = ''; $AthId = 0; $image = null; if (!empty($_REQUEST["Id"]) && ($EnId = intval($_REQUEST["Id"]))) { if (!empty($_REQUEST["picDelete"])) { safe_w_sql("DELETE FROM Photos WHERE PhEnId={$EnId}"); } if (!empty($_REQUEST["picEncoded"])) { $picEncoded = str_replace(array('data:image/png;base64,', ' '), array('', '+'), $_REQUEST["picEncoded"]); $im = new Imagick(); $im->setFormat('jpg'); if ($im->readImageBlob(base64_decode($picEncoded))) { $w = $im->getImageWidth(); $h = $im->getimageheight(); // echo $w . "." . $h;exit; if ($w != MAX_WIDTH or $h != MAX_HEIGHT) { // resize image $im->scaleimage($w / $h < MAX_WIDTH / MAX_HEIGHT ? MAX_WIDTH : 0, $w / $h < MAX_WIDTH / MAX_HEIGHT ? 0 : MAX_HEIGHT); $w = $im->getImageWidth(); $h = $im->getimageheight(); $im->cropimage(MAX_WIDTH, MAX_HEIGHT, ($w - MAX_WIDTH) / 2, ($h - MAX_HEIGHT) / 2); } $imgtoSave = StrSafe_DB(base64_encode($im->getImageBlob())); safe_w_sql("insert into Photos set PhEnId={$EnId}, PhPhoto={$imgtoSave} on duplicate key update PhPhoto={$imgtoSave}"); require_once 'Common/CheckPictures.php'; updatePhoto($EnId);
public function extent($width, $height, $rgb) { $color = "rgb({$rgb[0]},{$rgb[1]},{$rgb[2]})"; $new = new ImagickCore(); $new->newImage($width, $height, $color); $new->compositeImage($this->_object, ImagickCore::COMPOSITE_OVER, $width / 2 - $this->width() / 2, $height / 2 - $this->height() / 2); $new->setFormat($this->_object->getFormat()); $this->_object = $new; return true; }
/** * Put image to square * * @param string $path image file * @param int $width square width * @param int $height square height * @param int|string $align reserved * @param int|string $valign reserved * @param string $bgcolor square background color in #rrggbb format * @param string $destformat image destination format * @param int $jpgQuality JEPG quality (1-100) * @return false|string * @author Dmitry (dio) Levashov * @author Alexey Sukhotin */ protected function imgSquareFit($path, $width, $height, $align = 'center', $valign = 'middle', $bgcolor = '#0000ff', $destformat = null, $jpgQuality = null) { if (($s = getimagesize($path)) == false) { return false; } $result = false; /* Coordinates for image over square aligning */ $y = ceil(abs($height - $s[1]) / 2); $x = ceil(abs($width - $s[0]) / 2); if (!$jpgQuality) { $jpgQuality = $this->options['jpgQuality']; } elFinder::extendTimeLimit(300); switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } if ($bgcolor === 'transparent') { $bgcolor = 'rgba(255, 255, 255, 0.0)'; } $ani = $img->getNumberImages() > 1; if ($ani && is_null($destformat)) { $img1 = new Imagick(); $img1->setFormat('gif'); $img = $img->coalesceImages(); do { $gif = new Imagick(); $gif->newImage($width, $height, new ImagickPixel($bgcolor)); $gif->setImageColorspace($img->getImageColorspace()); $gif->setImageFormat('gif'); $gif->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y); $gif->setImageDelay($img->getImageDelay()); $gif->setImageIterations($img->getImageIterations()); $img1->addImage($gif); $gif->clear(); } while ($img->nextImage()); $img1 = $img1->optimizeImageLayers(); $result = $img1->writeImages($path, true); } else { if ($ani) { $img->setFirstIterator(); } $img1 = new Imagick(); $img1->newImage($width, $height, new ImagickPixel($bgcolor)); $img1->setImageColorspace($img->getImageColorspace()); $img1->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y); $result = $this->imagickImage($img1, $path, $destformat, $jpgQuality); } $img1->clear(); $img->clear(); return $result ? $path : false; break; case 'convert': extract($this->imageMagickConvertPrepare($path, $destformat, $jpgQuality, $s)); if ($bgcolor === 'transparent') { $bgcolor = 'rgba(255, 255, 255, 0.0)'; } $cmd = sprintf('convert -size %dx%d "xc:%s" png:- | convert%s%s png:- %s -geometry +%d+%d -compose over -composite%s %s', $width, $height, $bgcolor, $coalesce, $jpgQuality, $quotedPath, $x, $y, $deconstruct, $quotedDstPath); $result = false; if ($this->procExec($cmd) === 0) { $result = true; } return $result ? $path : false; break; case 'gd': $img = $this->gdImageCreate($path, $s['mime']); if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) { $this->gdImageBackground($tmp, $bgcolor); if ($bgcolor === 'transparent' && ($destformat === 'png' || $s[2] === IMAGETYPE_PNG)) { $bgNum = imagecolorallocatealpha($tmp, 255, 255, 255, 127); imagefill($tmp, 0, 0, $bgNum); } if (!imagecopy($tmp, $img, $x, $y, 0, 0, $s[0], $s[1])) { return false; } $result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality); imagedestroy($img); imagedestroy($tmp); return $result ? $path : false; } break; } return false; }
/** * Image conversion abstraction. * * @param string $source * @param array $size * @return Imagick */ protected function _convert($source, $size) { extract($size); $im = new Imagick(); $js = 0; $hint = max($tw, $th) * $js; if ($hint > 0 && $hint < $sw && $hint < $sh) { if (pathinfo($source, PATHINFO_EXTENSION) === 'jpg') { $im->setOption('jpeg:size', sprintf('%dx%d', $hint, $hint)); } } $im->readImage($source); if ($im->getNumberImages() > 1) { $im->flattenImages(); } $colorspace = $im->getImageColorSpace(); if ($colorspace !== Imagick::COLORSPACE_RGB && $colorspace !== Imagick::COLORSPACE_SRGB) { $im->setImageColorSpace(Imagick::COLORSPACE_SRGB); } if ($im->getImageMatte()) { $im->setImageMatte(false); } if ($this->doesTrimming()) { $im->cropImage($sw, $sh, $sx, $sy); } if ($this->doesResampling()) { $im->resizeImage($tw, $th, Imagick::FILTER_LANCZOS, 0.9, true); } $im->stripImage(); $degrees = $this->getRotation(); if ($degrees) { $bgcolor = $this->getBgColor(); $bg = sprintf('rgb(%d,%d,%d)', $bgcolor[0], $bgcolor[1], $bgcolor[2]); $im->rotateImage(new ImagickPixel($bg), $degrees); } if ($this->isPng()) { $im->setFormat('PNG'); } else { $im->setFormat('JPEG'); if ($this->getQuality()) { $im->setCompressionQuality($this->getQuality()); } } return $im; }
// 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); //} //Imagick::DITHERMETHOD_RIEMERSMA //Imagick::DITHERMETHOD_FLOYDSTEINBERG //6.9meg //$imagickFrame->quantizeImage(255, Imagick::COLORSPACE_RGB, 0, true, false ); //orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_ALL ] ) //posterizeImage ( int $levels , bool $dither ) //$imagickFrame->remapimage() $imagickFrame->setImageDelay($frameDelay); $animation->addImage($imagickFrame); } //Zero default - 8 biggest tree //$animation->quantizeImages(255, Imagick::COLORSPACE_RGB, 0, false, false ); //$animation->quantizeImages(255, Imagick::COLORSPACE_RGB, 8, true, false ); //Imagick::clutImage ( Imagick $lookup_table [, float $channel = Imagick::CHANNEL_DEFAULT ] ) $animation->setFormat('gif'); $animation->setImageFormat('gif'); $outputGif = $animation->deconstructImages(); $outputFilename = $animDir . ".gif"; $outputGif->writeImages($outputFilename, true); $filesize = filesize($outputFilename); echo "output is {$outputFilename}, filesize is {$filesize} \n";
public function mask() { header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); if ($this->input->get('image')) { $image = $this->input->get('image'); // $image_directory = BASEPATH . '../images/masks/'; // XXX: dev $image_directory = BASEPATH . '../../www/images/masks/'; // XXX: staging $image_url = '/images/masks/'; /* XXX: Temporary insecure stub! */ $download = file_get_contents($image); $image = md5(parse_url($image, PHP_URL_PATH)) . '.png'; $url = $image_url . $image; file_put_contents($image_directory . $image, $download); if (!$image) { return; } $image = $image_directory . $image; if (!file_exists($image)) { return; } $source_image = new Imagick(); $source_image->readImage($image); if (!$source_image instanceof Imagick) { return; } $extension = pathinfo($image, PATHINFO_EXTENSION); if (in_array($extension, array('jpg', 'jpeg', 'png', 'gif'))) { $source_image->setFormat($extension); } else { break; } $mask_image = $source_image->clone(); $mask_image->modulateImage(100, 100, 130); $background = $mask_image->getImagePixelColor(3, 3); $iQuantumDepth = pow(2, $mask_image->getQuantumDepth()['quantumDepthLong']); $mask_image->paintOpaqueImage($background, 'white', 0.2 * $iQuantumDepth); $mask_image->negateImage(false); $mask_image->thresholdImage(0); $mask_image->setImageMatte(false); $source_image->compositeImage($mask_image, Imagick::COMPOSITE_COPYOPACITY, 0, 0); $masked_image = preg_replace(sprintf('#(\\.%s)$#', $extension), '.mask0$1', $image); $source_image->writeImage($masked_image); echo json_encode(preg_replace(sprintf('#(\\.%s)$#', $extension), '.mask0$1', $url)); } }
function createFavicon() { $favicon_image = $this->_params->get('favicon_image'); $favicon_path = 'templates/blank_j3/favicon/'; if (isset($favicon_image)) { if (!is_dir(__DIR__ . '/../favicon')) { mkdir(__DIR__ . '/../favicon', 0777, true); } $favicon_set = array('apple-touch-icon' => array(57, 60, 72, 76, 114, 120, 144, 152), 'favicon' => array(16, 32, 96, 160, 196), 'mstile' => array(70, 144, 150, 310)); $return_favicons = ''; // create favicons for all except Win foreach ($favicon_set as $name => $sizes) { foreach ($sizes as $size) { $favicon_name = "{$name}-{$size}" . "x{$size}.png"; $outFile = __DIR__ . "/../favicon/{$favicon_name}"; $image = new Imagick($favicon_image); $image->adaptiveResizeImage($size, $size, true); $image->setImageBackgroundColor('None'); $image->thumbnailImage($size, $size, 1, 'None'); $image->writeImage($outFile); //echo "<img src='$favicon_path/$favicon_name' />"; if ($name != 'mstile') { $return_favicons .= "<link rel='{$name}' sizes='{$size}" . "x{$size}' href='{$favicon_path}/{$favicon_name}'>"; } unset($image); } } // create favicon for Win // generate XML $tile_bg_win = $this->_params->get('bg_win'); $xml_data = <<<XML <?xml version="1.0" encoding="utf-8"?> <browserconfig> <msapplication> <tile> <square70x70logo src="{$favicon_path}/mstile-70x70.png"/> <square150x150logo src="{$favicon_path}/mstile-150x150.png"/> <square310x310logo src="{$favicon_path}/mstile-310x310.png"/> <wide310x150logo src="{$favicon_path}/mstile-310x150.png"/> <TileColor>{$tile_bg_win}</TileColor> </tile> </msapplication> </browserconfig> XML; file_put_contents(__DIR__ . "/../favicon/browserconfig.xml", $xml_data); $return_favicons .= "<meta name='msapplication-TileColor' content='{$tile_bg_win}'>"; $return_favicons .= "<meta name='msapplication-TileImage' content='{$favicon_path}/mstile-144x144.png'>"; $return_favicons .= "<meta name='msapplication-config' content='{$favicon_path}/browserconfig.xml'>"; // generate favicon.ico $image = new Imagick($favicon_image); $image->cropThumbnailImage(32, 32); $image->setFormat('ico'); $image->writeImage("{$favicon_path}/favicon.ico"); unset($image); $return_favicons .= "<link rel='shortcut icon' href='{$favicon_path}/favicon.ico'>"; return $return_favicons; } }
public function getFileContents($file, $language = null) { $ret = array(); if (substr($file, -4) == '.gif') { $ret['mimeType'] = 'image/gif'; } else { if (substr($file, -4) == '.png') { $ret['mimeType'] = 'image/png'; } else { if (substr($file, -4) == '.jpg') { $ret['mimeType'] = 'image/jpeg'; } else { if (substr($file, -4) == '.mp4') { $ret['mimeType'] = 'video/mp4'; } else { if (substr($file, -5) == '.webm') { $ret['mimeType'] = 'video/webm'; } else { if (substr($file, -4) == '.css' || substr($file, -5) == '.scss') { $ret['mimeType'] = 'text/css; charset=utf-8'; if (!Kwf_Assets_Dispatcher::allowSourceAccess()) { throw new Kwf_Exception_AccessDenied(); } } else { if (substr($file, -3) == '.js') { $ret['mimeType'] = 'text/javascript; charset=utf-8'; if (!Kwf_Assets_Dispatcher::allowSourceAccess()) { throw new Kwf_Exception_AccessDenied(); } } else { if (substr($file, -4) == '.swf') { $ret['mimeType'] = 'application/flash'; } else { if (substr($file, -4) == '.ico') { $ret['mimeType'] = 'image/x-icon'; } else { if (substr($file, -5) == '.html') { $ret['mimeType'] = 'text/html; charset=utf-8'; } else { if (substr($file, -4) == '.otf') { // für Schriften $ret['mimeType'] = 'application/octet-stream'; } else { if (substr($file, -4) == '.eot') { // für Schriften $ret['mimeType'] = 'application/vnd.ms-fontobject'; } else { if (substr($file, -4) == '.svg') { // für Schriften $ret['mimeType'] = 'image/svg+xml'; } else { if (substr($file, -4) == '.ttf') { // für Schriften $ret['mimeType'] = 'application/octet-stream'; } else { if (substr($file, -5) == '.woff') { // für Schriften $ret['mimeType'] = 'application/font-woff'; } else { if (substr($file, -6) == '.woff2') { // für Schriften $ret['mimeType'] = 'application/font-woff2'; } else { if (substr($file, -4) == '.htc') { // für ie css3 $ret['mimeType'] = 'text/x-component'; } else { if (substr($file, -4) == '.pdf') { $ret['mimeType'] = 'application/pdf'; } else { throw new Kwf_Assets_NotFoundException("Invalid filetype ({$file})"); } } } } } } } } } } } } } } } } } } if (substr($ret['mimeType'], 0, 5) == 'text/') { $ret['mtime'] = time(); $file = new Kwf_Assets_Dependency_File($file); if (!$file->getAbsoluteFileName() || !file_exists($file->getAbsoluteFileName())) { throw new Kwf_Exception_NotFound(); } $ret['contents'] = $file->getContents(null); } else { $fx = substr($file, 0, strpos($file, '/')); if (substr($fx, 0, 3) == 'fx_') { $cache = Kwf_Assets_Cache::getInstance(); $cacheId = 'fileContents' . str_replace(array('/', '.', '-', ':'), array('_', '_', '_', '_'), $file); if (!($cacheData = $cache->load($cacheId))) { if (substr($ret['mimeType'], 0, 6) != 'image/') { throw new Kwf_Exception("Fx is only possible for images"); } $im = new Imagick(); if (substr($file, -4) == '.ico') { $im->setFormat('ico'); } //required because imagick can't autodetect ico format $file = new Kwf_Assets_Dependency_File(substr($file, strpos($file, '/') + 1)); $im->readImage($file->getAbsoluteFileName()); $fx = explode('_', substr($fx, 3)); foreach ($fx as $i) { $params = array(); if (($pos = strpos($i, '-')) !== false) { $params = explode('-', substr($i, $pos + 1)); $i = substr($i, 0, $pos); } call_user_func(array('Kwf_Assets_Effects', $i), $im, $params); } $cacheData['mtime'] = $file->getMTime(); $cacheData['contents'] = $im->getImagesBlob(); $im->destroy(); $cache->save($cacheData, $cacheId); } $ret['contents'] = $cacheData['contents']; $ret['mtime'] = time(); } else { $ret['mtime'] = time(); $file = new Kwf_Assets_Dependency_File($file); if (!file_exists($file->getAbsoluteFileName())) { throw new Kwf_Exception_NotFound(); } $ret['contents'] = $file->getContents(null); } } return $ret; }
private function getCharacterOutline() { //Example ImagickKernel::morphology $imagick = new \Imagick(realpath("./images/character.png")); $character = new \Imagick(); $character->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "canvas:white"); $canvas = new \Imagick(); $canvas->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "canvas:black"); $character->compositeimage($imagick, \Imagick::COMPOSITE_COPYOPACITY, 0, 0); $canvas->compositeimage($character, \Imagick::COMPOSITE_ATOP, 0, 0); $canvas->setFormat('png'); return $canvas; //Example end }
/** * Put image to square * * @param string $path image file * @param int $width square width * @param int $height square height * @param int $align reserved * @param int $valign reserved * @param string $bgcolor square background color in #rrggbb format * @param string $destformat image destination format * @return string|false * @author Dmitry (dio) Levashov * @author Alexey Sukhotin **/ protected function imgSquareFit($path, $width, $height, $align = 'center', $valign = 'middle', $bgcolor = '#0000ff', $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; /* Coordinates for image over square aligning */ $y = ceil(abs($height - $s[1]) / 2); $x = ceil(abs($width - $s[0]) / 2); switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $ani = $img->getNumberImages() > 1; if ($ani && is_null($destformat)) { $img1 = new Imagick(); $img1->setFormat('gif'); $img = $img->coalesceImages(); do { $gif = new Imagick(); $gif->newImage($width, $height, new ImagickPixel($bgcolor)); $gif->setImageColorspace($img->getImageColorspace()); $gif->setImageFormat('gif'); $gif->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y); $gif->setImageDelay($img->getImageDelay()); $gif->setImageIterations($img->getImageIterations()); $img1->addImage($gif); $gif->destroy(); } while ($img->nextImage()); $img1 = $img1->optimizeImageLayers(); $result = $img1->writeImages($path, true); } else { if ($ani) { $img->setFirstIterator(); } $img1 = new Imagick(); $img1->newImage($width, $height, new ImagickPixel($bgcolor)); $img1->setImageColorspace($img->getImageColorspace()); $img1->setImageFormat($destformat != null ? $destformat : $img->getFormat()); $img1->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y); $result = $img1->writeImage($path); } $img1->destroy(); $img->destroy(); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path, $s['mime']); if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) { self::gdImageBackground($tmp, $bgcolor); if (!imagecopy($tmp, $img, $x, $y, 0, 0, $s[0], $s[1])) { return false; } $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imagedestroy($img); imagedestroy($tmp); return $result ? $path : false; } break; } return false; }
if ($row2['RATING'] > $max_rating) { continue; } if (isset($favorites)) { $favorites = count(explode(",", $row2['FAVORITES'])); } else { $favorites = 0; } if ($row2['FAVORITES'] == NULL) { $favorites = 0; } $thumb_fn = $setting['image_output'] . 'thumbnails/' . $row2['ID'] . '.jpg'; if (!file_exists($thumb_fn)) { $image = new Imagick(); $image->readImage($setting['image_output'] . $row2['ID'] . "." . $row2['FILE']); $image->setFormat("jpg"); $image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality($setting['thumbnail_quality']); $image->thumbnailImage($setting['thumbnail_size'], 0); $image->writeImage($thumb_fn); $image->clear(); } //$output = $image->getImageBlob(); echo '<a href="image.php?id=' . $row2['ID'] . '"><div class="image" style="background-image: url(' . $setting['image_output_htmlsafe'] . 'thumbnails/' . $row2['ID'] . '.jpg);">'; if (time() - 24 * 60 * 60 <= $row2['DATEADD']) { echo '<div class="new_banner">NEW</div>'; } echo '<div class="info"> <div class="i_l"> <span style="color: ' . getRatingColor($row2['RATING']) . '; padding-left: 10px;">' . getRating($row2['RATING']) . '</span> </div>
/** * Create an image thumbnail. * * This function can be used to create a scaled down thumbnail version of * an image. You can specifiy a width and/or a height to which to scale * down the image. The aspect ratio will always be kept. If both a width * and height are provided, then the one which requires the largest scale * down will be leading. * * @param string $image * The raw binary image data. * * @param integer $max_w * The maximum allowed width for the image in pixels. * Use NULL or 0 (zero) to indicate that any width will do. * * @param integer $max_h * The maximum allowed height for the image in pixels. * Use NULL or 0 (zero) to indicate that any height will do. * * @param string $method * The method to use for scaling the image. By default, this function * will try to autodetect a working method. Providing a $method parameter * is mostly useful for debugging purposes. Available methods (in the * order in which they are probed in the code) are: * - gd: using the GD library (requires extension "gd") * - imagick: using the ImageMagick library (requires extension "imagick") * - convert: using the ImageMagick "convert" tool (requires the * ImageMagick package to be installed on the server, does not work * in combination with some PHP safety restrictions). * * @return mixed * NULL is returned in case creating the thumbnail failed. The function * {@link phorum_api_strerror()} can be used to retrieve information * about the error which occurred. * * An array is returned in case creating the thumbnail did work. * This array contains the following fields: * - image: The scaled down image. NULL if no scaling was needed. * - method: The method that was used to create the thumbnail. * - cur_w: The width of the original $image. * - cur_h: The height of the original $image. * - cur_mime: The MIME type of the original $image. * - new_w: The width of the scaled down image. * - new_h: The height of the scaled down image. * - new_mime: The MIME type of the scaled down image, */ function phorum_api_image_thumbnail($image, $max_w = NULL, $max_h = NULL, $method = NULL) { // Reset error storage. $GLOBALS['PHORUM']['API']['errno'] = NULL; $GLOBALS['PHORUM']['API']['error'] = NULL; $error = NULL; if (empty($max_w)) { $max_w = NULL; } if (empty($max_h)) { $max_h = NULL; } // Initialize the return array. $img = array('image' => NULL, 'new_mime' => NULL); // Check if PHP supports the getimagesize() function. I think it // always should, but let's check it to be sure. if (!function_exists('getimagesize')) { return phorum_api_error_set(PHORUM_ERRNO_ERROR, 'Your PHP installation lacks "getimagesize()" support'); } // Try to determine the image type and size using the getimagesize() // PHP function. Unfortunately, this function requires a file on disk // to process. Therefore we create a temporary file in the Phorum cache // for doing this. require_once './include/api/write_file.php'; $tmpdir = $GLOBALS['PHORUM']['cache']; $tmpfile = $tmpdir . '/scale_image_tmp_' . md5($image . microtime()); if (!phorum_api_write_file($tmpfile, $image)) { return NULL; } // Get the image information and clean up the temporary file. $file_info = getimagesize($tmpfile); @unlink($tmpfile); if ($file_info === FALSE) { return phorum_api_error_set(PHORUM_ERRNO_ERROR, 'Running getimagesize() on the image data failed'); } // Add the image data to the return array. $img['cur_w'] = $img['new_w'] = $file_info[0]; $img['cur_h'] = $img['new_h'] = $file_info[1]; $img['cur_mime'] = $img['new_mime'] = $file_info['mime']; // We support only GIF, JPG and PNG images. if (substr($img['cur_mime'], 0, 6) == 'image/') { $type = substr($img['cur_mime'], 6); if ($type != 'jpeg' && $type != 'gif' && $type != 'png') { return phorum_api_error_set(PHORUM_ERRNO_ERROR, "Scaling image type \"{$img['cur_mime']}\" is not supported"); } } else { return phorum_api_error_set(PHORUM_ERRNO_ERROR, 'The file does not appear to be an image'); } // Check if scaling is required and if yes, what the new size should be. // First, determine width and height scale factors. $scale_w = NULL; $scale_h = NULL; // Need horizontal scaling? if ($max_w !== NULL && $max_w < $img['cur_w']) { $scale_w = $max_w / $img['cur_w']; } // Need vertical scaling? if ($max_h !== NULL && $max_h < $img['cur_h']) { $scale_h = $max_h / $img['cur_h']; } // No scaling needed, return. if ($scale_w === NULL && $scale_h === NULL) { return $img; } // The lowest scale factor wins. Compute the required image size. if ($scale_h === NULL || $scale_w !== NULL && $scale_w < $scale_h) { $img['new_w'] = $max_w; $img['new_h'] = floor($img['cur_h'] * $scale_w + 0.5); } else { $img['new_w'] = floor($img['cur_w'] * $scale_h + 0.5); $img['new_h'] = $max_h; } // ----------------------------------------------------------------- // Try to use the imagick library tools // ----------------------------------------------------------------- // First, try to load the imagick extension if it is not loaded yet. // This way we can make this work on systems where imagick is not built-in // or loaded from the PHP ini. if (($method === NULL || $method == 'imagick') && !extension_loaded('imagick')) { @dl('imagick.so'); } if (($method === NULL || $method == 'imagick') && extension_loaded('imagick') && class_exists('Imagick')) { $method = NULL; $imagick = new Imagick(); $imagick->readImageBlob($image); $imagick->thumbnailImage($img['new_w'], $img['new_h'], TRUE); $imagick->setFormat("jpg"); $img['image'] = $imagick->getimageblob(); $img['new_mime'] = 'image/' . $imagick->getFormat(); $img['method'] = 'imagick'; return $img; } // ----------------------------------------------------------------- // Try to use the GD library tools // ----------------------------------------------------------------- // First, try to load the GD extension if it is not loaded yet. // This way we can make this work on systems where gd is not built-in // or loaded from the PHP ini. if (($method === NULL || $method == 'gd') && !extension_loaded('gd')) { @dl('gd.so'); } if (($method === NULL || $method == 'gd') && extension_loaded('gd') && function_exists('gd_info')) { // We need gd_info() to check whether GD has the required // image support for the type of image that we are handling. $gd = gd_info(); // We need PNG support for the scaled down image. if (empty($gd['PNG Support'])) { $error = "GD: no PNG support available for creating thumbnail"; } elseif ($type == 'gif' && empty($gd['GIF Read Support']) || $type == 'jpeg' && empty($gd['JPG Support']) || $type == 'png' && empty($gd['PNG Support'])) { $error = "GD: no support available for image type \"{$type}\""; } else { // Create a GD image handler based on the image data. // imagecreatefromstring() spawns PHP warnings if the file cannot // be processed. We do not care to see that in the event logging, // so if event logging is loaded, we suspend it here. // Instead, we catch error output and try to mangle it into a // usable error message. if (defined('EVENT_LOGGING')) { phorum_mod_event_logging_suspend(); } ob_start(); $original = imagecreatefromstring($image); $error = ob_get_contents(); ob_end_clean(); $error = trim(preg_replace('!(^(?:\\w+:\\s*).*?:|in /.*$)!', '', trim($error))); if (defined('EVENT_LOGGING')) { phorum_mod_event_logging_resume(); } if (!$original) { if ($error == '') { $error = "GD: Cannot process the {$type} image using GD"; } else { $error = 'GD: ' . $error; } } else { // Create the scaled image. $scaled = imagecreatetruecolor($img['new_w'], $img['new_h']); //Retain transparency. $trans_idx = imagecolortransparent($original); if ($trans_idx >= 0) { $trans = imagecolorsforindex($original, $trans_idx); $idx = imagecolorallocate($scaled, $trans['red'], $trans['green'], $trans['blue']); imagefill($scaled, 0, 0, $idx); imagecolortransparent($scaled, $idx); } elseif ($type == 'png') { imagealphablending($scaled, FALSE); $trans = imagecolorallocatealpha($scaled, 0, 0, 0, 127); imagefill($scaled, 0, 0, $trans); imagesavealpha($scaled, TRUE); } // Scale the image. imagecopyresampled($scaled, $original, 0, 0, 0, 0, $img['new_w'], $img['new_h'], $img['cur_w'], $img['cur_h']); // Create the jpeg output data for the scaled image. ob_start(); imagejpeg($scaled); $image = ob_get_contents(); $size = ob_get_length(); ob_end_clean(); $img['image'] = $image; $img['new_mime'] = 'image/jpeg'; $img['method'] = 'gd'; return $img; } } } // ----------------------------------------------------------------- // Try to use the ImageMagick "convert" tool // ----------------------------------------------------------------- if ($method === NULL || $method == 'convert') { // Try to find the "convert" utility. // First, check if it is configured in the Phorum settings. $convert = NULL; if (isset($PHORUM['imagemagick_convert_path'])) { $path = $PHORUM['imagemagick_convert_path']; if (is_executable($path)) { $convert = $path; } } // Not found? Then simply use "convert" and hope that it // can be found in the OS' path. if ($convert === NULL) { $convert = 'convert'; } // Build the command line. $cmd = escapeshellcmd($convert) . ' ' . '- ' . '-thumbnail ' . $img['new_w'] . 'x' . $img['new_h'] . ' ' . '-write jpeg:- ' . '--'; // Otherwise I get: option requires an argument `-write' // Run the command. $descriptors = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')); $process = proc_open($cmd, $descriptors, $pipes); if ($process == FALSE) { $error = 'Failed to run "convert".'; } // Feed convert the image data on STDIN. fwrite($pipes[0], $image); fclose($pipes[0]); // Read the scaled image from STDOUT. $scaled = stream_get_contents($pipes[1]); fclose($pipes[1]); // Read errors. $errors = trim(stream_get_contents($pipes[2])); fclose($pipes[2]); $exit = proc_close($process); if ($exit == 0) { $img['image'] = $scaled; $img['new_mime'] = 'image/jpeg'; $img['method'] = 'convert'; return $img; } // Some error occurred. if ($errors == '') { $error = 'Got exit code ' . $exit . ' from "convert".'; } else { $error = $errors; } } // ----------------------------------------------------------------- // Safety nets. // ----------------------------------------------------------------- // Return error if one was set. if ($error) { return phorum_api_error_set(PHORUM_ERRNO_ERROR, $error); } // Catch illegal methods if ($method !== NULL) { return phorum_api_error_set(PHORUM_ERRNO_ERROR, 'Illegal scaling method: ' . $method); } // If we get here, then we were totally out of luck. return phorum_api_error_set(PHORUM_ERRNO_ERROR, 'No working image scaling method found'); }
$numberOfPoints = 250; $points = array(); $colorPalette = array(); for ($i = 0; $i < $numberOfPoints; $i++) { $points[] = array('x' => rand(0, $width - 1), 'y' => rand(0, $height - 1)); $colorPalette[] = array('r' => rand(0, 255), 'g' => rand(0, 255), 'b' => rand(0, 255)); } apc_store('test.points', $points, 0); apc_store('test.palette', $colorPalette, 0); $taskId = 1; $pending = array(); $unsolved = array(); for ($i = 0; $i < $height; $i += $rowsPerTask) { for ($j = 0; $j < $width; $j += $columnsPerTask) { $unsolved[] = array('taskId' => $taskId, 'x' => $j, 'y' => $i, 'columns' => min($columnsPerTask, $width - $j), 'rows' => min($rowsPerTask, $height - $i)); $taskId += 1; } } shuffle($unsolved); apc_store('test.pending', $pending, 0); apc_store('test.unsolved', $unsolved, 0); $filename = 'test.bmp'; $imagesFolderName = 'images'; $image = new Imagick(); $image->newImage($width, $height, new ImagickPixel('black')); $image->setImageFormat('bmp'); $image->writeImage(sprintf('%s/%s', $imagesFolderName, $filename)); $image->setFormat('jpg'); $image->writeImage('images/test.jpg'); echo 'gotov'; var_dump($taskId);