function multiply($firstPicture, $twoPicture, $x, $y) { $img = new Imagick($firstPicture); $img->thumbnailImage(140, 140); $shadow = $img->clone(); $shadow->setImageBackgroundColor(new ImagickPixel('black')); //color shadow $shadow->shadowImage(80, 3, 5, 5); //create shadow $shadow->compositeImage($img, Imagick::COMPOSITE_OVER, 0, 0); header("Content-Type: image/jpeg"); $img2 = new Imagick($twoPicture); $img2->compositeImage($shadow, $shadow->getImageCompose(), $x, $y); echo $img2; }
/** * (non-PHPdoc) * @see Imagine\ImageInterface::copy() */ public function copy() { try { $clone = $this->imagick->clone(); } catch (\ImagickException $e) { throw new RuntimeException('Copy operation failed', $e->getCode(), $e); } return new self($clone); }
/** * {@inheritdoc} */ public function copy() { try { if (version_compare(phpversion("imagick"), "3.1.0b1", ">=")) { $clone = clone $this->imagick; } else { $clone = $this->imagick->clone(); } } catch (\ImagickException $e) { throw new RuntimeException('Copy operation failed', $e->getCode(), $e); } return new self($clone); }
/** * Applies the image effect on an Imagick object. This function should be overridden by the effect. * @param \Imagick The image object to work with * @return \Imagick The new image object to use */ protected final function executeFilterImagick(\Imagick $imageData) { $shadow = $imageData->clone(); $shadow->setImageBackgroundColor(new \ImagickPixel('black')); $shadow->shadowImage(80, $this->shadowWidth / 4, 0, 0); $shadow->compositeImage($imageData, \Imagick::COMPOSITE_OVER, 0, 0); return $shadow; }
public function browseDirectory($directory) { $input = "/"; if (!empty($directory)) { $input = rtrim($directory, '/') . '/'; $input = str_replace('../', '', $input); //We don't want to go any level up in directory hierarchy } $dir = new DirectoryIterator($this->baseDir . $input); $directories = array(); $files = array(); $thumbnails = array(); if ($input != "/") { $inputParts = explode("/", rtrim($input, '/')); array_pop($inputParts); $directories['..'] = implode("/", $inputParts); } foreach ($dir as $file) { if (substr($file->getFileName(), 0, 1) != '.') { //We don't want to list hidden files if ($file->isDir()) { $directories[$file->getFileName()] = $input . $file->getFileName(); } else { $files[$file->getFileName()] = $this->urlPrefix . $input . $file->getFileName(); if (class_exists('Imagick')) { //We are good to create thumbnails to cache try { $thumbFileName = md5($input . $file->getFileName()) . '.png'; if (!file_exists($this->cacheDir . '/' . $thumbFileName)) { //No such thumbnail in cache $im = new Imagick($file->getPathName()); $thumb = $im->clone(); if ($thumb->getImageHeight() > $thumb->getImageWidth()) { //preserve aspect ratio $thumb->thumbnailImage(0, 150); } else { $thumb->thumbnailImage(150, 0); } $thumb->setImageFormat('png'); $thumb->writeImage($this->cacheDir . '/' . $thumbFileName); } $thumbnails[$file->getFileName()] = $this->cacheUrlPrefix . '/' . $thumbFileName; } catch (ImagickException $ex) { $fileName = $file->getFileName(); $fileNameParts = explode(".", $fileName); $extension = array_pop($fileNameParts); if (file_exists($this->layoutDir . '/' . $extension . '.png')) { $thumbnails[$file->getFileName()] = $this->layoutUrlPrefix . '/' . $extension . '.png'; } else { $thumbnails[$file->getFileName()] = $this->layoutUrlPrefix . '/unknown.png'; } } } } } } return array('files' => $files, 'directories' => $directories, 'thumbnails' => $thumbnails); }
function submit_photo() { $dir = "../images"; $pid = intval(get_http_var('pid')); $errors = array(); if (!array_key_exists('photo', $_FILES)) array_push($errors, 'Not got the photo.'); elseif ($_FILES['photo']['error'] > 0) array_push($errors, 'There was an error uploading the photo.'); elseif (!is_uploaded_file($_FILES['photo']['tmp_name'])) array_push($errors, 'Did not get an uploaded file.'); else { $tmp_name = $_FILES['photo']['tmp_name']; $image = new Imagick(); $image->readImage($tmp_name); if (!$image) array_push($errors, 'Failed to read image from uploaded file'); $imageS = $image->clone(); if (!$image->scaleImage(0, 118)) array_push($errors, 'Scaling large failed'); if (!$imageS->scaleImage(0, 59)) array_push($errors, 'Scaling small failed'); if (!$image->writeImage("$dir/mpsL/$pid.jpeg")) array_push($errors, "Saving to $dir/mpsL/$pid.jpeg failed"); if (!$imageS->writeImage("$dir/mps/$pid.jpeg")) array_push($errors, "Saving to $dir/mps/$pid.jpeg failed"); if (!$errors) { print "<pre>"; chdir($dir); passthru('git pull'); passthru("git add mpsL/$pid.jpeg"); passthru("git add mps/$pid.jpeg"); passthru('git commit -m "Photo update from admin web photo upload interface."'); passthru('git push'); print "</pre>"; } } if ($errors) return display_form($errors); return "<p><em>Photo uploaded and resized for pid $pid</em> — check how it looks <a href=\"/mp?p=$pid\">on their page</a></p>" . display_form(); }
/** * Reflection. * @param integer $height * @param integer $opacity * @param boolean $fade_in */ protected function _reflection($height, $opacity, $fade_in) { $reflection = $this->im->clone(); $reflection->flipImage(); $reflection->cropImage($this->width, $height, 0, 0); $reflection->setImagePage($this->width, $height, 0, 0); $direction = array('transparent', 'black'); if ($fade_in) { $direction = array_reverse($direction); } $fade = new \Imagick(); $fade->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight(), vsprintf('gradient:%s-%s', $direction)); $reflection->compositeImage($fade, \Imagick::COMPOSITE_DSTOUT, 0, 0); $reflection->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity / 100, \Imagick::CHANNEL_ALPHA); $image = new \Imagick(); $image->newImage($this->width, $this->height + $height, new \ImagickPixel()); $image->setImageAlphaChannel(\Imagick::ALPHACHANNEL_SET); $image->setColorspace($this->im->getColorspace()); if ($image->compositeImage($this->im, \Imagick::COMPOSITE_SRC, 0, 0) && $image->compositeImage($reflection, \Imagick::COMPOSITE_OVER, 0, $this->height)) { $this->im = $image; $this->width = $this->im->getImageWidth(); $this->height = $this->im->getImageHeight(); } }
function placeImage(&$canvas, $o) { if (!file_exists($o['path'])) { return; } try { if ($o['padding'] > 0) { $o['x'] += $o['padding']; $o['y'] += $o['padding']; $o['w'] -= $o['padding']*2; $o['h'] -= $o['padding']*2; } $img = new Imagick(); $img->readImage(realpath($o['path'])); $img->resizeImage($o['w'], $o['h'], imagick::FILTER_TRIANGLE, 1, true); $actual_w = $img->getImageWidth( ); $actual_h = $img->getImageHeight( ); /* center image horizontally */ if ($actual_w < $o['w']) { $o['x'] += ($o['w'] - $actual_w) / 2; } /* and vertically */ if ($actual_h < $o['h']) { $o['y'] += ($o['h'] - $actual_h) / 2; } /* add drop shadow */ if ($o['shadow'] > 0){ $shadow = $img->clone(); $shadow->setImageBackgroundColor('black'); $shadow->shadowImage(75, 2, $o['shadow'], $o['shadow']); // last 2 args currently do nothing $canvas->compositeImage($shadow, imagick::COMPOSITE_OVER, $o['x'], $o['y']); } $canvas->compositeImage($img, imagick::COMPOSITE_OVER, $o['x'], $o['y']); } catch (Exception $e) { echo 'Error: ', $e->getMessage(), ""; } }
/** * * @return bool */ public function reflectionEffect() { $source = $this->_getTempEditorFullPath(); $im = new Imagick($source[0]); /* Thumbnail the image */ $im->thumbnailImage(200, null); /* Create a border for the image */ $im->borderImage(new ImagickPixel("white"), 1, 1); /* Clone the image and flip it */ $reflection = $im->clone(); $reflection->flipImage(); /* Create gradient. It will be overlayd on the reflection */ $gradient = new Imagick(); /* Gradient needs to be large enough for the image and the borders */ $gradient->newPseudoImage($reflection->getImageWidth() + 5, round($reflection->getImageHeight() / 2), "gradient:transparent-white"); /* Composite the gradient on the reflection */ $reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0); /* Add some opacity. Requires ImageMagick 6.2.9 or later */ $reflection->setImageOpacity(0.2); /* Create an empty canvas */ $canvas = new Imagick(); /* Canvas needs to be large enough to hold the both images */ $width = $im->getImageWidth() + 40; $height = $im->getImageHeight() * 1.5 + 10; $canvas->newImage($width, $height, new ImagickPixel("white")); $canvas->setImageFormat("png"); /* Composite the original image and the reflection on the canvas */ $canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10); $canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10); $canvas->writeImage($source[1]); $this->getRawEditorCache(); return true; }
$selected = array_search(max($weights), $weights); foreach ($weights as $i => $value) { if ($i != $selected && $value >= $weights[$selected]) { return -1; } } return $selected; } $imagePath = './images/0.png'; //$imagePath = './images/1.jpg'; $formulario = new \Imagick(realpath($imagePath)); foreach ($regions as $region => $question) { $weights = [-1]; for ($i = 0; $i < count($question['options']); $i++) { list($width, $height, $x, $y) = $question['options'][$i]; $box = $formulario->clone(); $box->cropImage($width, $height, $x, $y); $weights[] = weight($box); } // TODO: controlar pesos por si hai respostas en branco echo "Opción seleccionada: " . selected($weights) . PHP_EOL; } //$square->blackThresholdImage('grey'); //$square->contrastImage(true); // //$similarity = null; //$bestMatch = null; //$comparison = $imagick2->subImageMatch($square, $bestMatch, $similarity); /* $similarity->setImageFormat('png'); $similarity->writeImage('images/similarity.png');*/
function trample_text_layer($draw, $text_width, $text_height) { $im = new Imagick(); $im->newImage($text_width, $text_height, 'none', 'png'); $im->drawImage($draw); $noise_layer = $im->clone(); $noise_layer->addNoiseImage(imagick::NOISE_POISSON); $im->compositeImage($noise_layer, imagick::COMPOSITE_DSTIN, 0, 0); $im->waveImage(0.3, 30); $im->chopImage(0, 2, 0, 0); $width = $im->getImageWidth(); $height = $im->getImageHeight(); for ($begin = 0; $begin < $width; $begin += $width / 3) { $begin = floor($begin); $portion = $im->getImageRegion(floor($width / 3) - 1, $height, $begin, 0); $portion->swirlImage(15); $im->compositeImage($portion, imagick::COMPOSITE_REPLACE, $begin, 0); } $im->blurImage(0.5, 0.1); return $im; }
echo ' <figcaption>' . $image . '</figcaption>'; echo '</div>'; if ($width > $height) { $sqwidth = $height; } else { if ($width < $height) { $sqwidth = $width; } } $resource->cropThumbnailImage($sqwidth, $sqwidth); $resource->writeImage('photos/sq-' . $image); echo '<div>'; echo ' <figure>'; echo ' <img src="photos/sq-' . $image . '">'; echo ' </figure>'; echo ' <figcaption>sq-' . $image . '</figcaption>'; echo '</div>'; $imagesizes = array(500, 300, 150, 50); foreach ($imagesizes as $imagesize) { $clone = $resource->clone(); $clone->scaleImage($imagesize, $imagesize); $clone->writeImage('photos/sq' . $imagesize . '-' . $image); echo '<div>'; echo ' <figure>'; echo ' <img src="photos/sq' . $imagesize . '-' . $image . '">'; echo ' </figure>'; echo ' <figcaption>sq' . $imagesize . '-' . $image . '</figcaption>'; echo '</div>'; } $resource->clear(); }
function create_thumbnail($filename, $save2disk = true, $resize_type = 0) { $filename = $this->basename($filename); if ($this->is_image($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $filename) == true) { $extension = $this->file_extension($filename); $thumbnail = $this->thumbnail_name($filename); if ($save2disk == true) { // Seemed easier to build the image resize upload // option into the already established thumbnail function // instead of waisting time trying to chop it up for new one. if ($resize_type > 0 && $resize_type <= 8) { $thumbnail = $filename; $this->mmhclass->info->config['advanced_thumbnails'] = false; $size_values = array(1 => array("w" => 100, "h" => 75), 2 => array("w" => 150, "h" => 112), 3 => array("w" => 320, "h" => 240), 4 => array("w" => 640, "h" => 480), 5 => array("w" => 800, "h" => 600), 6 => array("w" => 1024, "h" => 768), 7 => array("w" => 1280, "h" => 1024), 8 => array("w" => 1600, "h" => 1200)); $thumbnail_size = $size_values[$resize_type]; } else { $thumbnail_size = $this->scale($filename, $this->mmhclass->info->config['thumbnail_width'], $this->mmhclass->info->config['thumbnail_height']); } if ($this->manipulator == "imagick") { // New Design of Advanced Thumbnails created by: IcyTexx - http://www.hostili.com // Classic Design of Advanced Thumbnails created by: Mihalism Technologies - http://www.mihalism.net $canvas = new Imagick(); $athumbnail = new Imagick(); $imagick_version = $canvas->getVersion(); // Imagick needs to start giving real version number, not build number. $new_thumbnails = version_compare($imagick_version['versionNumber'], "1621", ">=") == true ? true : false; $athumbnail->readImage("{$this->mmhclass->info->root_path}{$this->mmhclass->info->config['upload_path']}{$filename}[0]"); $athumbnail->flattenImages(); $athumbnail->orgImageHeight = $athumbnail->getImageHeight(); $athumbnail->orgImageWidth = $athumbnail->getImageWidth(); $athumbnail->orgImageSize = $athumbnail->getImageLength(); $athumbnail->thumbnailImage($thumbnail_size['w'], $thumbnail_size['h']); if ($this->mmhclass->info->config['advanced_thumbnails'] == true) { $thumbnail_filesize = $this->format_filesize($athumbnail->orgImageSize, true); $resobar_filesize = $thumbnail_filesize['f'] < 0 || $thumbnail_filesize['c'] > 9 ? $this->mmhclass->lang['5454'] : sprintf("%s%s", round($thumbnail_filesize['f']), $this->mmhclass->lang['7071'][$thumbnail_filesize['c']]); if ($new_thumbnails == true) { $textdraw = new ImagickDraw(); $textdrawborder = new ImagickDraw(); if ($athumbnail->getImageWidth() > 113) { $textdraw->setFillColor(new ImagickPixel("white")); $textdraw->setFontSize(9); $textdraw->setFont("{$mmhclass->info->root_path}css/fonts/sf_fedora_titles.ttf"); $textdraw->setFontWeight(900); $textdraw->setGravity(8); $textdraw->setTextKerning(1); $textdraw->setTextAntialias(false); $textdrawborder->setFillColor(new ImagickPixel("black")); $textdrawborder->setFontSize(9); $textdrawborder->setFont("{$mmhclass->info->root_path}css/fonts/sf_fedora_titles.ttf"); $textdrawborder->setFontWeight(900); $textdrawborder->setGravity(8); $textdrawborder->setTextKerning(1); $textdrawborder->setTextAntialias(false); $array_x = array("-1", "0", "1", "1", "1", "0", "-1", "-1"); $array_y = array("-1", "-1", "-1", "0", "1", "1", "1", "0"); foreach ($array_x as $key => $value) { $athumbnail->annotateImage($textdrawborder, $value, 3 - $array_y[$key], 0, "{$athumbnail->orgImageWidth}x{$athumbnail->orgImageHeight} - {$resobar_filesize}"); } $athumbnail->annotateImage($textdraw, 0, 3, 0, "{}x{$athumbnail->orgImageHeight} - {$resobar_filesize}"); } } else { $transback = new Imagick(); $canvasdraw = new ImagickDraw(); $canvas->newImage($athumbnail->getImageWidth(), $athumbnail->getImageHeight() + 12, new ImagickPixel("black")); $transback->newImage($canvas->getImageWidth(), $canvas->getImageHeight() - 12, new ImagickPixel("white")); $canvas->compositeImage($transback, 40, 0, 0); $canvasdraw->setFillColor(new ImagickPixel("white")); $canvasdraw->setGravity(8); $canvasdraw->setFontSize(10); $canvasdraw->setFontWeight(900); $canvasdraw->setFont("AvantGarde-Demi"); $canvas->annotateImage($canvasdraw, 0, 0, 0, "{$athumbnail->orgImageWidth}x{$athumbnail->orgImageHeight} - {$resobar_filesize}"); $canvas->compositeImage($athumbnail, 40, 0, 0); $athumbnail = $canvas->clone(); } } if ($this->mmhclass->info->config['thumbnail_type'] == "jpeg") { $athumbnail->setImageFormat("jpeg"); $athumbnail->setImageCompression(9); } else { $athumbnail->setImageFormat("png"); } $athumbnail->writeImage($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail); } else { // I hate GD. Piece of crap supports nothing. NOTHING! if (in_array($extension, array("png", "gif", "jpg", "jpeg")) == true) { $function_extension = str_replace("jpg", "jpeg", $extension); $image_function = "imagecreatefrom{$function_extension}"; $image = $image_function($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $filename); $imageinfo = $this->get_image_info($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $this->basename($filename)); $thumbnail_image = imagecreatetruecolor($thumbnail_size['w'], $thumbnail_size['h']); $index = imagecolortransparent($thumbnail_image); if ($index < 0) { $white = imagecolorallocate($thumbnail_image, 255, 255, 255); imagefill($thumbnail_image, 0, 0, $white); } imagecopyresampled($thumbnail_image, $image, 0, 0, 0, 0, $thumbnail_size['w'], $thumbnail_size['h'], $imageinfo['width'], $imageinfo['height']); $image_savefunction = sprintf("image%s", $this->mmhclass->info->config['thumbnail_type'] == "jpeg" ? "jpeg" : "png"); $image_savefunction($thumbnail_image, $this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail); chmod($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail, 0644); imagedestroy($image); imagedestroy($thumbnail_image); } else { trigger_error("Image format not supported by GD", E_USER_ERROR); } } chmod($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail, 0644); } else { readfile($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail); } } }
<?php header('Content-type: image/jpeg'); $image = "ega.png"; $directory = "images/"; $imageLocation = $directory . $image; $thumbDestination = $directory . "/t" . $image; $compression_type = Imagick::COMPRESSION_UNDEFINED; $im = new Imagick("images/ega.png"); //$im->thumbnailImage(245,170); $thumbImage = $im->clone(); $thumbImage->setImageCompression($compression_type); $thumbImage->setImageCompressionQuality(10); $thumbImage->stripImage(); $thumbImage->thumbnailImage(100, null); $thumbImage->writeImage($imageLocation); echo $thumbImage;
/** * 填充指定图像,内部使用 * @param \Imagick $newimg * @param $posx * @param $posy * @param $neww * @param $newh * @param null $img * @return mixed */ private function _fill($newimg, $posx, $posy, $neww, $newh, $img = NULL) { is_null($img) && ($img = $this->img); /* 将指定图片绘入空白图片 */ $draw = new \ImagickDraw(); $draw->composite($img->getImageCompose(), $posx, $posy, $neww, $newh, $img); /** * @var \Imagick $image */ $image = $newimg->clone(); $image->drawImage($draw); $draw->destroy(); return $image; }
/** * Applies the image effect on an Imagick object. This function should be overridden by the effect. * @param \Imagick The image object to work with * @return \Imagick The new image object to use */ protected final function executeFilterImagick(\Imagick $imageData) { $width = $imageData->getImageWidth(); $height = $imageData->getImageHeight(); if ($this->reflectionHeight > $height) { $this->reflectionHeight = $height; } if (empty($this->reflectionBackgroundColor)) { $this->reflectionBackgroundColor = 'transparent'; } /** @var \Imagick */ $reflection = $imageData->clone(); $reflection->flipImage(); $gradient = new \Imagick(); $gradient->newPseudoImage($reflection->getImageWidth(), $this->reflectionHeight, 'gradient:transparent-white'); $reflection->compositeImage($gradient, \Imagick::COMPOSITE_OVER, 0, 0); $reflection->setImageOpacity(1); $canvas = new \Imagick(); $newHeight = $height + $this->reflectionHeight + $this->gradientDistance; $canvas->newImage($width, $newHeight, $this->reflectionBackgroundColor, 'png'); $canvas->compositeImage($imageData, \Imagick::COMPOSITE_OVER, 0, 0); $canvas->compositeImage($reflection, \Imagick::COMPOSITE_OVER, 0, $height + $this->gradientDistance); return $canvas; }
/** * Sets the destination path. * @param sfFilebasePluginImage $destination */ public function setDestination(sfFilebasePluginImage $destination) { $this->destination = $destination; $this->destination_resource = $this->source_resource->clone(); }
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)); } }
/** * 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; }
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")) { // Native cloning was added to pecl-imagick in svn commit 263814 // the first version containing it was 3.0.1RC1 static $imagickClonable = null; if ($imagickClonable === null) { $imagickClonable = version_compare(phpversion('imagick'), '3.0.1rc1') > 0; } $imagick = new Imagick($file); $imagick->setFormat('png'); // Get opacity channel (negative of alpha channel) $alpha_channel = $imagickClonable ? clone $imagick : $imagick->clone(); $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); }
public function polaroidEffect($src, $color, $angle = 0) { if (15 != abs($angle)) { $srcs = [$src, $src, $src, $src]; $bg = new \ImagickDraw(); $images = new \Imagick($srcs); $format = $images->getImageFormat(); $maxwidth = 0; $maxheight = 0; foreach ($images as $key => $im) { $im->setImageFormat("png"); $im->setImageBackgroundColor(new \ImagickPixel("black")); $angle = mt_rand(-20, 20); if ($angle == 0) { $angle = -1; } $im->polaroidImage($bg, $angle); $info = $im->getImageGeometry(); $maxwidth = max($maxwidth, $info["width"]); $maxheight = max($maxheight, $info["height"]); } $image = new \Imagick(); $image->newImage($maxwidth, $maxheight, new \ImagickPixel($color)); foreach ($images as $key => $im) { $image->compositeImage($im, $im->getImageCompose(), 0, 0); } $image->setImageFormat($format); $bg->destroy(); $images->destroy(); } else { $image = new \Imagick($src); $format = $image->getImageFormat(); $image->frameImage(new \ImagickPixel("white"), 6, 6, 0, 0); $image->frameImage(new \ImagickPixel("gray"), 1, 1, 0, 0); $image->setImageFormat("png"); $shadow = $image->clone(); $shadow->setImageBackgroundColor(new \ImagickPixel("black")); $shadow->shadowImage(50, 3, 0, 0); $shadow->compositeImage($image, $image->getImageCompose(), 0, 0); $shadow->rotateImage(new \ImagickPixel($color), $angle); $info = $shadow->getImageGeometry(); $image->destroy(); $image = new \Imagick(); $image->newImage($info["width"], $info["height"], new \ImagickPixel($color)); $image->compositeImage($shadow, $shadow->getImageCompose(), 0, 0); $image->setImageFormat($format); $shadow->destroy(); } $this->_handle = $image; }
<?php require_once 'Imagick.php'; die; /* Read the image */ $im = new Imagick("sample.jpg"); /* Thumbnail the image */ $im->thumbnailImage(200, null); /* Create a border for the image */ $im->borderImage(new ImagickPixel("white"), 5, 5); /* Clone the image and flip it */ $reflection = $im->clone(); $reflection->flipImage(); /* Create gradient. It will be overlayed on the reflection */ $gradient = new Imagick(); /* Gradient needs to be large enough for the image and the borders */ $gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black"); /* Composite the gradient on the reflection */ $reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0); /* Add some opacity. Requires ImageMagick 6.2.9 or later */ $reflection->setImageOpacity(0.3); /* Create an empty canvas */ $canvas = new Imagick(); /* Canvas needs to be large enough to hold the both images */ $width = $im->getImageWidth() + 40; $height = $im->getImageHeight() * 2 + 30; $canvas->newImage($width, $height, new ImagickPixel("black")); $canvas->setImageFormat("png"); /* Composite the original image and the reflection on the canvas */ $canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10); $canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);
/** * Create and store a thumbnail of a given Imagick image object * * @author Scott Blake * @param Imagick $image * @param array $options * @param string $savePath * @return bool **/ private static function createThumbnail($originalFile, $filename, $options, $assetsID, $combined = FALSE) { if ($originalFile instanceof Imagick) { $image = $originalFile; } else { $image = new Imagick(); $image->readImage($originalFile); } $assetsDirectory = $combined != FALSE ? "combine" : 'thumbs'; $thumbname = ($combined != FALSE ? "thumb" : $filename) . '.' . strtolower($options['thumbnailFormat']); $savePath = self::getSaveDir($assetsID, $assetsDirectory) . $thumbname; // Make a copy of the original $thumb = $image->clone(); // Set the Width if (isset($options['thumbnailWidth'])) { $width = $options['thumbnailWidth']; } else { $width = 0; } // Set the Height if (isset($options['thumbnailHeight'])) { $height = $options['thumbnailHeight']; } else { $height = 0; } // Change the format if (isset($options['thumbnailFormat'])) { $thumb->setImageFormat($options['thumbnailFormat']); } // Scale to thumbnail size, constraining proportions if ($width > 0 || $height > 0) { $thumb->thumbnailImage($width, $height, TRUE); } // Store thumbnail, returns TRUE on success, FALSE on failure if ($thumb->writeImage($savePath) === FALSE) { return FALSE; } return array('name' => $thumbname, 'path' => self::getSaveDir($assetsID, $assetsDirectory, FALSE), 'size' => filesize($savePath), 'type' => self::getMimeType($savePath), 'errors' => ''); }
function renderKernel(ImagickKernel $imagickKernel) { $matrix = $imagickKernel->getMatrix(); $imageMargin = 20; $tileSize = 20; $tileSpace = 4; $shadowSigma = 4; $shadowDropX = 20; $shadowDropY = 0; $radius = $tileSize / 2 * 0.9; $rows = count($matrix); $columns = count($matrix[0]); $imagickDraw = new \ImagickDraw(); $imagickDraw->setFillColor('#afafaf'); $imagickDraw->setStrokeColor('none'); $imagickDraw->translate($imageMargin, $imageMargin); $imagickDraw->push(); ksort($matrix); foreach ($matrix as $row) { ksort($row); $imagickDraw->push(); foreach ($row as $cell) { if ($cell !== false) { $color = intval(255 * $cell); $colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color); $imagickDraw->setFillColor($colorString); $imagickDraw->rectangle(0, 0, $tileSize, $tileSize); } $imagickDraw->translate($tileSize + $tileSpace, 0); } $imagickDraw->pop(); $imagickDraw->translate(0, $tileSize + $tileSpace); } $imagickDraw->pop(); $width = $columns * $tileSize + ($columns - 1) * $tileSpace; $height = $rows * $tileSize + ($rows - 1) * $tileSpace; $imagickDraw->push(); $imagickDraw->translate($width / 2, $height / 2); $imagickDraw->setFillColor('rgba(0, 0, 0, 0)'); $imagickDraw->setStrokeColor('white'); $imagickDraw->circle(0, 0, $radius - 1, 0); $imagickDraw->setStrokeColor('black'); $imagickDraw->circle(0, 0, $radius, 0); $imagickDraw->pop(); $canvasWidth = $width + 2 * $imageMargin; $canvasHeight = $height + 2 * $imageMargin; $kernel = new \Imagick(); $kernel->newPseudoImage($canvasWidth, $canvasHeight, 'canvas:none'); $kernel->setImageFormat('png'); $kernel->drawImage($imagickDraw); /* create drop shadow on it's own layer */ $canvas = $kernel->clone(); $canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)')); $canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY); $canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5); $canvas->cropImage($canvasWidth, $canvasHeight, 0, 0); /* composite original text_layer onto shadow_layer */ $canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0); $canvas->setImageFormat('png'); return $canvas; }
error($uploaded_file . " missing"); } $i = new Imagick($uploaded_file); if ($paintcolor && !in_array($requested_image, $images_ignore)) { if ($paintcolor == 1) { $paintcolor = 12073019; } if ($requested_image == "paintcan.png") { $p = new Imagick($settings['upload']['folder'][$dir] . 'paintcan_paintcolor.png'); } else { $p = new Imagick($settings['upload']['folder'][$dir] . 'paint_splatter.png'); } //$p = new Imagick($settings['upload']['folder'][$dir].'paintcan_paintcolor.png'); //$p->colorizeImage ('#'.dechex($paintcolor),.5); //$c = $p->clone();//new Imagick(); $m = $p->clone(); $c = new Imagick(); $c->newImage(500, 500, '#' . dechex($paintcolor)); //$c->setImageAlphaChannel(imagick::ALPHACHANNEL_ACTIVATE); $c->compositeImage($m, imagick::COMPOSITE_COPYOPACITY, 0, 0); $p->compositeImage($c, imagick::COMPOSITE_MULTIPLY, 0, 0); $i->compositeImage($p, imagick::COMPOSITE_DEFAULT, 0, 0); //$i = $p; //die("!!".$target_file); } $geo = $i->getImageGeometry(); // crop the image if ($geo['width'] / $width < $geo['height'] / $height) { $i->cropImage($geo['width'], floor($height * $geo['width'] / $width), 0, ($geo['height'] - $height * $geo['width'] / $width) / 2); } else { $i->cropImage(ceil($width * $geo['height'] / $height), $geo['height'], ($geo['width'] - $width * $geo['height'] / $height) / 2, 0);
/** * Extract info from a PNG image with alpha channel using the GD library. * @param string $file Name of the file containing the image. * @param float $x Abscissa of the upper-left corner. * @param float $y Ordinate of the upper-left corner. * @param float $wpx Original width of the image in pixels. * @param float $hpx original height of the image in pixels. * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated. * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension. * @param mixed $link URL or identifier returned by AddLink(). * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library). * @param int $dpi dot-per-inch resolution used on resize * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul> * @author Nicola Asuni * @access protected * @since 4.3.007 (2008-12-04) * @see Image() */ protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign) { // create temp image file (without alpha channel) $tempfile_plain = tempnam(K_PATH_CACHE, 'mskp_'); // create temp alpha file $tempfile_alpha = tempnam(K_PATH_CACHE, 'mska_'); if (extension_loaded('imagick')) { // ImageMagick // ImageMagick library $img = new Imagick(); $img->readImage($file); // clone image object $imga = $img->clone(); // extract alpha channel $img->separateImageChannel(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE); $img->negateImage(true); $img->setImageFormat('png'); $img->writeImage($tempfile_alpha); // remove alpha channel $imga->separateImageChannel(imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE)); $imga->setImageFormat('png'); $imga->writeImage($tempfile_plain); } else { // GD library // generate images $img = imagecreatefrompng($file); $imgalpha = imagecreate($wpx, $hpx); // generate gray scale palette (0 -> 255) for ($c = 0; $c < 256; ++$c) { ImageColorAllocate($imgalpha, $c, $c, $c); } // extract alpha channel for ($xpx = 0; $xpx < $wpx; ++$xpx) { for ($ypx = 0; $ypx < $hpx; ++$ypx) { $color = imagecolorat($img, $xpx, $ypx); $alpha = $color >> 24; // shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha) $alpha = (127 - $alpha) / 127 * 255; // GD alpha is only 7 bit (0 -> 127) $alpha = $this->getGDgamma($alpha); // correct gamma imagesetpixel($imgalpha, $xpx, $ypx, $alpha); } } imagepng($imgalpha, $tempfile_alpha); imagedestroy($imgalpha); // extract image without alpha channel $imgplain = imagecreatetruecolor($wpx, $hpx); imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx); imagepng($imgplain, $tempfile_plain); imagedestroy($imgplain); } // embed mask image $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false); // embed image, masked with previously embedded mask $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask); // remove temp files unlink($tempfile_alpha); unlink($tempfile_plain); }
$draw->setStrokeColor(new ImagickPixel($tracks[$k][$i]['color'])); if ($tracks[$k][$i]['stroke'] == 'dot') { $draw->setStrokeDashArray(array(2, 3)); } else { $draw->setStrokeWidth(2); } for ($j = 1; $j < count($tracks[$k][$i]['data']); $j++) { $draw->line($tracks[$k][$i]['data'][$j - 1][0], $tracks[$k][$i]['data'][$j - 1][1], $tracks[$k][$i]['data'][$j][0], $tracks[$k][$i]['data'][$j][1]); } $canvas->drawImage($draw); } } foreach ($features as $k => $v) { $img = new Imagick($iconSysPath . $k . '.png'); for ($i = 0; $i < count($features[$k]); $i++) { $cloneImg = $img->clone(); // don't rotate for now // $cloneImg->rotateImage(new ImagickPixel('none'),$features[$k][$i][2]); $dim = $cloneImg->getImageGeometry(); $canvas->compositeImage($cloneImg, imagick::COMPOSITE_OVER, $features[$k][$i][0] - $dim['width'] / 2, $features[$k][$i][1] - $dim['height'] / 2); } } $canvas->writeImage($tmp_dir . $id . '.print.png'); $legTr = array(); $images = array(); for ($i = 0; $i < count($legends); $i++) { // create local copies of all images preg_match('/src="(.*)"/', $legends[$i], $matches); if (count($matches) > 0) { $handle = fopen($tmp_dir . $id . '.legend.' . $i . '.png', 'w'); fwrite($handle, @file_get_contents('http://localhost' . str_replace(' ', '%20', $matches[1])));