public static function run($res, $width = NULL, $height = NULL) { $dst_w = Image::width($res); $dst_h = Image::height($res); if (!empty($width) && !empty($height)) { $dst_w = $width; $dst_h = $height; } elseif (empty($height)) { $ratio = $dst_h / $dst_w; $dst_w = $width; $dst_h = round($dst_w * $ratio); } elseif (empty($width)) { $ratio = $dst_w / $dst_h; $dst_h = $height; $dst_w = round($dst_h * $ratio); } $dst = imagecreatetruecolor($dst_w, $dst_h); /* making the new image transparent */ $background = imagecolorallocate($dst, 0, 0, 0); ImageColorTransparent($dst, $background); // make the new temp image all transparent imagealphablending($dst, false); imagesavealpha($dst, true); imageAntiAlias($dst, true); self::__fill($dst); imagecopyresampled($dst, $res, 0, 0, 0, 0, $dst_w, $dst_h, Image::width($res), Image::height($res)); @imagedestroy($res); return $dst; }
/** * Draws the pie chart, with optional supersampled anti-aliasing. * @param int $aa */ public function draw($aa = 4) { $this->canvas = imageCreateTrueColor($this->width, $this->height); // Set anti-aliasing for the pie chart. imageAntiAlias($this->canvas, true); imageFilledRectangle($this->canvas, 0, 0, $this->width, $this->height, $this->_convertColor($this->backgroundColor)); $total = 0; $sliceStart = -90; // Start at 12 o'clock. $titleHeight = $this->_drawTitle(); $legendWidth = $this->_drawLegend($titleHeight); // Account for the space occupied by the legend and its padding. $pieCentreX = ($this->width - $legendWidth) / 2; // Account for the space occupied by the title. $pieCentreY = $titleHeight + ($this->height - $titleHeight) / 2; // 10% padding on the top and bottom of the pie. $pieDiameter = round(min($this->width - $legendWidth, $this->height - $titleHeight) * 0.85); foreach ($this->slices as $slice) { $total += $slice['value']; } // If anti-aliasing is enabled, we supersample the pie to work around // the fact that GD does not provide anti-aliasing natively. if ($aa > 0) { $ssDiameter = $pieDiameter * $aa; $ssCentreX = $ssCentreY = $ssDiameter / 2; $superSample = imageCreateTrueColor($ssDiameter, $ssDiameter); imageFilledRectangle($superSample, 0, 0, $ssDiameter, $ssDiameter, $this->_convertColor($this->backgroundColor)); foreach ($this->slices as $slice) { $sliceWidth = 360 * $slice['value'] / $total; // Skip slices that are too small to draw / be visible. if ($sliceWidth == 0) { continue; } $sliceEnd = $sliceStart + $sliceWidth; imageFilledArc($superSample, $ssCentreX, $ssCentreY, $ssDiameter, $ssDiameter, $sliceStart, $sliceEnd, $this->_convertColor($slice['color']), IMG_ARC_PIE); // Move along to the next slice. $sliceStart = $sliceEnd; } imageCopyResampled($this->canvas, $superSample, $pieCentreX - $pieDiameter / 2, $pieCentreY - $pieDiameter / 2, 0, 0, $pieDiameter, $pieDiameter, $ssDiameter, $ssDiameter); imageDestroy($superSample); } else { // Draw the slices. foreach ($this->slices as $slice) { $sliceWidth = 360 * $slice['value'] / $total; // Skip slices that are too small to draw / be visible. if ($sliceWidth == 0) { continue; } $sliceEnd = $sliceStart + $sliceWidth; imageFilledArc($this->canvas, $pieCentreX, $pieCentreY, $pieDiameter, $pieDiameter, $sliceStart, $sliceEnd, $this->_convertColor($slice['color']), IMG_ARC_PIE); // Move along to the next slice. $sliceStart = $sliceEnd; } } }
public function createThumbs($thumb_size) { $thumb = imageCreateTrueColor($thumb_size['width'], $thumb_size['height']); if ($thumb === false) { throw new Exception('cannot create img_thumb file'); } $resX = floor(imagesx($this->_orig_img) * ($thumb_size['height'] / imagesy($this->_orig_img))); $resY = $thumb_size['height']; imageAntiAlias($thumb, true); imagecopyresized($thumb, $this->_orig_img, 0, 0, 0, 0, $resX, $resY, imagesx($this->_orig_img), imagesy($this->_orig_img)); if (!imageJPEG($thumb, $this->_save_path . 'thumbs_' . $this->_new_img_name, 100)) { imagedestroy($thumb); throw new Exception('cannot save img_thumbs file'); } imagedestroy($thumb); return $this; }
/** * Crée si possible une miniature d'une image * * @see _image_valeurs_trans() * @uses _image_ratio() * * @param array $valeurs * Description de l'image, telle que retournée par `_image_valeurs_trans()` * @param int $maxWidth * Largeur maximum en px de la miniature à réaliser * @param int $maxHeight * Hauteur maximum en px de la miniateure à réaliser * @param string $process * Librairie graphique à utiliser (gd1, gd2, netpbm, convert, imagick). * AUTO utilise la librairie sélectionnée dans la configuration. * @param bool $force * @return array|null * Description de l'image, sinon null. **/ function _image_creer_vignette($valeurs, $maxWidth, $maxHeight, $process = 'AUTO', $force = false) { // ordre de preference des formats graphiques pour creer les vignettes // le premier format disponible, selon la methode demandee, est utilise $image = $valeurs['fichier']; $format = $valeurs['format_source']; $destdir = dirname($valeurs['fichier_dest']); $destfile = basename($valeurs['fichier_dest'], "." . $valeurs["format_dest"]); $format_sortie = $valeurs['format_dest']; if ($process == 'AUTO' and isset($GLOBALS['meta']['image_process'])) { $process = $GLOBALS['meta']['image_process']; } // liste des formats qu'on sait lire $img = isset($GLOBALS['meta']['formats_graphiques']) ? strpos($GLOBALS['meta']['formats_graphiques'], $format) !== false : false; // si le doc n'est pas une image, refuser if (!$force and !$img) { return; } $destination = "{$destdir}/{$destfile}"; // calculer la taille if (($srcWidth = $valeurs['largeur']) && ($srcHeight = $valeurs['hauteur'])) { if (!($destWidth = $valeurs['largeur_dest']) || !($destHeight = $valeurs['hauteur_dest'])) { list($destWidth, $destHeight) = _image_ratio($valeurs['largeur'], $valeurs['hauteur'], $maxWidth, $maxHeight); } } elseif ($process == 'convert' or $process == 'imagick') { $destWidth = $maxWidth; $destHeight = $maxHeight; } else { spip_log("echec {$process} sur {$image}"); return; } // Si l'image est de la taille demandee (ou plus petite), simplement la retourner if ($srcWidth and $srcWidth <= $maxWidth and $srcHeight <= $maxHeight) { $vignette = $destination . '.' . $format; @copy($image, $vignette); } elseif ($process == 'convert') { if (!defined('_CONVERT_COMMAND')) { define('_CONVERT_COMMAND', 'convert'); } // Securite : mes_options.php peut preciser le chemin absolu define('_RESIZE_COMMAND', _CONVERT_COMMAND . ' -quality ' . _IMG_CONVERT_QUALITE . ' -resize %xx%y! %src %dest'); $vignette = $destination . "." . $format_sortie; $commande = str_replace(array('%x', '%y', '%src', '%dest'), array($destWidth, $destHeight, escapeshellcmd($image), escapeshellcmd($vignette)), _RESIZE_COMMAND); spip_log($commande); exec($commande); if (!@file_exists($vignette)) { spip_log("echec convert sur {$vignette}"); return; // echec commande } } elseif ($process == 'imagick') { $vignette = "{$destination}." . $format_sortie; if (!class_exists('Imagick')) { spip_log("Classe Imagick absente !", _LOG_ERREUR); return; } $imagick = new Imagick(); $imagick->readImage($image); $imagick->resizeImage($destWidth, $destHeight, Imagick::FILTER_LANCZOS, 1); //, IMAGICK_FILTER_LANCZOS, _IMG_IMAGICK_QUALITE / 100); $imagick->writeImage($vignette); if (!@file_exists($vignette)) { spip_log("echec imagick sur {$vignette}"); return; } } elseif ($process == "netpbm") { if (!defined('_PNMSCALE_COMMAND')) { define('_PNMSCALE_COMMAND', 'pnmscale'); } // Securite : mes_options.php peut preciser le chemin absolu if (_PNMSCALE_COMMAND == '') { return; } $vignette = $destination . "." . $format_sortie; $pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND); if ($format == "jpg") { $jpegtopnm_command = str_replace("pnmscale", "jpegtopnm", _PNMSCALE_COMMAND); exec("{$jpegtopnm_command} {$image} | " . _PNMSCALE_COMMAND . " -width {$destWidth} | {$pnmtojpeg_command} > {$vignette}"); if (!($s = @filesize($vignette))) { spip_unlink($vignette); } if (!@file_exists($vignette)) { spip_log("echec netpbm-jpg sur {$vignette}"); return; } } else { if ($format == "gif") { $giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND); exec("{$giftopnm_command} {$image} | " . _PNMSCALE_COMMAND . " -width {$destWidth} | {$pnmtojpeg_command} > {$vignette}"); if (!($s = @filesize($vignette))) { spip_unlink($vignette); } if (!@file_exists($vignette)) { spip_log("echec netpbm-gif sur {$vignette}"); return; } } else { if ($format == "png") { $pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND); exec("{$pngtopnm_command} {$image} | " . _PNMSCALE_COMMAND . " -width {$destWidth} | {$pnmtojpeg_command} > {$vignette}"); if (!($s = @filesize($vignette))) { spip_unlink($vignette); } if (!@file_exists($vignette)) { spip_log("echec netpbm-png sur {$vignette}"); return; } } } } } elseif ($process == 'gd1' or $process == 'gd2') { if (!function_exists('gd_info')) { spip_log("Librairie GD absente !", _LOG_ERREUR); return; } if (_IMG_GD_MAX_PIXELS && $srcWidth * $srcHeight > _IMG_GD_MAX_PIXELS) { spip_log("vignette gd1/gd2 impossible : " . $srcWidth * $srcHeight . "pixels"); return; } $destFormat = $format_sortie; if (!$destFormat) { spip_log("pas de format pour {$image}"); return; } $fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom']; if (!function_exists($fonction_imagecreatefrom)) { return ''; } $srcImage = @$fonction_imagecreatefrom($image); if (!$srcImage) { spip_log("echec gd1/gd2"); return; } // Initialisation de l'image destination $destImage = null; if ($process == 'gd2' and $destFormat != "gif") { $destImage = ImageCreateTrueColor($destWidth, $destHeight); } if (!$destImage) { $destImage = ImageCreate($destWidth, $destHeight); } // Recopie de l'image d'origine avec adaptation de la taille $ok = false; if ($process == 'gd2' and function_exists('ImageCopyResampled')) { if ($format == "gif") { // Si un GIF est transparent, // fabriquer un PNG transparent $transp = imagecolortransparent($srcImage); if ($transp > 0) { $destFormat = "png"; } } if ($destFormat == "png") { // Conserver la transparence if (function_exists("imageAntiAlias")) { imageAntiAlias($destImage, true); } @imagealphablending($destImage, false); @imagesavealpha($destImage, true); } $ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight); } if (!$ok) { $ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight); } // Sauvegarde de l'image destination $valeurs['fichier_dest'] = $vignette = "{$destination}.{$destFormat}"; $valeurs['format_dest'] = $format = $destFormat; _image_gd_output($destImage, $valeurs); if ($srcImage) { ImageDestroy($srcImage); } ImageDestroy($destImage); } $size = @getimagesize($vignette); // Gaffe: en safe mode, pas d'acces a la vignette, // donc risque de balancer "width='0'", ce qui masque l'image sous MSIE if ($size[0] < 1) { $size[0] = $destWidth; } if ($size[1] < 1) { $size[1] = $destHeight; } $retour['width'] = $largeur = $size[0]; $retour['height'] = $hauteur = $size[1]; $retour['fichier'] = $vignette; $retour['format'] = $format; $retour['date'] = @filemtime($vignette); // renvoyer l'image return $retour; }
function image_masque($im, $masque, $pos = "") { // Passer, en plus de l'image d'origine, // une image de "masque": un fichier PNG24 transparent. // Le decoupage se fera selon la transparence du "masque", // et les couleurs seront eclaircies/foncees selon de couleur du masque. // Pour ne pas modifier la couleur, le masque doit etre en gris 50%. // // Si l'image source est plus grande que le masque, alors cette image est reduite a la taille du masque. // Sinon, c'est la taille de l'image source qui est utilisee. // // $pos est une variable libre, qui permet de passer left=..., right=..., bottom=..., top=... // dans ce cas, le masque est place a ces positions sur l'image d'origine, // et evidemment cette image d'origine n'est pas redimensionnee // // Positionnement horizontal: text-align=left, right, center // Positionnement vertical : vertical-align=top, bottom, middle // (les positionnements left, right, top, left sont relativement inutiles, mais coherence avec CSS) // // Choix du mode de fusion: mode=masque, normal, eclaircir, obscurcir, produit, difference, ecran, superposer, lumiere_dure, teinte, saturation, valeur // https://en.wikipedia.org/wiki/Blend_modes // masque: mode par defaut // normal: place la nouvelle image par dessus l'ancienne // eclaircir: place uniquement les points plus clairs // obscurcir: place uniquement les points plus fonc'es // produit: multiplie par le masque (points noirs rendent l'image noire, points blancs ne changent rien) // difference: remplit avec l'ecart entre les couleurs d'origine et du masque // ecran: effet inverse de 'produit' -> l'image resultante est plus claire // superposer: combine les modes 'produit' et 'ecran' -> les parties claires sont eclaircies, les parties sombres assombries. // lumiere_dure: equivalent a 'superposer', sauf que l'image du bas et du haut sont inversees. // teinte: utilise la teinte du masque // saturation: utilise la saturation du masque // valeur: utilise la valeur du masque $mode = "masque"; $numargs = func_num_args(); $arg_list = func_get_args(); $variable = array(); $texte = $arg_list[0]; for ($i = 1; $i < $numargs; $i++) { if (($p = strpos($arg_list[$i], "=")) !== false) { $nom_variable = substr($arg_list[$i], 0, $p); $val_variable = substr($arg_list[$i], $p + 1); $variable["{$nom_variable}"] = $val_variable; $defini["{$nom_variable}"] = 1; } } if (isset($defini["mode"]) and $defini["mode"]) { $mode = $variable["mode"]; } // utiliser _image_valeurs_trans pour accepter comme masque : // - une balise <img src='...' /> // - une image avec un timestamp ?01234 $mask = _image_valeurs_trans($masque, "source-image_masque", "png", null, true); if (!$mask) { return ""; } $masque = $mask['fichier']; $pos = md5(serialize($variable) . $mask['date_src']); $fonction = array('image_masque', func_get_args()); $image = _image_valeurs_trans($im, "masque-{$masque}-{$pos}", "png", $fonction); if (!$image) { return ""; } $x_i = $image["largeur"]; $y_i = $image["hauteur"]; $im = $image["fichier"]; $dest = $image["fichier_dest"]; $creer = $image["creer"]; // doit-on positionner l'image ? $placer = false; foreach (array("right", "left", "bottom", "top", "text-align", "vertical-align") as $pl) { if (isset($defini[$pl]) and $defini[$pl]) { $placer = true; break; } } if ($creer) { $im_m = $mask["fichier"]; $x_m = $mask["largeur"]; $y_m = $mask["hauteur"]; $im2 = $mask["fonction_imagecreatefrom"]($masque); if ($mask["format_source"] == "gif" and function_exists('ImageCopyResampled')) { $im2_ = imagecreatetruecolor($x_m, $y_m); // Si un GIF est transparent, // fabriquer un PNG transparent // Conserver la transparence if (function_exists("imageAntiAlias")) { imageAntiAlias($im2_, true); } @imagealphablending($im2_, false); @imagesavealpha($im2_, true); @ImageCopyResampled($im2_, $im2, 0, 0, 0, 0, $x_m, $y_m, $x_m, $y_m); imagedestroy($im2); $im2 = $im2_; } if ($placer) { // On fabriquer une version "agrandie" du masque, // aux dimensions de l'image source // et on "installe" le masque dans cette image // ainsi: aucun redimensionnement $dx = 0; $dy = 0; if (isset($defini["right"]) and $defini["right"]) { $right = $variable["right"]; $dx = $x_i - $x_m - $right; } if (isset($defini["bottom"]) and $defini["bottom"]) { $bottom = $variable["bottom"]; $dy = $y_i - $y_m - $bottom; } if (isset($defini["top"]) and $defini["top"]) { $top = $variable["top"]; $dy = $top; } if (isset($defini["left"]) and $defini["left"]) { $left = $variable["left"]; $dx = $left; } if (isset($defini["text-align"]) and $defini["text-align"]) { $align = $variable["text-align"]; if ($align == "right") { $right = 0; $dx = $x_i - $x_m; } else { if ($align == "left") { $left = 0; $dx = 0; } else { if ($align = "center") { $dx = round(($x_i - $x_m) / 2); } } } } if (isset($defini["vertical-align"]) and $defini["vertical-align"]) { $valign = $variable["vertical-align"]; if ($valign == "bottom") { $bottom = 0; $dy = $y_i - $y_m; } else { if ($valign == "top") { $top = 0; $dy = 0; } else { if ($valign = "middle") { $dy = round(($y_i - $y_m) / 2); } } } } $im3 = imagecreatetruecolor($x_i, $y_i); @imagealphablending($im3, false); @imagesavealpha($im3, true); if ($mode == "masque") { $color_t = ImageColorAllocateAlpha($im3, 128, 128, 128, 0); } else { $color_t = ImageColorAllocateAlpha($im3, 128, 128, 128, 127); } imagefill($im3, 0, 0, $color_t); imagecopy($im3, $im2, $dx, $dy, 0, 0, $x_m, $y_m); imagedestroy($im2); $im2 = imagecreatetruecolor($x_i, $y_i); @imagealphablending($im2, false); @imagesavealpha($im2, true); imagecopy($im2, $im3, 0, 0, 0, 0, $x_i, $y_i); imagedestroy($im3); $x_m = $x_i; $y_m = $y_i; } $rapport = $x_i / $x_m; if ($y_i / $y_m < $rapport) { $rapport = $y_i / $y_m; } $x_d = ceil($x_i / $rapport); $y_d = ceil($y_i / $rapport); if ($x_i < $x_m or $y_i < $y_m) { $x_dest = $x_i; $y_dest = $y_i; $x_dec = 0; $y_dec = 0; } else { $x_dest = $x_m; $y_dest = $y_m; $x_dec = round(($x_d - $x_m) / 2); $y_dec = round(($y_d - $y_m) / 2); } $nouveau = _image_valeurs_trans(image_reduire($im, $x_d, $y_d), ""); if (!is_array($nouveau)) { return ""; } $im_n = $nouveau["fichier"]; $im = $nouveau["fonction_imagecreatefrom"]($im_n); imagepalettetotruecolor($im); if ($nouveau["format_source"] == "gif" and function_exists('ImageCopyResampled')) { $im_ = imagecreatetruecolor($x_dest, $y_dest); // Si un GIF est transparent, // fabriquer un PNG transparent // Conserver la transparence if (function_exists("imageAntiAlias")) { imageAntiAlias($im_, true); } @imagealphablending($im_, false); @imagesavealpha($im_, true); @ImageCopyResampled($im_, $im, 0, 0, 0, 0, $x_dest, $y_dest, $x_dest, $y_dest); imagedestroy($im); $im = $im_; } $im_ = imagecreatetruecolor($x_dest, $y_dest); @imagealphablending($im_, false); @imagesavealpha($im_, true); $color_t = ImageColorAllocateAlpha($im_, 255, 255, 255, 127); imagefill($im_, 0, 0, $color_t); // calcul couleurs de chaque pixel selon les modes de fusion for ($x = 0; $x < $x_dest; $x++) { for ($y = 0; $y < $y_dest; $y++) { $rgb = ImageColorAt($im2, $x, $y); // image au dessus $a = $rgb >> 24 & 0xff; $r = $rgb >> 16 & 0xff; $g = $rgb >> 8 & 0xff; $b = $rgb & 0xff; $rgb2 = ImageColorAt($im, $x + $x_dec, $y + $y_dec); // image en dessous $a2 = $rgb2 >> 24 & 0xff; $r2 = $rgb2 >> 16 & 0xff; $g2 = $rgb2 >> 8 & 0xff; $b2 = $rgb2 & 0xff; if ($mode == "normal") { $v = (127 - $a) / 127; if ($v == 1) { $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v + $v2 == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { if ($v2 == 0) { $r_ = $r; $g_ = $g; $b_ = $b; } else { if ($v == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { $r_ = $r + ($r2 - $r) * $v2 * (1 - $v); $g_ = $g + ($g2 - $g) * $v2 * (1 - $v); $b_ = $b + ($b2 - $b) * $v2 * (1 - $v); } } } } $a_ = min($a, $a2); } elseif (in_array($mode, array("produit", "difference", "superposer", "lumiere_dure", "ecran"))) { if ($mode == "produit") { $r = $r / 255 * $r2; $g = $g / 255 * $g2; $b = $b / 255 * $b2; } elseif ($mode == "difference") { $r = abs($r - $r2); $g = abs($g - $g2); $b = abs($b - $b2); } elseif ($mode == "superposer") { $r = $r2 < 128 ? 2 * $r * $r2 / 255 : 255 - 2 * (255 - $r) * (255 - $r2) / 255; $g = $g2 < 128 ? 2 * $g * $g2 / 255 : 255 - 2 * (255 - $g) * (255 - $g2) / 255; $b = $b2 < 128 ? 2 * $b * $b2 / 255 : 255 - 2 * (255 - $b) * (255 - $b2) / 255; } elseif ($mode == "lumiere_dure") { $r = $r < 128 ? 2 * $r * $r2 / 255 : 255 - 2 * (255 - $r2) * (255 - $r) / 255; $g = $g < 128 ? 2 * $g * $g2 / 255 : 255 - 2 * (255 - $g2) * (255 - $g) / 255; $b = $b < 128 ? 2 * $b * $b2 / 255 : 255 - 2 * (255 - $b2) * (255 - $b) / 255; } elseif ($mode == "ecran") { $r = 255 - (255 - $r) * (255 - $r2) / 255; $g = 255 - (255 - $g) * (255 - $g2) / 255; $b = 255 - (255 - $b) * (255 - $b2) / 255; } $r = max(0, min($r, 255)); $g = max(0, min($g, 255)); $b = max(0, min($b, 255)); // melange en fonction de la transparence du masque $v = (127 - $a) / 127; if ($v == 1) { // melange complet $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v + $v2 == 0) { // ?? $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { // pas de melange (transparence du masque) $r_ = $r + ($r2 - $r) * $v2 * (1 - $v); $g_ = $g + ($g2 - $g) * $v2 * (1 - $v); $b_ = $b + ($b2 - $b) * $v2 * (1 - $v); } } $a_ = $a2; } elseif ($mode == "eclaircir" or $mode == "obscurcir") { $v = (127 - $a) / 127; if ($v == 1) { $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v + $v2 == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { $r_ = $r + ($r2 - $r) * $v2 * (1 - $v); $g_ = $g + ($g2 - $g) * $v2 * (1 - $v); $b_ = $b + ($b2 - $b) * $v2 * (1 - $v); } } if ($mode == "eclaircir") { $r_ = max($r_, $r2); $g_ = max($g_, $g2); $b_ = max($b_, $b2); } else { $r_ = min($r_, $r2); $g_ = min($g_, $g2); $b_ = min($b_, $b2); } $a_ = min($a, $a2); } elseif (in_array($mode, array("teinte", "saturation", "valeur"))) { include_spip("filtres/images_lib"); $hsv = _couleur_rgb2hsv($r, $g, $b); // image au dessus $h = $hsv["h"]; $s = $hsv["s"]; $v = $hsv["v"]; $hsv2 = _couleur_rgb2hsv($r2, $g2, $b2); // image en dessous $h2 = $hsv2["h"]; $s2 = $hsv2["s"]; $v2 = $hsv2["v"]; switch ($mode) { case "teinte": $rgb3 = _couleur_hsv2rgb($h, $s2, $v2); break; case "saturation": $rgb3 = _couleur_hsv2rgb($h2, $s, $v2); break; case "valeur": $rgb3 = _couleur_hsv2rgb($h2, $s2, $v); break; } $r = $rgb3["r"]; $g = $rgb3["g"]; $b = $rgb3["b"]; // melange en fonction de la transparence du masque $v = (127 - $a) / 127; if ($v == 1) { // melange complet $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v + $v2 == 0) { // ?? $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { // pas de melange (transparence du masque) $r_ = $r + ($r2 - $r) * $v2 * (1 - $v); $g_ = $g + ($g2 - $g) * $v2 * (1 - $v); $b_ = $b + ($b2 - $b) * $v2 * (1 - $v); } } $a_ = $a2; } else { $r_ = $r2 + 1 * ($r - 127); $r_ = max(0, min($r_, 255)); $g_ = $g2 + 1 * ($g - 127); $g_ = max(0, min($g_, 255)); $b_ = $b2 + 1 * ($b - 127); $b_ = max(0, min($b_, 255)); $a_ = $a + $a2 - round($a * $a2 / 127); } $color = ImageColorAllocateAlpha($im_, $r_, $g_, $b_, $a_); imagesetpixel($im_, $x, $y, $color); } } _image_gd_output($im_, $image); imagedestroy($im_); imagedestroy($im); imagedestroy($im2); } $x_dest = largeur($dest); $y_dest = hauteur($dest); return _image_ecrire_tag($image, array('src' => $dest, 'width' => $x_dest, 'height' => $y_dest)); }
<?php /* Создание изображения */ // $i = imageCreate(500, 300); $i = imageCreateTrueColor(500, 300); /* Подготовка к работе */ imageAntiAlias($i, true); $red = imageColorAllocate($i, 255, 0, 0); $white = imageColorAllocate($i, 0xff, 0xff, 0xff); $black = imageColorAllocate($i, 0, 0, 0); $green = imageColorAllocate($i, 0, 255, 0); $blue = imageColorAllocate($i, 0, 0, 255); $grey = imageColorAllocate($i, 192, 192, 192); imageFill($i, 0, 0, $grey); /* Рисуем примитивы */ imageSetPixel($i, 10, 10, $black); imageLine($i, 20, 20, 280, 180, $red); imageRectangle($i, 20, 20, 280, 180, $blue); //array of dots $points = [120, 120, 100, 200, 300, 200]; imagePolygon($i, $points, 3, $green); imageEllipse($i, 200, 150, 300, 200, $red); // imageArc($i, 210, 160, 300, 200, 0, 90, $black); imageFilledArc($i, 200, 150, 300, 200, 0, 40, $red, IMG_ARC_PIE); /* Рисуем текст */ imageString($i, 5, 150, 200, 'php7', $black); imageCharUp($i, 3, 200, 200, 'PHP5', $blue); imageTtfText($i, 30, 10, 300, 150, $green, 'arial.ttf', 'PHP7'); /* Отдаем изображение */ // header("Content-type: image/gif"); // imageGif($i);
function image_masque($im, $masque, $pos="") { // Passer, en plus de l'image d'origine, // une image de "masque": un fichier PNG24 transparent. // Le decoupage se fera selon la transparence du "masque", // et les couleurs seront eclaircies/foncees selon de couleur du masque. // Pour ne pas modifier la couleur, le masque doit etre en gris 50%. // // Si l'image source est plus grande que le masque, alors cette image est reduite a la taille du masque. // Sinon, c'est la taille de l'image source qui est utilisee. // // $pos est une variable libre, qui permet de passer left=..., right=..., bottom=..., top=... // dans ce cas, le pasque est place a ces positions sur l'image d'origine, // et evidemment cette image d'origine n'est pas redimensionnee // // Positionnement horizontal: text-align=left, right, center // Positionnement vertical : vertical-align: top, bottom, middle // (les positionnements left, right, top, left sont relativement inutiles, mais coherence avec CSS) // // Choix du mode de fusion: mode=masque, normal, eclaircir, obscurcir, produit, difference // masque: mode par defaut // normal: place la nouvelle image par dessus l'ancienne // eclaircir: place uniquement les points plus clairs // obscurcir: place uniquement les points plus fonc'es // produit: multiplie par le masque (points noirs rendent l'image noire, points blancs ne changent rien) // difference: remplit avec l'ecart entre les couleurs d'origine et du masque $mode = "masque"; $numargs = func_num_args(); $arg_list = func_get_args(); $texte = $arg_list[0]; for ($i = 1; $i < $numargs; $i++) { if ( ($p = strpos($arg_list[$i],"=")) !==false) { $nom_variable = substr($arg_list[$i], 0, $p); $val_variable = substr($arg_list[$i], $p+1); $variable["$nom_variable"] = $val_variable; $defini["$nom_variable"] = 1; } } if ($defini["mode"]) $mode = $variable["mode"]; $masque = find_in_path($masque); $pos = md5(serialize($variable).@filemtime($masque)); $fonction = array('image_masque', func_get_args()); $image = _image_valeurs_trans($im, "masque-$masque-$pos", "png",$fonction); if (!$image) return(""); $x_i = $image["largeur"]; $y_i = $image["hauteur"]; $im = $image["fichier"]; $dest = $image["fichier_dest"]; $creer = $image["creer"]; if ($defini["right"] OR $defini["left"] OR $defini["bottom"] OR $defini["top"] OR $defini["text-align"] OR $defini["vertical-align"]) { $placer = true; } else $placer = false; if ($creer) { $mask = _image_valeurs_trans($masque,""); if (!is_array($mask)) return(""); $im_m = $mask["fichier"]; $x_m = $mask["largeur"]; $y_m = $mask["hauteur"]; $im2 = $mask["fonction_imagecreatefrom"]($masque); if ($mask["format_source"] == "gif" AND function_exists('ImageCopyResampled')) { $im2_ = imagecreatetruecolor($x_m, $y_m); // Si un GIF est transparent, // fabriquer un PNG transparent // Conserver la transparence if (function_exists("imageAntiAlias")) imageAntiAlias($im2_,true); @imagealphablending($im2_, false); @imagesavealpha($im2_,true); @ImageCopyResampled($im2_, $im2, 0, 0, 0, 0, $x_m, $y_m, $x_m, $y_m); imagedestroy($im2); $im2 = $im2_; } if ($placer) { // On fabriquer une version "agrandie" du masque, // aux dimensions de l'image source // et on "installe" le masque dans cette image // ainsi: aucun redimensionnement $dx = 0; $dy = 0; if ($defini["right"]) { $right = $variable["right"]; $dx = ($x_i - $x_m) - $right; } if ($defini["bottom"]) { $bottom = $variable["bottom"]; $dy = ($y_i - $y_m) - $bottom; } if ($defini["top"]) { $top = $variable["top"]; $dy = $top; } if ($defini["left"]) { $left = $variable["left"]; $dx = $left; } if ($defini["text-align"]) { $align = $variable["text-align"]; if ($align == "right") { $right = 0; $dx = ($x_i - $x_m); } else if ($align == "left") { $left = 0; $dx = 0; } else if ($align = "center") { $dx = round( ($x_i - $x_m) / 2 ) ; } } if ($defini["vertical-align"]) { $valign = $variable["vertical-align"]; if ($valign == "bottom") { $bottom = 0; $dy = ($y_i - $y_m); } else if ($valign == "top") { $top = 0; $dy = 0; } else if ($valign = "middle") { $dy = round( ($y_i - $y_m) / 2 ) ; } } $im3 = imagecreatetruecolor($x_i, $y_i); @imagealphablending($im3, false); @imagesavealpha($im3,true); if ($mode == "masque") $color_t = ImageColorAllocateAlpha( $im3, 128, 128, 128 , 0 ); else $color_t = ImageColorAllocateAlpha( $im3, 128, 128, 128 , 127 ); imagefill ($im3, 0, 0, $color_t); imagecopy ( $im3, $im2, $dx, $dy, 0, 0, $x_m, $y_m); imagedestroy($im2); $im2 = imagecreatetruecolor($x_i, $y_i); @imagealphablending($im2, false); @imagesavealpha($im2,true); imagecopy ( $im2, $im3, 0, 0, 0, 0, $x_i, $y_i); imagedestroy($im3); $x_m = $x_i; $y_m = $y_i; } $rapport = $x_i / $x_m; if (($y_i / $y_m) < $rapport ) { $rapport = $y_i / $y_m; } $x_d = ceil($x_i / $rapport); $y_d = ceil($y_i / $rapport); if ($x_i < $x_m OR $y_i < $y_m) { $x_dest = $x_i; $y_dest = $y_i; $x_dec = 0; $y_dec = 0; } else { $x_dest = $x_m; $y_dest = $y_m; $x_dec = round(($x_d - $x_m) /2); $y_dec = round(($y_d - $y_m) /2); } $nouveau = _image_valeurs_trans(image_reduire($im, $x_d, $y_d),""); if (!is_array($nouveau)) return(""); $im_n = $nouveau["fichier"]; $im = $nouveau["fonction_imagecreatefrom"]($im_n); imagepalettetotruecolor($im); if ($nouveau["format_source"] == "gif" AND function_exists('ImageCopyResampled')) { $im_ = imagecreatetruecolor($x_dest, $y_dest); // Si un GIF est transparent, // fabriquer un PNG transparent // Conserver la transparence if (function_exists("imageAntiAlias")) imageAntiAlias($im_,true); @imagealphablending($im_, false); @imagesavealpha($im_,true); @ImageCopyResampled($im_, $im, 0, 0, 0, 0, $x_dest, $y_dest, $x_dest, $y_dest); imagedestroy($im); $im = $im_; } $im_ = imagecreatetruecolor($x_dest, $y_dest); @imagealphablending($im_, false); @imagesavealpha($im_,true); $color_t = ImageColorAllocateAlpha( $im_, 255, 255, 255 , 127 ); imagefill ($im_, 0, 0, $color_t); for ($x = 0; $x < $x_dest; $x++) { for ($y=0; $y < $y_dest; $y++) { $rgb = ImageColorAt($im2, $x, $y); $a = ($rgb >> 24) & 0xFF; $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $rgb2 = ImageColorAt($im, $x+$x_dec, $y+$y_dec); $a2 = ($rgb2 >> 24) & 0xFF; $r2 = ($rgb2 >> 16) & 0xFF; $g2 = ($rgb2 >> 8) & 0xFF; $b2 = $rgb2 & 0xFF; if ($mode == "normal") { $v = (127 - $a) / 127; if ($v == 1) { $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v+$v2 == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; } else if ($v2 ==0) { $r_ = $r; $g_ = $g; $b_ = $b; } else if ($v == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; }else { $r_ = $r + (($r2 - $r) * $v2 * (1 - $v)); $g_ = $g + (($g2 - $g) * $v2 * (1 - $v)); $b_ = $b + (($b2 - $b) * $v2 * (1 - $v)); } } $a_ = min($a,$a2); } elseif ($mode == "produit" OR $mode == "difference") { if ($mode == "produit") { $r = ($r/255) * $r2; $g = ($g/255) * $g2; $b = ($b/255) * $b2; } else if ($mode == "difference") { $r = abs($r-$r2); $g = abs($g-$g2); $b = abs($b-$b2); } $r = max(0, min($r, 255)); $g = max(0, min($g, 255)); $b = max(0, min($b, 255)); $v = (127 - $a) / 127; if ($v == 1) { $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v+$v2 == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { $r_ = $r + (($r2 - $r) * $v2 * (1 - $v)); $g_ = $g + (($g2 - $g) * $v2 * (1 - $v)); $b_ = $b + (($b2 - $b) * $v2 * (1 - $v)); } } $a_ = $a2; } elseif ($mode == "eclaircir" OR $mode == "obscurcir") { $v = (127 - $a) / 127; if ($v == 1) { $r_ = $r; $g_ = $g; $b_ = $b; } else { $v2 = (127 - $a2) / 127; if ($v+$v2 == 0) { $r_ = $r2; $g_ = $g2; $b_ = $b2; } else { $r_ = $r + (($r2 - $r) * $v2 * (1 - $v)); $g_ = $g + (($g2 - $g) * $v2 * (1 - $v)); $b_ = $b + (($b2 - $b) * $v2 * (1 - $v)); } } if ($mode == "eclaircir") { $r_ = max ($r_, $r2); $g_ = max ($g_, $g2); $b_ = max ($b_, $b2); } else { $r_ = min ($r_, $r2); $g_ = min ($g_, $g2); $b_ = min ($b_, $b2); } $a_ = min($a,$a2); } else { $r_ = $r2 + 1 * ($r - 127); $r_ = max(0, min($r_, 255)); $g_ = $g2 + 1 * ($g - 127); $g_ = max(0, min($g_, 255)); $b_ = $b2 + 1 * ($b - 127); $b_ = max(0, min($b_, 255)); $a_ = $a + $a2 - round($a*$a2/127); } $color = ImageColorAllocateAlpha( $im_, $r_, $g_, $b_ , $a_ ); imagesetpixel ($im_, $x, $y, $color); } } _image_gd_output($im_,$image); imagedestroy($im_); imagedestroy($im); imagedestroy($im2); } $x_dest = largeur($dest); $y_dest = hauteur($dest); return _image_ecrire_tag($image,array('src'=>$dest,'width'=>$x_dest,'height'=>$y_dest)); }
/** * Resize the image * * Includes function ImageCreateTrueColor and ImageCopyResampled which are available only under GD 2.0.1 or higher ! * * @copyright * @author RolandD * @todo Fix docbloc * @see * @access private * @param $orig_img * @return * @since 3.0 */ private function NewImgResize($orig_img) { $orig_size = getimagesize($this->file); $maxX = $this->file_out_width; $maxY = $this->file_out_height; if ($orig_size[0] < $orig_size[1]) { $this->file_out_width = $this->file_out_height * ($orig_size[0] / $orig_size[1]); $adjustX = ($maxX - $this->file_out_width) / 2; $adjustY = 0; } else { $this->file_out_height = $this->file_out_width / ($orig_size[0] / $orig_size[1]); $adjustX = 0; $adjustY = ($maxY - $this->file_out_height) / 2; } while ($this->file_out_width < 1 || $this->file_out_height < 1) { $this->file_out_width *= 2; $this->file_out_height *= 2; } // See if we need to create an image at maximum size if ($this->maxSize) { if (function_exists("imagecreatetruecolor")) { $im_out = imagecreatetruecolor($maxX, $maxY); } else { $im_out = imagecreate($maxX, $maxY); } if ($im_out) { // Need to image fill just in case image is transparent, don't always want black background $bgfill = imagecolorallocate($im_out, $this->bg_red, $this->bg_green, $this->bg_blue); if (function_exists("imageAntiAlias")) { imageAntiAlias($im_out, true); } imagealphablending($im_out, false); if (function_exists("imagesavealpha")) { imagesavealpha($im_out, true); } if (function_exists("imagecolorallocatealpha")) { $transparent = imagecolorallocatealpha($im_out, 255, 255, 255, 127); } if (function_exists("imagecopyresampled")) { ImageCopyResampled($im_out, $orig_img, $adjustX, $adjustY, 0, 0, $this->file_out_width, $this->file_out_height, $orig_size[0], $orig_size[1]); } else { ImageCopyResized($im_out, $orig_img, $adjustX, $adjustY, 0, 0, $this->file_out_width, $this->file_out_height, $orig_size[0], $orig_size[1]); } } else { return false; } } else { if (function_exists("imagecreatetruecolor")) { $im_out = ImageCreateTrueColor($this->file_out_width, $this->file_out_height); } else { $im_out = imagecreate($this->file_out_width, $this->file_out_height); } if ($im_out) { if (function_exists("imageAntiAlias")) { imageAntiAlias($im_out, true); } imagealphablending($im_out, false); if (function_exists("imagesavealpha")) { imagesavealpha($im_out, true); } if (function_exists("imagecolorallocatealpha")) { $transparent = imagecolorallocatealpha($im_out, 255, 255, 255, 127); } if (function_exists("imagecopyresampled")) { ImageCopyResampled($im_out, $orig_img, 0, 0, 0, 0, $this->file_out_width, $this->file_out_height, $orig_size[0], $orig_size[1]); } else { ImageCopyResized($im_out, $orig_img, 0, 0, 0, 0, $this->file_out_width, $this->file_out_height, $orig_size[0], $orig_size[1]); } } else { return false; } } return $im_out; }
/** * Maybe adding sharpening with * $sharpenMatrix = array ( array(-1.2, -1, -1.2), array(-1, 20, -1), array(-1.2, -1, -1.2) ); // calculate the sharpen divisor $divisor = array_sum(array_map('array_sum', $sharpenMatrix)); $offset = 0; // apply the matrix imageconvolution($img, $sharpenMatrix, $divisor, $offset); * * private function - do not call * includes function ImageCreateTrueColor and ImageCopyResampled which are available only under GD 2.0.1 or higher ! */ private function NewImgResize($orig_img, $newxsize, $newysize, $filename) { //getimagesize returns array // [0] = width in pixels // [1] = height in pixels // [2] = type // [3] = img tag "width=xx height=xx" values $orig_size = getimagesize($filename); $newxsize = (int) $newxsize; $newysize = (int) $newysize; if (empty($newxsize) and empty($newysize)) { vmWarn('NewImgResize failed x,y = 0', 'NewImgResize failed x,y = 0'); return false; } $maxX = $newxsize; $maxY = $newysize; if ($orig_size[0] < $orig_size[1]) { $newxsize = (int) $newysize * ($orig_size[0] / $orig_size[1]); $adjustX = (int) ($maxX - $newxsize) / 2; $adjustY = 0; } else { $newysize = (int) $newxsize / ($orig_size[0] / $orig_size[1]); $adjustX = 0; $adjustY = (int) ($maxY - $newysize) / 2; } /* Original code removed to allow for maxSize thumbnails $im_out = ImageCreateTrueColor($newxsize,$newysize); ImageCopyResampled($im_out, $orig_img, 0, 0, 0, 0, $newxsize, $newysize,$orig_size[0], $orig_size[1]); */ // New modification - creates new image at maxSize if ($this->maxSize) { if (function_exists("imagecreatetruecolor")) { $im_out = imagecreatetruecolor($maxX, $maxY); } else { $im_out = imagecreate($maxX, $maxY); } // Need to image fill just in case image is transparent, don't always want black background $bgfill = imagecolorallocate($im_out, $this->bg_red, $this->bg_green, $this->bg_blue); if (function_exists("imageAntiAlias")) { imageAntiAlias($im_out, true); } imagealphablending($im_out, false); if (function_exists("imagesavealpha")) { imagesavealpha($im_out, true); } if (function_exists("imagecolorallocatealpha")) { $transparent = imagecolorallocatealpha($im_out, 255, 255, 255, 127); } //imagefill( $im_out, 0,0, $bgfill ); if (function_exists("imagecopyresampled")) { ImageCopyResampled($im_out, $orig_img, $adjustX, $adjustY, 0, 0, $newxsize, $newysize, $orig_size[0], $orig_size[1]); } else { ImageCopyResized($im_out, $orig_img, $adjustX, $adjustY, 0, 0, $newxsize, $newysize, $orig_size[0], $orig_size[1]); } } else { if (function_exists("imagecreatetruecolor")) { $im_out = ImageCreateTrueColor($newxsize, $newysize); } else { $im_out = imagecreate($newxsize, $newysize); } if (function_exists("imageAntiAlias")) { imageAntiAlias($im_out, true); } imagealphablending($im_out, false); if (function_exists("imagesavealpha")) { imagesavealpha($im_out, true); } if (function_exists("imagecolorallocatealpha")) { $transparent = imagecolorallocatealpha($im_out, 255, 255, 255, 127); } if (function_exists("imagecopyresampled")) { ImageCopyResampled($im_out, $orig_img, 0, 0, 0, 0, $newxsize, $newysize, $orig_size[0], $orig_size[1]); } else { ImageCopyResized($im_out, $orig_img, 0, 0, 0, 0, $newxsize, $newysize, $orig_size[0], $orig_size[1]); } } return $im_out; }
<?php //$img = imageCreateTrueColor(500,300); $img = imagecreatefromjpeg("images/noise.jpg"); imageAntiAlias($img, true); //зглаживание $red = imageColorAllocate($img, 255, 0, 0); $green = imageColorAllocate($img, 0, 255, 0); $blue = imageColorAllocate($img, 0, 0, 255); $white = imageColorAllocate($img, 255, 255, 255); $black = imageColorAllocate($img, 0, 0, 0); $silver = imageColorAllocate($img, 192, 192, 192); /* imageLine($img,20,20,480,280,$white); imageLine($img,480,20,20,280,$red); imageFilledRectangle($img,40,40,80,280,$white); imageRectangle($img,20,20,80,280,$blue); $points = array(0,0,100,200,300,200); imagePolygon($img, $points,3,$green); imageEllipse($img, 200,150,300,200, $red); imageFilledEllipse($img, 200,150,300,200, $red); imageArc($img, 210,160,300,200,0,-60, $blue); imageFilledArc($img, 210,160,300,200,0,90, $silver, IMG_ARC_NOFILL); imageString($img, 5, 150, 200, "Hello!", $white); imageTtfText($img,30,10,200,150,$red,"arial.ttf","Привет!"); */ imageTtfText($img, 20, 3, 20, 30, $black, "arial.ttf", "Привет"); header('Content-type: image/png'); imagePNG($img);
function _image_creer_vignette($valeurs, $maxWidth, $maxHeight, $process='AUTO', $force=false, $test_cache_only = false) { // ordre de preference des formats graphiques pour creer les vignettes // le premier format disponible, selon la methode demandee, est utilise $image = $valeurs['fichier']; $format = $valeurs['format_source']; $destdir = dirname($valeurs['fichier_dest']); $destfile = basename($valeurs['fichier_dest'],".".$valeurs["format_dest"]); $format_sortie = $valeurs['format_dest']; // liste des formats qu'on sait lire $img = isset($GLOBALS['meta']['formats_graphiques']) ? (strpos($GLOBALS['meta']['formats_graphiques'], $format)!==false) : false; // si le doc n'est pas une image, refuser if (!$force AND !$img) return; $destination = "$destdir/$destfile"; // chercher un cache $vignette = ''; if ($test_cache_only AND !$vignette) return; // utiliser le cache ? if (!$test_cache_only) if ($force OR !$vignette OR (@filemtime($vignette) < @filemtime($image))) { $creation = true; // calculer la taille if (($srcWidth=$valeurs['largeur']) && ($srcHeight=$valeurs['hauteur'])){ if (!($destWidth=$valeurs['largeur_dest']) || !($destHeight=$valeurs['hauteur_dest'])) list ($destWidth,$destHeight) = _image_ratio($valeurs['largeur'], $valeurs['hauteur'], $maxWidth, $maxHeight); } elseif ($process == 'convert' OR $process == 'imagick') { $destWidth = $maxWidth; $destHeight = $maxHeight; } else { spip_log("echec $process sur $image"); return; } // Si l'image est de la taille demandee (ou plus petite), simplement // la retourner if ($srcWidth AND $srcWidth <= $maxWidth AND $srcHeight <= $maxHeight) { $vignette = $destination.'.'.$format; @copy($image, $vignette); } // imagemagick en ligne de commande else if ($process == 'convert') { define('_CONVERT_COMMAND', 'convert'); define ('_RESIZE_COMMAND', _CONVERT_COMMAND.' -quality 85 -resize %xx%y! %src %dest'); $vignette = $destination.".".$format_sortie; $commande = str_replace( array('%x', '%y', '%src', '%dest'), array( $destWidth, $destHeight, escapeshellcmd($image), escapeshellcmd($vignette) ), _RESIZE_COMMAND); spip_log($commande); exec($commande); if (!@file_exists($vignette)) { spip_log("echec convert sur $vignette"); return; // echec commande } } else // imagick (php4-imagemagick) if ($process == 'imagick') { $vignette = "$destination.".$format_sortie; $handle = imagick_readimage($image); imagick_resize($handle, $destWidth, $destHeight, IMAGICK_FILTER_LANCZOS, 0.75); imagick_write($handle, $vignette); if (!@file_exists($vignette)) { spip_log("echec imagick sur $vignette"); return; } } else // netpbm if ($process == "netpbm") { define('_PNMSCALE_COMMAND', 'pnmscale'); // chemin a changer dans mes_options if (_PNMSCALE_COMMAND == '') return; $vignette = $destination.".".$format_sortie; $pnmtojpeg_command = str_replace("pnmscale", "pnmtojpeg", _PNMSCALE_COMMAND); if ($format == "jpg") { $jpegtopnm_command = str_replace("pnmscale", "jpegtopnm", _PNMSCALE_COMMAND); exec("$jpegtopnm_command $image | "._PNMSCALE_COMMAND." -width $destWidth | $pnmtojpeg_command > $vignette"); if (!($s = @filesize($vignette))) spip_unlink($vignette); if (!@file_exists($vignette)) { spip_log("echec netpbm-jpg sur $vignette"); return; } } else if ($format == "gif") { $giftopnm_command = str_replace("pnmscale", "giftopnm", _PNMSCALE_COMMAND); exec("$giftopnm_command $image | "._PNMSCALE_COMMAND." -width $destWidth | $pnmtojpeg_command > $vignette"); if (!($s = @filesize($vignette))) spip_unlink($vignette); if (!@file_exists($vignette)) { spip_log("echec netpbm-gif sur $vignette"); return; } } else if ($format == "png") { $pngtopnm_command = str_replace("pnmscale", "pngtopnm", _PNMSCALE_COMMAND); exec("$pngtopnm_command $image | "._PNMSCALE_COMMAND." -width $destWidth | $pnmtojpeg_command > $vignette"); if (!($s = @filesize($vignette))) spip_unlink($vignette); if (!@file_exists($vignette)) { spip_log("echec netpbm-png sur $vignette"); return; } } } // gd ou gd2 else if ($process == 'gd1' OR $process == 'gd2') { if (_IMG_GD_MAX_PIXELS && $srcWidth*$srcHeight>_IMG_GD_MAX_PIXELS){ spip_log("vignette gd1/gd2 impossible : ".$srcWidth*$srcHeight."pixels"); return; } $destFormat = $format_sortie; if (!$destFormat) { spip_log("pas de format pour $image"); return; } $fonction_imagecreatefrom = $valeurs['fonction_imagecreatefrom']; if (!function_exists($fonction_imagecreatefrom)) return ''; $srcImage = @$fonction_imagecreatefrom($image); if (!$srcImage) { spip_log("echec gd1/gd2"); return; } // Initialisation de l'image destination if ($process == 'gd2' AND $destFormat != "gif") $destImage = ImageCreateTrueColor($destWidth, $destHeight); if (!$destImage) $destImage = ImageCreate($destWidth, $destHeight); // Recopie de l'image d'origine avec adaptation de la taille $ok = false; if (($process == 'gd2') AND function_exists('ImageCopyResampled')) { if ($format == "gif") { // Si un GIF est transparent, // fabriquer un PNG transparent $transp = imagecolortransparent($srcImage); if ($transp > 0) $destFormat = "png"; } if ($destFormat == "png") { // Conserver la transparence if (function_exists("imageAntiAlias")) imageAntiAlias($destImage,true); @imagealphablending($destImage, false); @imagesavealpha($destImage,true); } $ok = @ImageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight); } if (!$ok) $ok = ImageCopyResized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight); // Sauvegarde de l'image destination $valeurs['fichier_dest'] = $vignette = "$destination.$destFormat"; $valeurs['format_dest'] = $format = $destFormat; _image_gd_output($destImage,$valeurs); if ($srcImage) ImageDestroy($srcImage); ImageDestroy($destImage); } } $size = @getimagesize($vignette); // Gaffe: en safe mode, pas d'acces a la vignette, // donc risque de balancer "width='0'", ce qui masque l'image sous MSIE if ($size[0] < 1) $size[0] = $destWidth; if ($size[1] < 1) $size[1] = $destHeight; $retour['width'] = $largeur = $size[0]; $retour['height'] = $hauteur = $size[1]; $retour['fichier'] = $vignette; $retour['format'] = $format; $retour['date'] = (file_exists($vignette)) ? filemtime($vignette) : 0; // renvoyer l'image return $retour; }
/** * Resizes image to maxWidth x maxHeight * * @param int $maxWidth * @param int $maxHeight */ public function resize($maxWidth = 0, $maxHeight = 0) { $this->maxWidth = $maxWidth; $this->maxHeight = $maxHeight; $this->calcImageSize($this->currentDimensions['width'], $this->currentDimensions['height']); if (function_exists("ImageCreateTrueColor")) { if ($this->format == 'PNG') { $temp = ImageCreateTrueColor($this->newDimensions['newWidth'], $this->newDimensions['newHeight']); // $temp = imagecreatetruecolor($w, $h); /* making the new image transparent */ $background = imagecolorallocate($temp, 0, 0, 0); ImageColorTransparent($temp, $background); // make the new temp image all transparent imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel imagesavealpha($temp, true); // Save full alpha imageAntiAlias($temp, true); $this->workingImage = $temp; } else { $this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'], $this->newDimensions['newHeight']); } } else { $this->workingImage = ImageCreate($this->newDimensions['newWidth'], $this->newDimensions['newHeight']); } ImageCopyResampled($this->workingImage, $this->oldImage, 0, 0, 0, 0, $this->newDimensions['newWidth'], $this->newDimensions['newHeight'], $this->currentDimensions['width'], $this->currentDimensions['height']); $this->oldImage = $this->workingImage; $this->newImage = $this->workingImage; $this->currentDimensions['width'] = $this->newDimensions['newWidth']; $this->currentDimensions['height'] = $this->newDimensions['newHeight']; }
function osc_gd_resize($original_image, $dest_image, $dest_width, $dest_height, $force_size = '0') { $img_type = false; switch (strtolower(substr(basename($original_image), strrpos(basename($original_image), '.') + 1))) { case 'jpg': case 'jpeg': if (imagetypes() & IMG_JPG) { $img_type = 'jpg'; } break; case 'gif': if (imagetypes() & IMG_GIF) { $img_type = 'gif'; } break; case 'png': if (imagetypes() & IMG_PNG) { $img_type = 'png'; } break; } if ($img_type !== false) { list($orig_width, $orig_height) = getimagesize($original_image); $width = $dest_width; $height = $dest_height; $factor = max($orig_width / $width, $orig_height / $height); if ($force_size == '1') { $width = $dest_width; } else { $width = round($orig_width / $factor); $height = round($orig_height / $factor); } $im_p = imageCreateTrueColor($dest_width, $dest_height); imageAntiAlias($im_p, true); imagealphablending($im_p, false); imagesavealpha($im_p, true); $transparent = imagecolorallocatealpha($im_p, 255, 255, 255, 127); for ($x = 0; $x < $dest_width; $x++) { for ($y = 0; $y < $dest_height; $y++) { imageSetPixel($im_p, $x, $y, $transparent); } } $x = 0; $y = 0; if ($force_size == '1') { $width = round($orig_width * $dest_height / $orig_height); if ($width < $dest_width) { $x = floor(($dest_width - $width) / 2); } } else { $x = floor(($dest_width - $width) / 2); $y = floor(($dest_height - $height) / 2); } switch ($img_type) { case 'jpg': $im = imagecreatefromjpeg($original_image); break; case 'gif': $im = imagecreatefromgif($original_image); break; case 'png': $im = imagecreatefrompng($original_image); break; } imagecopyresampled($im_p, $im, $x, $y, 0, 0, $width, $height, $orig_width, $orig_height); switch ($img_type) { case 'jpg': imagejpeg($im_p, $dest_image); break; case 'gif': imagegif($im_p, $dest_image); break; case 'png': imagepng($im_p, $dest_image); break; } imagedestroy($im_p); imagedestroy($im); @chmod($dest_image, 0777); } else { return false; } }
//Calculate the new size based on the selected area and the minimums if ($width > $height) { $dest_width = $max_width; $dest_height = round($max_width * $height / $width); } else { $dest_width = round($max_height * $width / $height); $dest_height = $max_height; } //we generate a new image object of the size calculated above, using PHP's GD functions if (!($dest_image = imagecreatetruecolor($dest_width, $dest_height))) { die('Could not create new image from source file.'); } //hack to keep transparency in gif and png if ($info[2] == IMAGETYPE_GIF || $info[2] == IMAGETYPE_PNG) { if ($info[2] == IMAGETYPE_PNG) { imageAntiAlias($dest_image, true); } imagecolortransparent($dest_image, imagecolorallocatealpha($dest_image, 0, 0, 0, 127)); imagealphablending($dest_image, false); imagesavealpha($dest_image, true); } /* this is where we crop the image, -the first parameter is the destinatation image (not a physical file, but a GD image object) -second is the source image. Again it's not the physical file but a GD object (which was generated from an image file this time) -third and fourth params are the X and Y coordinates to paste the copied region in the destination image. In this case we want both of them to be 0, -fifth and sixth are the X and Y coordinates to start cropping in the source image. So they are pretty much the coordinates we got from UvumiCrop. -seventh and eighth are the width and height of the destination image, the one calculated right above -ninth and tenth are the width and height of the cropping region, directly from UvumiCrop again By just setting $max_width and $max_height above, you should not have to worry about this
function _resizeImage($file_path, $newWidth, $newHeight, $dstFolder = '', $type = 'thumbnail', $watermark = '') { $image = $this->uploadFolder . $file_path; if (empty($dstFolder)) { $dstFolder = $this->uploadFolder . 'thumbnail_' . $this->thumbnail_y . 'x' . $this->thumbnail_x . DS; } $watermark_path = ''; if (hikashop_level(2) && $type == 'image') { $config =& hikashop_config(); $watermark_name = $watermark; if (empty($watermark_name) && $watermark_name !== false) { $watermark_name = $config->get('watermark', ''); } if (!empty($watermark_name)) { $watermark_path = $this->main_uploadFolder . $watermark_name; if (!$this->_checkImage($watermark_path)) { $watermark_path = ''; } else { $wm_extension = strtolower(substr($watermark_path, strrpos($watermark_path, '.') + 1)); $watermark = $this->_getImage($watermark_path, $wm_extension); if ($watermark) { if (in_array($wm_extension, array('gif', 'png'))) { imagealphablending($watermark, false); imagesavealpha($watermark, true); } } else { $watermark_path = ''; } } } } $extension = strtolower(substr($file_path, strrpos($file_path, '.') + 1)); $img = $this->_getImage($image, $extension); if (!$img) { return false; } if (in_array($extension, array('gif', 'png'))) { imagealphablending($img, false); imagesavealpha($img, true); } if ($newWidth != $this->width || $newHeight != $this->height) { $thumb = ImageCreateTrueColor($newWidth, $newHeight); if (in_array($extension, array('gif', 'png'))) { $trnprt_indx = imagecolortransparent($img); if ($trnprt_indx >= 0) { $trnprt_color = imagecolorsforindex($img, $trnprt_indx); $trnprt_indx = imagecolorallocate($thumb, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); imagefill($thumb, 0, 0, $trnprt_indx); imagecolortransparent($thumb, $trnprt_indx); } elseif ($extension == 'png') { imagealphablending($thumb, false); $color = imagecolorallocatealpha($thumb, 0, 0, 0, 127); imagefill($thumb, 0, 0, $color); imagesavealpha($thumb, true); } } if (function_exists("imageAntiAlias")) { imageAntiAlias($thumb, true); } if (function_exists("imagecopyresampled")) { ImageCopyResampled($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight, $this->width, $this->height); } else { ImageCopyResized($thumb, $img, 0, 0, 0, 0, $newWidth, $newHeight, $this->width, $this->height); } } else { $thumb =& $img; } if (!empty($watermark_path)) { list($wm_width, $wm_height) = getimagesize($watermark_path); $padding = 3; $dest_x = $newWidth - $wm_width - $padding; if ($dest_x < 0) { $dest_x = 0; } $dest_y = $newHeight - $wm_height - $padding; if ($dest_y < 0) { $dest_y = 0; } $trnprt_color = null; if (in_array($extension, array('gif', 'png'))) { $trnprt_indx = imagecolortransparent($img); if ($trnprt_indx >= 0) { $trnprt_color = imagecolorsforindex($img, $trnprt_indx); } } imagealphablending($thumb, false); imagealphablending($watermark, false); $this->imagecopymerge_alpha($thumb, $watermark, $dest_x, $dest_y, 0, 0, $wm_width, $wm_height, (int) $config->get('opacity', 0), $trnprt_color); imagedestroy($watermark); } $dest = $dstFolder . $file_path; ob_start(); switch ($extension) { case 'gif': $status = imagegif($thumb); break; case 'jpg': case 'jpeg': $status = imagejpeg($thumb, null, 100); break; case 'png': $status = imagepng($thumb, null, 0); break; } $imageContent = ob_get_clean(); $status = $status && JFile::write($dest, $imageContent); imagedestroy($img); @imagedestroy($thumb); return $status; }
function conv_img($src, $dest, $quality, $imgcut) { if (file_exists($src) && isset($dest)) { // path info $destInfo = pathInfo($dest); // image src size $srcSize = getImageSize($src); $maxWidth=$srcSize[0]; $maxHeight=$srcSize[1]; // image dest size $destSize[0] = width, $destSize[1] = height $srcRatio= $srcSize[0]/$srcSize[1]; //$destRatio = $maxWidth/$maxHeight; $RatioX = $maxWidth/$srcSize[0]; // 최대 이미지 너비 / 원본 이미지 너비 $RatioY = $maxHeight/$srcSize[1]; // 최대 이미지 높이 / 원본 이미지 높이 if ($imgcut == N){ //원본 이미지를 자르지 않고 비율대로 축소 할 경우 //if ($destRatio > $srcRatio){ if ($RatioX <= $RatioY) { $destSize[0] = $maxWidth; $destSize[1] = $maxWidth/$srcRatio; } else { $destSize[1] = $maxHeight; $destSize[0] = $maxHeight*$srcRatio; } } else { //원본이미지를 비율대로 축소하고 사이즈에 맞게 자를 경우 //if ($destRatio < $srcRatio){ if ($RatioX <= $RatioY) { $destSize[0] = round(($srcSize[0]*$maxHeight)/$srcSize[1]); //$maxHeight*$srcRatio; $destSize[1] = $maxHeight; $offsetX = round(($destSize[0] - $maxWidth) / 2); // 각각 좌우로 잘라낼 길이 $offsetY = 0; } else { $destSize[0] = $maxWidth; $destSize[1] = round(($srcSize[1]*$maxWidth)/$srcSize[0]); //$maxWidth/$srcRatio; $offsetX = 0; $offsetY = round(($destSize[1] - $maxHeight ) / 2); // 각각 상하로 잘라낼 길이 } } // path rectification if ($destInfo['extension'] == "gif"){ $dest = substr_replace($dest, 'jpg', -3); } // src image switch ($srcSize[2]) { case 1: //GIF $srcImage = imageCreateFromGif($src); break; case 2: //JPEG $srcImage = imageCreateFromJpeg($src); break; case 3: //PNG $srcImage = imageCreateFromPng($src); break; default: return false; break; } // true color image, with anti-aliasing if ($imgcut == N){ $destImage = imageCreateTrueColor($destSize[0], $destSize[1]); } else { $destImage = imageCreateTrueColor($maxWidth, $maxHeight); } imageAntiAlias($destImage,true); // resampling if ($imgcut == N){ imageCopyResampled($destImage, $srcImage,0,0,0,0,$destSize[0],$destSize[1],$srcSize[0],$srcSize[1]); }else{ imageCopyResampled($destImage, $srcImage, 0, 0, $offsetX, $offsetY, $destSize[0], $destSize[1], ImagesX($srcImage)-$offsetX, ImagesY($srcImage)-$offsetY); } // generating image switch ($srcSize[2]){ case 1: imageGif($destImage,$dest); break; case 2: imageJpeg($destImage,$dest,$quality); break; case 3: imagePng($destImage,$dest); break; } return true; } else { return false; } }