本文整理匯總了PHP中Imagick::setImageAlphaChannel方法的典型用法代碼示例。如果您正苦於以下問題:PHP Imagick::setImageAlphaChannel方法的具體用法?PHP Imagick::setImageAlphaChannel怎麽用?PHP Imagick::setImageAlphaChannel使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Imagick
的用法示例。
在下文中一共展示了Imagick::setImageAlphaChannel方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。
示例1: refresh
/**
* @param Thumbnail $thumbnail
* @return void
* @throws Exception\NoThumbnailAvailableException
*/
public function refresh(Thumbnail $thumbnail)
{
try {
$filenameWithoutExtension = pathinfo($thumbnail->getOriginalAsset()->getResource()->getFilename(), PATHINFO_FILENAME);
$temporaryLocalCopyFilename = $thumbnail->getOriginalAsset()->getResource()->createTemporaryLocalCopy();
$documentFile = sprintf(in_array($thumbnail->getOriginalAsset()->getResource()->getFileExtension(), $this->getOption('paginableDocuments')) ? '%s[0]' : '%s', $temporaryLocalCopyFilename);
$width = $thumbnail->getConfigurationValue('width') ?: $thumbnail->getConfigurationValue('maximumWidth');
$height = $thumbnail->getConfigurationValue('height') ?: $thumbnail->getConfigurationValue('maximumHeight');
$im = new \Imagick();
$im->setResolution($this->getOption('resolution'), $this->getOption('resolution'));
$im->readImage($documentFile);
$im->setImageFormat('png');
$im->setImageBackgroundColor('white');
$im->setImageCompose(\Imagick::COMPOSITE_OVER);
$im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_RESET);
$im->thumbnailImage($width, $height, true);
$im->flattenImages();
// Replace flattenImages in imagick 3.3.0
// @see https://pecl.php.net/package/imagick/3.3.0RC2
// $im->mergeImageLayers(\Imagick::LAYERMETHOD_MERGE);
$resource = $this->resourceManager->importResourceFromContent($im->getImageBlob(), $filenameWithoutExtension . '.png');
$im->destroy();
$thumbnail->setResource($resource);
$thumbnail->setWidth($width);
$thumbnail->setHeight($height);
} catch (\Exception $exception) {
$filename = $thumbnail->getOriginalAsset()->getResource()->getFilename();
$sha1 = $thumbnail->getOriginalAsset()->getResource()->getSha1();
$message = sprintf('Unable to generate thumbnail for the given document (filename: %s, SHA1: %s)', $filename, $sha1);
throw new Exception\NoThumbnailAvailableException($message, 1433109652, $exception);
}
}
示例2: removeAlpha
/**
* @param null|string $backgroundColor
*
* @throws ProcessorException
*
* @returns $this
*/
public function removeAlpha($backgroundColor = null)
{
$backgroundColor = $backgroundColor === null ? 'white' : $backgroundColor;
try {
$this->im->setBackgroundColor($backgroundColor);
$this->im->setImageAlphaChannel($this->getLibraryConstant('ALPHACHANNEL_REMOVE', null, 11));
} catch (\Exception $e) {
throw new ProcessorException('Could not remove alpha channel: %s', null, $e, (string) $e->getMessage());
}
return $this;
}
示例3: __construct
/**
* @param string $file
*
* @throws \ManaPHP\Image\Adapter\Exception
*/
public function __construct($file)
{
if (!extension_loaded('imagick')) {
throw new ImagickException('Imagick is not installed, or the extension is not loaded');
}
$this->_file = realpath($this->alias->resolve($file));
if (!$this->_file) {
throw new ImagickException('`:file` file is not exists', ['file' => $file]);
}
$this->_image = new \Imagick();
if (!$this->_image->readImage($this->_file)) {
throw new ImagickException('Imagick::readImage `:file` failed', ['file' => $file]);
}
if ($this->_image->getNumberImages() !== 1) {
throw new ImagickException('not support multiple iterations: `:file`', ['file' => $file]);
}
if (!$this->_image->getImageAlphaChannel()) {
$this->_image->setImageAlphaChannel(\Imagick::ALPHACHANNEL_SET);
}
$this->_width = $this->_image->getImageWidth();
$this->_height = $this->_image->getImageHeight();
}
示例4: resize
/**
* Resize image to a given size. Use only to shrink an image.
* If an image is smaller than specified size it will be not resized.
*
* @param int $size Max width/height size
* @param string $filename Output filename
* @param boolean $browser_compat Convert to image type displayable by any browser
*
* @return mixed Output type on success, False on failure
*/
public function resize($size, $filename = null, $browser_compat = false)
{
$result = false;
$rcube = rcube::get_instance();
$convert = $rcube->config->get('im_convert_path', false);
$props = $this->props();
if (empty($props)) {
return false;
}
if (!$filename) {
$filename = $this->image_file;
}
// use Imagemagick
if ($convert || class_exists('Imagick', false)) {
$p['out'] = $filename;
$p['in'] = $this->image_file;
$type = $props['type'];
if (!$type && ($data = $this->identify())) {
$type = $data[0];
}
$type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
$p['intype'] = $type;
// convert to an image format every browser can display
if ($browser_compat && !in_array($type, array('jpg', 'gif', 'png'))) {
$type = 'jpg';
}
// If only one dimension is greater than the limit convert doesn't
// work as expected, we need to calculate new dimensions
$scale = $size / max($props['width'], $props['height']);
// if file is smaller than the limit, we do nothing
// but copy original file to destination file
if ($scale >= 1 && $p['intype'] == $type) {
$result = $this->image_file == $filename || copy($this->image_file, $filename) ? '' : false;
} else {
$valid_types = "bmp,eps,gif,jp2,jpg,png,svg,tif";
if (in_array($type, explode(',', $valid_types))) {
// Valid type?
if ($scale >= 1) {
$width = $props['width'];
$height = $props['height'];
} else {
$width = intval($props['width'] * $scale);
$height = intval($props['height'] * $scale);
}
// use ImageMagick in command line
if ($convert) {
$p += array('type' => $type, 'quality' => 75, 'size' => $width . 'x' . $height);
$result = rcube::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace sRGB -strip' . ' -quality {quality} -resize {size} {intype}:{in} {type}:{out}', $p);
} else {
try {
$image = new Imagick($this->image_file);
try {
// it throws exception on formats not supporting these features
$image->setImageBackgroundColor('white');
$image->setImageAlphaChannel(11);
$image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
} catch (Exception $e) {
// ignore errors
}
$image->setImageColorspace(Imagick::COLORSPACE_SRGB);
$image->setImageCompressionQuality(75);
$image->setImageFormat($type);
$image->stripImage();
$image->scaleImage($width, $height);
if ($image->writeImage($filename)) {
$result = '';
}
} catch (Exception $e) {
rcube::raise_error($e, true, false);
}
}
}
}
if ($result === '') {
@chmod($filename, 0600);
return $type;
}
}
// do we have enough memory? (#1489937)
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' && !$this->mem_check($props)) {
return false;
}
// use GD extension
if ($props['gd_type']) {
if ($props['gd_type'] == IMAGETYPE_JPEG && function_exists('imagecreatefromjpeg')) {
$image = imagecreatefromjpeg($this->image_file);
$type = 'jpg';
} else {
if ($props['gd_type'] == IMAGETYPE_GIF && function_exists('imagecreatefromgif')) {
$image = imagecreatefromgif($this->image_file);
//.........這裏部分代碼省略.........
示例5: ewww_image_optimizer
//.........這裏部分代碼省略.........
if ($convert) {
ewwwio_debug_message("attempting to convert PNG to JPG: {$jpgfile}");
if (empty($new_size)) {
$new_size = $orig_size;
}
$magick_background = ewww_image_optimizer_jpg_background();
if (empty($magick_background)) {
$magick_background = '000000';
}
// convert the PNG to a JPG with all the proper options
if (ewww_image_optimizer_gmagick_support()) {
try {
if (ewww_image_optimizer_png_alpha($file)) {
$gmagick_overlay = new Gmagick($file);
$gmagick = new Gmagick();
$gmagick->newimage($gmagick_overlay->getimagewidth(), $gmagick_overlay->getimageheight(), '#' . $magick_background);
$gmagick->compositeimage($gmagick_overlay, 1, 0, 0);
} else {
$gmagick = new Gmagick($file);
}
$gmagick->setimageformat('JPG');
$gmagick->setcompressionquality($gquality);
$gmagick->writeimage($jpgfile);
} catch (Exception $gmagick_error) {
ewwwio_debug_message($gmagick_error->getMessage());
}
$jpg_size = ewww_image_optimizer_filesize($jpgfile);
}
if (!$jpg_size && ewww_image_optimizer_imagick_support()) {
try {
$imagick = new Imagick($file);
if (ewww_image_optimizer_png_alpha($file)) {
$imagick->setImageBackgroundColor(new ImagickPixel('#' . $magick_background));
$imagick->setImageAlphaChannel(11);
}
$imagick->setImageFormat('JPG');
$imagick->setCompressionQuality($gquality);
$imagick->writeImage($jpgfile);
} catch (Exception $imagick_error) {
ewwwio_debug_message($imagick_error->getMessage());
}
$jpg_size = ewww_image_optimizer_filesize($jpgfile);
}
if (!$jpg_size) {
// retrieve version info for ImageMagick
$convert_path = ewww_image_optimizer_find_nix_binary('convert', 'i');
if (!empty($convert_path)) {
ewwwio_debug_message('converting with ImageMagick');
ewwwio_debug_message("using command: {$convert_path} {$background} -alpha remove {$cquality} {$file} {$jpgfile}");
exec("{$convert_path} {$background} -alpha remove {$cquality} " . ewww_image_optimizer_escapeshellarg($file) . " " . ewww_image_optimizer_escapeshellarg($jpgfile));
$jpg_size = ewww_image_optimizer_filesize($jpgfile);
}
}
if (!$jpg_size && ewww_image_optimizer_gd_support()) {
ewwwio_debug_message('converting with GD');
// retrieve the data from the PNG
$input = imagecreatefrompng($file);
// retrieve the dimensions of the PNG
list($width, $height) = getimagesize($file);
// create a new image with those dimensions
$output = imagecreatetruecolor($width, $height);
if ($r === '') {
$r = 255;
$g = 255;
$b = 255;
}
示例6: _background
/**
* Fill the image background.
* @param integer $r
* @param integer $g
* @param integer $b
* @param integer $opacity
*/
protected function _background($r, $g, $b, $opacity)
{
$background = new \Imagick();
$background->newImage($this->width, $this->height, new \ImagickPixel(sprintf('rgb(%d, %d, %d)', $r, $g, $b)));
if (!$background->getImageAlphaChannel()) {
$background->setImageAlphaChannel(\Imagick::ALPHACHANNEL_SET);
}
$background->setImageBackgroundColor(new \ImagickPixel('transparent'));
$background->evaluateImage(\Imagick::EVALUATE_MULTIPLY, $opacity / 100, \Imagick::CHANNEL_ALPHA);
$background->setColorspace($this->im->getColorspace());
if ($background->compositeImage($this->im, \Imagick::COMPOSITE_DISSOLVE, 0, 0)) {
$this->im = $background;
}
}
示例7: _do_reflection
protected function _do_reflection($height, $opacity, $fade_in)
{
// Clone the current image and flip it for reflection
$reflection = $this->im->clone();
$reflection->flipImage();
// Crop the reflection to the selected height
$reflection->cropImage($this->width, $height, 0, 0);
$reflection->setImagePage($this->width, $height, 0, 0);
// Select the fade direction
$direction = array('transparent', 'black');
if ($fade_in) {
// Change the direction of the fade
$direction = array_reverse($direction);
}
// Create a gradient for fading
$fade = new Imagick();
$fade->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight(), vsprintf('gradient:%s-%s', $direction));
// Apply the fade alpha channel to the reflection
$reflection->compositeImage($fade, Imagick::COMPOSITE_DSTOUT, 0, 0);
// NOTE: Using setImageOpacity will destroy alpha channels!
$reflection->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opacity / 100, Imagick::CHANNEL_ALPHA);
// Create a new container to hold the image and reflection
$image = new Imagick();
$image->newImage($this->width, $this->height + $height, new ImagickPixel());
// Force the image to have an alpha channel
$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET);
// Force the background color to be transparent
// $image->setImageBackgroundColor(new ImagickPixel('transparent'));
// Match the colorspace between the two images before compositing
$image->setColorspace($this->im->getColorspace());
// Place the image and reflection into the container
if ($image->compositeImage($this->im, Imagick::COMPOSITE_SRC, 0, 0) and $image->compositeImage($reflection, Imagick::COMPOSITE_OVER, 0, $this->height)) {
// Replace the current image with the reflected image
$this->im = $image;
// Reset the width and height
$this->width = $this->im->getImageWidth();
$this->height = $this->im->getImageHeight();
return TRUE;
}
return FALSE;
}
示例8: _mergeSingleImg
private function _mergeSingleImg($margedImagePath)
{
switch ($this->imageProcessLib) {
case 'gd':
$watermarkInfo = getimagesize($this->watermarkPath);
if ($watermarkInfo["mime"] == "image/png") {
$watermark = imagecreatefrompng($this->watermarkPath);
} else {
$watermark = imagecreatefromjpeg($this->watermarkPath);
}
$imageInfo = getimagesize($this->imagePath);
if ($imageInfo["mime"] == "image/png") {
$image = imagecreatefrompng($this->imagePath);
} else {
$image = imagecreatefromjpeg($this->imagePath);
}
imagesavealpha($image, true);
imagesavealpha($watermark, true);
imagealphablending($image, false);
imagealphablending($watermark, false);
if ($watermarkInfo[0] > $imageInfo[0] || $watermarkInfo[1] > $imageInfo[1]) {
$kWidth = $watermarkInfo[0] / $imageInfo[0];
$kHeight = $watermarkInfo[0] / $imageInfo[0];
if ($kWidth > $kHeight) {
// Масштабируем по ширине
$watermarkInfo[0] = $watermarkInfo[0] / $kWidth;
$watermarkInfo[1] = $watermarkInfo[1] / $kWidth;
} else {
// Масштабируем по высоте
$watermarkInfo[0] = $watermarkInfo[0] / $kHeight;
$watermarkInfo[1] = $watermarkInfo[1] / $kHeight;
}
imagecopyresampled($watermark, $watermark, 0, 0, 0, 0, $watermarkInfo[0], $watermarkInfo[1], imagesx($watermark), imagesy($watermark));
}
imagecopy($image, $watermark, $this->watermarkOfsetX, $this->watermarkOfsetY, 0, 0, $watermarkInfo[0], $watermarkInfo[1]);
if ($imageInfo["mime"] == "image/png") {
imagepng($image, $margedImagePath);
} else {
imagejpeg($image, $margedImagePath);
}
imagedestroy($image);
imagedestroy($watermark);
break;
case 'imagick':
$image = new Imagick();
$image->readImage($this->imagePath);
$watermark = new Imagick();
$watermark->readImage($this->watermarkPath);
if (!$watermark->getImageAlphaChannel()) {
$watermark->setImageAlphaChannel(1);
}
if ($watermark->getImageWidth() > $image->getImageWidth() || $watermark->getImageHeight() > $image->getImageHeight()) {
$kWidth = $watermark->getImageWidth() / $image->getImageWidth();
$kHeight = $watermark->getImageHeight() / $image->getImageHeight();
if ($kWidth > $kHeight) {
// Масштабируем по ширине
$watermark->scaleImage($watermark->getImageWidth() / $kWidth, $watermark->getImageHeight() / $kWidth);
} else {
// Масштабируем по высоте
$watermark->scaleImage($watermark->getImageWidth() / $kHeight, $watermark->getImageHeight() / $kHeight);
}
}
$watermark->evaluateImage(Imagick::EVALUATE_MULTIPLY, $this->watermarkTransparency, Imagick::CHANNEL_ALPHA);
$image->compositeImage($watermark, imagick::COMPOSITE_OVER, $this->watermarkOfsetX, $this->watermarkOfsetY);
$image->writeImage($margedImagePath);
break;
default:
echo json_encode(array('status' => 'error', 'errorId' => '1-6', 'errorText' => 'An invalid image processing library'), JSON_FORCE_OBJECT);
exit;
break;
}
return true;
}
示例9: createThumbnail
/**
* @desc Create a thumbnail of the picture and save it
* @param $size The size requested
*/
private function createThumbnail($width, $height = false, $format = 'jpeg')
{
if (!in_array($format, array_keys($this->_formats))) {
$format = 'jpeg';
}
if (!$height) {
$height = $width;
}
$path = $this->_path . md5($this->_key) . '_' . $width . $this->_formats[$format];
$im = new Imagick();
try {
$im->readImageBlob($this->_bin);
$im->setImageFormat($format);
if ($format == 'jpeg') {
$im->setImageCompression(Imagick::COMPRESSION_JPEG);
$im->setImageAlphaChannel(11);
// Put 11 as a value for now, see http://php.net/manual/en/imagick.flattenimages.php#116956
//$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->setImageBackgroundColor('#ffffff');
$im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
}
//$crop = new CropEntropy;
//$crop->setImage($im);
$geo = $im->getImageGeometry();
$im->cropThumbnailImage($width, $height);
if ($width > $geo['width']) {
$factor = floor($width / $geo['width']);
$im->blurImage($factor, 10);
}
//$im = $crop->resizeAndCrop($width, $height);
$im->setImageCompressionQuality(85);
$im->setInterlaceScheme(Imagick::INTERLACE_PLANE);
$im->writeImage($path);
$im->clear();
} catch (ImagickException $e) {
error_log($e->getMessage());
}
}
示例10: _background
protected function _background($r, $g, $b, $opacity)
{
$color = sprintf("rgb(%d, %d, %d)", $r, $g, $b);
$pixel1 = new \ImagickPixel($color);
$opacity = $opacity / 100;
$pixel2 = new \ImagickPixel("transparent");
$background = new \Imagick();
$this->_image->setIteratorIndex(0);
while (true) {
$background->newImage($this->_width, $this->_height, $pixel1);
if (!$background->getImageAlphaChannel()) {
$background->setImageAlphaChannel(constant("Imagick::ALPHACHANNEL_SET"));
}
$background->setImageBackgroundColor($pixel2);
$background->evaluateImage(constant("Imagick::EVALUATE_MULTIPLY"), $opacity, constant("Imagick::CHANNEL_ALPHA"));
$background->setColorspace($this->_image->getColorspace());
$background->compositeImage($this->_image, constant("Imagick::COMPOSITE_DISSOLVE"), 0, 0);
if (!$this->_image->nextImage()) {
break;
}
}
$this->_image->clear();
$this->_image->destroy();
$this->_image = $background;
}
示例11: min
echo 'Error: Format not supported. Supported format: dds, jpeg, png, bmp.';
exit;
}
/*if ($icon_width > 200 or $icon_height > 200)
{
echo 'Error: The size of your picture is too big. Should be under 200*200';
exit;
}*/
if ($icon_width < 150 or $icon_height < 150) {
echo 'Error: The size of your picture is too small. Should be above 150*150';
exit;
}
if ($icon_format != 'PNG') {
$icon->setImageFormat('png');
}
$icon->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
// Resizing
if ($icon_width != $icon_height) {
$min = min($icon_width, $icon_height);
$icon->resizeImage($min, $min, Imagick::FILTER_BOX, 1, true);
$icon_width = $icon->getImageWidth();
$icon_height = $icon->getImageHeight();
}
$wanted_size = 176;
$icon->resizeImage($wanted_size, $wanted_size, Imagick::FILTER_BOX, 1);
$iterator = $icon->getPixelIterator();
foreach ($iterator as $row => $pixels) {
foreach ($pixels as $col => $pixel) {
$color = $pixel->getColor();
// values are 0-255
$alpha = $pixel->getColor(true);
示例12: ImagickPixel
break;
}
$image->setImageFormat('jpeg');
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality($cq);
} else {
$image->setImageFormat('png');
$compress[] = $file;
}
if (isset($size[SPLASH_ROTATE])) {
$image->rotateImage(new ImagickPixel('none'), $size[SPLASH_ROTATE]);
}
$image->cropThumbnailImage($size[SPLASH_WIDTH], $size[SPLASH_HEIGHT]);
$image->setImageResolution($size[SPLASH_DPI], $size[SPLASH_DPI]);
$image->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$image->setImageAlphaChannel(11);
$image->writeImage($file);
}
}
if ($_POST['compression'] && count($compress) > 0) {
switch ($_POST['compression']) {
case 'low':
$o = 1;
break;
case 'medium':
$o = 2;
break;
case 'high':
$o = 3;
break;
}
示例13: online
function online($db)
{
$db->exec(<<<'EOS'
--
CREATE TABLE `document` (
id INTEGER PRIMARY KEY,
slug CHAR(128) NOT NULL UNIQUE,
titre CHAR(128) NOT NULL,
description TEXT NULL,
auteur CHAR(512) NULL,
suffixe CHAR(8),
date DATETIME
);
INSERT INTO document
(slug, titre, suffixe, date)
SELECT id, titre, suffixe, date
FROM documents
ORDER BY ROWID;
DROP TABLE documents;
CREATE TABLE `unite_document` (
id INTEGER PRIMARY KEY,
unite INTEGER NOT NULL REFERENCES unite(id),
document INTEGER NOT NULL REFERENCES document(id),
UNIQUE (unite, document)
);
INSERT INTO `unite_document`
(document, unite)
SELECT document.id, unite.id
FROM doc_unite
JOIN document ON document.slug = doc_unite.document
JOIN unite ON unite.slug = doc_unite.unite;
DROP TABLE doc_unite;
CREATE VIEW vdocuments AS
SELECT document.id, unite.slug, document.slug, document.suffixe
FROM document
JOIN unite_document ON unite_document.document = document.id
JOIN unite ON unite.id = unite_document.unite
ORDER BY document.date;
ALTER TABLE activite_document RENAME TO tmp;
CREATE TABLE `activite_document` (
id INTEGER PRIMARY KEY,
activite INTEGER NOT NULL REFERENCES activite(id),
document INTEGER NOT NULL REFERENCES document(id),
UNIQUE (activite, document)
);
INSERT INTO activite_document
(activite, document)
SELECT tmp.activite, document.id
FROM tmp
JOIN document ON document.slug = document;
DROP TABLE tmp;
CREATE VIEW vpiecesjointes AS
SELECT document.id, activite.slug, document.slug, document.suffixe
FROM document
JOIN activite_document ON activite_document.document = document.id
JOIN activite ON activite.id = activite_document.activite
ORDER BY activite.debut;
EOS
);
error_log("Génération des vignettes des documents");
$stmt = $db->query("SELECT * FROM document");
foreach ($stmt as $row) {
if ($row['suffixe'] != 'pdf') {
continue;
}
$document = 'data/documents/' . $row['slug'] . '.' . $row['suffixe'];
$vignette = 'data/documents/' . $row['slug'] . '-vignette.jpeg';
$im = new Imagick($document . '[0]');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_RESET);
$im->setImageFormat('jpg');
$im->setBackgroundColor('white');
$im->thumbnailImage(0, 256);
$im->writeImage($vignette);
}
}
示例14: thumbnail_image
/**
* Efficiently resize the current image
*
* This is a WordPress specific implementation of Imagick::thumbnailImage(),
* which resizes an image to given dimensions and removes any associated profiles.
*
* @since 4.5.0
* @access protected
*
* @param int $dst_w The destination width.
* @param int $dst_h The destination height.
* @param string $filter_name Optional. The Imagick filter to use when resizing. Default 'FILTER_TRIANGLE'.
* @param bool $strip_meta Optional. Strip all profiles, excluding color profiles, from the image. Default true.
* @return bool|WP_Error
*/
protected function thumbnail_image($dst_w, $dst_h, $filter_name = 'FILTER_TRIANGLE', $strip_meta = true)
{
$allowed_filters = array('FILTER_POINT', 'FILTER_BOX', 'FILTER_TRIANGLE', 'FILTER_HERMITE', 'FILTER_HANNING', 'FILTER_HAMMING', 'FILTER_BLACKMAN', 'FILTER_GAUSSIAN', 'FILTER_QUADRATIC', 'FILTER_CUBIC', 'FILTER_CATROM', 'FILTER_MITCHELL', 'FILTER_LANCZOS', 'FILTER_BESSEL', 'FILTER_SINC');
/**
* Set the filter value if '$filter_name' name is in our whitelist and the related
* Imagick constant is defined or fall back to our default filter.
*/
if (in_array($filter_name, $allowed_filters) && defined('Imagick::' . $filter_name)) {
$filter = constant('Imagick::' . $filter_name);
} else {
$filter = defined('Imagick::FILTER_TRIANGLE') ? Imagick::FILTER_TRIANGLE : false;
}
/**
* Filters whether to strip metadata from images when they're resized.
*
* This filter only applies when resizing using the Imagick editor since GD
* always strips profiles by default.
*
* @since 4.5.0
*
* @param bool $strip_meta Whether to strip image metadata during resizing. Default true.
*/
if (apply_filters('image_strip_meta', $strip_meta)) {
$this->strip_meta();
// Fail silently if not supported.
}
try {
/*
* To be more efficient, resample large images to 5x the destination size before resizing
* whenever the output size is less that 1/3 of the original image size (1/3^2 ~= .111),
* unless we would be resampling to a scale smaller than 128x128.
*/
if (is_callable(array($this->image, 'sampleImage'))) {
$resize_ratio = $dst_w / $this->size['width'] * ($dst_h / $this->size['height']);
$sample_factor = 5;
if ($resize_ratio < 0.111 && ($dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128)) {
$this->image->sampleImage($dst_w * $sample_factor, $dst_h * $sample_factor);
}
}
/*
* Use resizeImage() when it's available and a valid filter value is set.
* Otherwise, fall back to the scaleImage() method for resizing, which
* results in better image quality over resizeImage() with default filter
* settings and retains backward compatibility with pre 4.5 functionality.
*/
if (is_callable(array($this->image, 'resizeImage')) && $filter) {
$this->image->setOption('filter:support', '2.0');
$this->image->resizeImage($dst_w, $dst_h, $filter, 1);
} else {
$this->image->scaleImage($dst_w, $dst_h);
}
// Set appropriate quality settings after resizing.
if ('image/jpeg' == $this->mime_type) {
if (is_callable(array($this->image, 'unsharpMaskImage'))) {
$this->image->unsharpMaskImage(0.25, 0.25, 8, 0.065);
}
$this->image->setOption('jpeg:fancy-upsampling', 'off');
}
if ('image/png' === $this->mime_type) {
$this->image->setOption('png:compression-filter', '5');
$this->image->setOption('png:compression-level', '9');
$this->image->setOption('png:compression-strategy', '1');
$this->image->setOption('png:exclude-chunk', 'all');
}
/*
* If alpha channel is not defined, set it opaque.
*
* Note that Imagick::getImageAlphaChannel() is only available if Imagick
* has been compiled against ImageMagick version 6.4.0 or newer.
*/
if (is_callable(array($this->image, 'getImageAlphaChannel')) && is_callable(array($this->image, 'setImageAlphaChannel')) && defined('Imagick::ALPHACHANNEL_UNDEFINED') && defined('Imagick::ALPHACHANNEL_OPAQUE')) {
if ($this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED) {
$this->image->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);
}
}
// Limit the bit depth of resized images to 8 bits per channel.
if (is_callable(array($this->image, 'getImageDepth')) && is_callable(array($this->image, 'setImageDepth'))) {
if (8 < $this->image->getImageDepth()) {
$this->image->setImageDepth(8);
}
}
if (is_callable(array($this->image, 'setInterlaceScheme')) && defined('Imagick::INTERLACE_NO')) {
$this->image->setInterlaceScheme(Imagick::INTERLACE_NO);
}
} catch (Exception $e) {
//.........這裏部分代碼省略.........
示例15: array
/**
* Convert a transparent PNG to JPG, with specified background color
*
* @param string $id Attachment ID
* @param string $file File Path Original Image
* @param string $meta Attachment Meta
* @param string $size Image size. set to 'full' by default
*
* @return array Savings and Updated Meta
*/
function convert_tpng_to_jpg($id = '', $file = '', $meta = '', $size = 'full')
{
global $wpsmush_settings;
$result = array('meta' => $meta, 'savings' => '');
//Flag: Whether the image was converted or not
if ('full' == $size) {
$result['converted'] = false;
}
//If any of the values is not set
if (empty($id) || empty($file) || empty($meta)) {
return $result;
}
//Get the File name without ext
$n_file = pathinfo($file);
if (empty($n_file['dirname']) || empty($n_file['filename'])) {
return $result;
}
$n_file['filename'] = wp_unique_filename($n_file['dirname'], $n_file['filename'] . '.jpg');
//Updated File name
$n_file = path_join($n_file['dirname'], $n_file['filename']);
$transparent_png = $wpsmush_settings->get_setting(WP_SMUSH_PREFIX . 'transparent_png');
/**
* Filter Background Color for Transparent PNGs
*/
$bg = apply_filters('wp_smush_bg', $transparent_png['background'], $id, $size);
$quality = $this->get_quality($file);
if ($this->supports_imagick()) {
try {
$imagick = new Imagick($file);
$imagick->setImageBackgroundColor(new ImagickPixel('#' . $bg));
$imagick->setImageAlphaChannel(11);
$imagick->setImageFormat('JPG');
$imagick->setCompressionQuality($quality);
$imagick->writeImage($n_file);
} catch (Exception $e) {
error_log("WP Smush PNG to JPG Conversion error in " . __FILE__ . " at " . __LINE__ . " " . $e->getMessage());
return $result;
}
} else {
//Use GD for conversion
//Get data from PNG
$input = imagecreatefrompng($file);
//Width and Height of image
list($width, $height) = getimagesize($file);
//Create New image
$output = imagecreatetruecolor($width, $height);
// set background color for GD
$r = hexdec('0x' . strtoupper(substr($bg, 0, 2)));
$g = hexdec('0x' . strtoupper(substr($bg, 2, 2)));
$b = hexdec('0x' . strtoupper(substr($bg, 4, 2)));
//Set the Background color
$rgb = imagecolorallocate($output, $r, $g, $b);
//Fill Background
imagefilledrectangle($output, 0, 0, $width, $height, $rgb);
//Create New image
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
//Create JPG
imagejpeg($output, $n_file, $quality);
}
//Replace file, and get savings
$result = $this->replace_file($file, $result, $n_file);
if (!empty($result['savings'])) {
if ('full' == $size) {
$result['converted'] = true;
}
//Update the File Details. and get updated meta
$result['meta'] = $this->update_image_path($id, $file, $n_file, $meta, $size);
/**
* Perform a action after the image URL is updated in post content
*/
do_action('wp_smush_image_url_changed', $id, $file, $n_file, $size);
}
return $result;
}