/** * Returns an image with a resized canvas * * The image is filled with $color. Use $scale to determine, when to resize. * * @param WideImage_Image $img * @param smart_coordinate $width * @param smart_coordinate $height * @param smart_coordinate $left * @param smart_coordinate $top * @param int $color * @param string $scale 'up', 'down', 'any' * @return WideImage_Image */ function execute($img, $width, $height, $left, $top, $color, $scale) { $new_width = WideImage_Coordinate::fix($width, $img->getWidth()); $new_height = WideImage_Coordinate::fix($width, $img->getHeight()); if ($scale == 'down') { $new_width = min($new_width, $img->getWidth()); $new_height = min($new_height, $img->getHeight()); } elseif ($scale == 'up') { $new_width = max($new_width, $img->getWidth()); $new_height = max($new_height, $img->getHeight()); } $new = WideImage::createTrueColorImage($new_width, $new_height); if ($img->isTrueColor()) { if ($color === null) { $color = $new->allocateColorAlpha(0, 0, 0, 127); } } else { imagepalettecopy($new->getHandle(), $img->getHandle()); if ($color === null) { if ($img->isTransparent()) { $new->copyTransparencyFrom($img); $tc_rgb = $img->getTransparentColorRGB(); $color = $new->allocateColorAlpha($tc_rgb); } else { $color = $new->allocateColorAlpha(255, 0, 127, 127); } imagecolortransparent($new->getHandle(), $color); } } $new->fill(0, 0, $color); $x = WideImage_Coordinate::fix($left, $new->getWidth(), $img->getWidth()); $y = WideImage_Coordinate::fix($top, $new->getHeight(), $img->getHeight()); $img->copyTo($new, $x, $y); return $new; }
/** * Workaround method for restoring alpha transparency for gif images * * @param resource $src * @param resource $dest * @return resource transparent gf color */ public static function restoreGifAlphaColor(&$src, &$dest) { $transparentcolor = imagecolortransparent($src); if ($transparentcolor != -1) { $colorcount = imagecolorstotal($src); imagetruecolortopalette($dest, true, $colorcount); imagepalettecopy($dest, $src); imagefill($dest, 0, 0, $transparentcolor); imagecolortransparent($dest, $transparentcolor); } return $transparentcolor; }
/** * Returns an image with a resized canvas * * The image is filled with $color. Use $scale to determine, when to resize. * * @param WideImage_Image $img * @param smart_coordinate $width * @param smart_coordinate $height * @param smart_coordinate $left * @param smart_coordinate $top * @param int $color * @param string $scale 'up', 'down', 'any' * @param boolean $merge * @return WideImage_Image */ function execute($img, $width, $height, $left, $top, $color, $scale, $merge) { $new_width = WideImage_Coordinate::fix($width, $img->getWidth()); $new_height = WideImage_Coordinate::fix($height, $img->getHeight()); if ($scale == 'down') { $new_width = min($new_width, $img->getWidth()); $new_height = min($new_height, $img->getHeight()); } elseif ($scale == 'up') { $new_width = max($new_width, $img->getWidth()); $new_height = max($new_height, $img->getHeight()); } $new = WideImage::createTrueColorImage($new_width, $new_height); if ($img->isTrueColor()) { if ($color === null) { $color = $new->allocateColorAlpha(0, 0, 0, 127); } } else { imagepalettecopy($new->getHandle(), $img->getHandle()); if ($img->isTransparent()) { $new->copyTransparencyFrom($img); $tc_rgb = $img->getTransparentColorRGB(); $t_color = $new->allocateColorAlpha($tc_rgb); } if ($color === null) { if ($img->isTransparent()) { $color = $t_color; } else { $color = $new->allocateColorAlpha(255, 0, 127, 127); } imagecolortransparent($new->getHandle(), $color); } } $new->fill(0, 0, $color); $x = WideImage_Coordinate::fix($left, $new->getWidth(), $img->getWidth()); $y = WideImage_Coordinate::fix($top, $new->getHeight(), $img->getHeight()); // blending for truecolor images if ($img->isTrueColor()) { $new->alphaBlending($merge); } // not-blending for palette images if (!$merge && !$img->isTrueColor() && isset($t_color)) { $new->getCanvas()->filledRectangle($x, $y, $x + $img->getWidth(), $y + $img->getHeight(), $t_color); } $img->copyTo($new, $x, $y); return $new; }
function keepTransparent($des) { $image = $this->image; if ($image->getFormat() == 'png') { imagealphablending($des, false); imagesavealpha($des, true); } elseif ($image->getFormat() == 'gif') { $gdimage =& $image->getImage(); $colorTransparent = imagecolortransparent($gdimage); imagepalettecopy($gdimage, $des); if ($colorTransparent > 0) { imagefill($des, 0, 0, $colorTransparent); imagecolortransparent($des, $colorTransparent); } imagetruecolortopalette($des, true, 256); } }
function imagecopyresampled_adv($image_type, &$dest, $source, $d_x, $d_y, $s_x, $s_y, $d_w, $d_h, $s_w, $s_h) { switch ($image_type) { // Process GIF images case 1: $transcol = imagecolortransparent($source); $dest = imagecreate($d_w, $d_h); imagepalettecopy($dest, $source); imagefill($dest, 0, 0, $transcol); imagecolortransparent($dest, $transcol); return imagecopyresized($dest, $source, $d_x, $d_y, $s_x, $s_y, $d_w, $d_h, $s_w, $s_h); break; // Process PNG images // Process PNG images case 3: $dest = imageCreateTrueColor($d_w, $d_h); imagealphablending($dest, false); imagesavealpha($dest, true); $transparent = imagecolorallocatealpha($dest, 255, 255, 255, 0); //BOF - DokuMan - 2011-01-06 - imagecolortransparent much faster on big images //for ($x = 0; $x < $d_w; $x++) { // for ($y = 0; $y < $d_h; $y++) { // imageSetPixel($dest, $x, $y, $transparent); // } //} imagecolortransparent($dest, $transparent); //EOF - DokuMan - 2011-01-06 - imagecolortransparent much faster on big images return imagecopyresampled($dest, $source, $d_x, $d_y, $s_x, $s_y, $d_w, $d_h, $s_w, $s_h); break; // Any other images // Any other images default: $dest = imageCreateTrueColor($d_w, $d_h); return imagecopyresampled($dest, $source, $d_x, $d_y, $s_x, $s_y, $d_w, $d_h, $s_w, $s_h); } }
/** * Returns a new image for temporary processing * * @access private * @param int $width Width of the new image * @param int $height Height of the new image * @param bool $trueColor Force which type of image to create * @return resource A GD image resource */ private function _createImage($width = -1, $height = -1, $trueColor = null) { if ($width == -1) { $width = $this->_img_w; } if ($height == -1) { $height = $this->_img_h; } $new_img = null; if (is_null($trueColor)) { if (function_exists('imageistruecolor')) { $createtruecolor = imageistruecolor($this->_hImage); } else { $createtruecolor = true; } } else { $createtruecolor = $trueColor; } if ($createtruecolor && function_exists('imagecreatetruecolor')) { $new_img = @imagecreatetruecolor($width, $height); } if (!$new_img) { $new_img = imagecreate($width, $height); imagepalettecopy($new_img, $this->_hImage); } if ($this->_itype != 'gif') { imagealphablending($new_img, false); imagesavealpha($new_img, true); } $color = imagecolortransparent($this->_hImage); if ($color != -1) { imagecolortransparent($new_img, $color); imagefill($new_img, 0, 0, $color); } return $new_img; }
function imagerotatex($im, $r, $c) { $r = deg2rad($r); $sx = imagesx($im); $sy = imagesy($im); $im2 = imagecreate($sx, $sy); imagepalettecopy($im2, $im); $dx = floor($sx / 2); $dy = floor($sy / 2); for ($x = 0; $x < $sx; $x++) { for ($y = 0; $y < $sy; $y++) { $xx = $x - $dx; $yy = $y - $dy; $x1 = round($xx * cos($r) + $yy * sin($r)) + $dx; $y1 = round(-$xx * sin($r) + $yy * cos($r)) + $dy; $p = imagecolorat($im, $x1, $y1); if ($p !== $c) { $p = 0; } imagesetpixel($im2, $x, $y, $p); } } return $im2; }
/** * Rotate image by the given angle * Uses a fast rotation algorythm for custom angles * or lines copy for multiple of 90 degrees * * @param int $angle Rotation angle * @param array $options array( 'autoresize'=>true|false, * 'color_mask'=>array(r,g,b), named color or #rrggbb * ) * @author Pierre-Alain Joye * @return mixed none or a PEAR error object on error * @see PEAR::isError() */ function rotate($angle, $options = null) { if (function_exists('imagerotate')) { $white = imagecolorallocatealpha($this->imageHandle, 255, 255, 255, 127); $this->imageHandle = imagerotate($this->imageHandle, $angle, $white); return true; } if ($options == null) { $autoresize = true; $color_mask = array(105, 255, 255); } else { extract($options); } while ($angle <= -45) { $angle += 360; } while ($angle > 270) { $angle -= 360; } $t = deg2rad($angle); if (!is_array($color_mask)) { if ($color[0] == '#') { $this->colorhex2colorarray($color_mask); } else { include_once 'Image/Transform/Driver/ColorDefs.php'; $color = isset($colornames[$color_mask]) ? $colornames[$color_mask] : false; } } // Do not round it, too much lost of quality $cosT = cos($t); $sinT = sin($t); $img =& $this->imageHandle; $width = $max_x = $this->img_x; $height = $max_y = $this->img_y; $min_y = 0; $min_x = 0; $x1 = round($max_x / 2, 0); $y1 = round($max_y / 2, 0); if ($autoresize) { $t = abs($t); $a = round($angle, 0); switch ((int) $angle) { case 0: $width2 = $width; $height2 = $height; break; case 90: $width2 = $height; $height2 = $width; break; case 180: $width2 = $width; $height2 = $height; break; case 270: $width2 = $height; $height2 = $width; break; default: $width2 = (int) abs(sin($t) * $height + cos($t) * $width); $height2 = (int) abs(cos($t) * $height + sin($t) * $width); } $width2 -= $width2 % 2; $height2 -= $height2 % 2; $d_width = abs($width - $width2); $d_height = abs($height - $height2); $x_offset = $d_width / 2; $y_offset = $d_height / 2; $min_x2 = -abs($x_offset); $min_y2 = -abs($y_offset); $max_x2 = $width2; $max_y2 = $height2; } $img2 = @$this->newImgPreserveAlpha(imagecreateTrueColor($width2, $height2)); if (!is_resource($img2)) { return false; /*PEAR::raiseError('Cannot create buffer for the rotataion.', null, PEAR_ERROR_TRIGGER, E_USER_NOTICE);*/ } $this->img_x = $width2; $this->img_y = $height2; imagepalettecopy($img2, $img); $mask = imagecolorallocatealpha($img2, $color_mask[0], $color_mask[1], $color_mask[2], 127); // use simple lines copy for axes angles switch ((int) $angle) { case 0: imagefill($img2, 0, 0, $mask); for ($y = 0; $y < $max_y; $y++) { for ($x = $min_x; $x < $max_x; $x++) { $c = @imagecolorat($img, $x, $y); imagesetpixel($img2, $x + $x_offset, $y + $y_offset, $c); } } break; case 90: imagefill($img2, 0, 0, $mask); for ($x = $min_x; $x < $max_x; $x++) { for ($y = $min_y; $y < $max_y; $y++) { $c = imagecolorat($img, $x, $y); imagesetpixel($img2, $max_y - $y - 1, $x, $c); } } break; case 180: imagefill($img2, 0, 0, $mask); for ($y = 0; $y < $max_y; $y++) { for ($x = $min_x; $x < $max_x; $x++) { $c = @imagecolorat($img, $x, $y); imagesetpixel($img2, $max_x2 - $x - 1, $max_y2 - $y - 1, $c); } } break; case 270: imagefill($img2, 0, 0, $mask); for ($y = 0; $y < $max_y; $y++) { for ($x = $max_x; $x >= $min_x; $x--) { $c = @imagecolorat($img, $x, $y); imagesetpixel($img2, $y, $max_x - $x - 1, $c); } } break; // simple reverse rotation algo // simple reverse rotation algo default: $i = 0; for ($y = $min_y2; $y < $max_y2; $y++) { // Algebra :) $x2 = round(($min_x2 - $x1) * $cosT + (($y - $y1) * $sinT + $x1), 0); $y2 = round(($y - $y1) * $cosT - ($min_x2 - $x1) * $sinT + $y1, 0); for ($x = $min_x2; $x < $max_x2; $x++) { // Check if we are out of original bounces, if we are // use the default color mask if ($x2 >= 0 && $x2 < $max_x && $y2 >= 0 && $y2 < $max_y) { $c = imagecolorat($img, $x2, $y2); } else { $c = $mask; } imagesetpixel($img2, $x + $x_offset, $y + $y_offset, $c); // round verboten! $x2 += $cosT; $y2 -= $sinT; } } break; } $this->old_image = $this->imageHandle; $this->imageHandle = $img2; return true; }
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $height_ori - $new_h, $new_w, $new_h, $new_w, $new_h); } elseif ($thumbdetail == 4) { imagecopyresampled($dst_img, $src_img, 0, 0, $width_ori - $new_w, $height_ori - $new_h, $new_w, $new_h, $new_w, $new_h); } else { imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, $width_ori, $height_ori); } } $img = imagegif($dst_img); imagedestroy($src_img); imagedestroy($dst_img); imagedestroy($img); } elseif (substr($_GET['img'], -3) == 'png') { header('Content-type: image/png'); $src_img = imagecreatefrompng($_image_); $dst_img = imagecreatetruecolor($new_w, $new_h); imagepalettecopy($dst_img, $src_img); if ($crop and ($crop_factor > 0 and $crop_factor < 100)) { imagecopyresampled($dst_img, $src_img, 0, 0, $x_coordinate, $y_coordinate, $new_w, $new_h, $crop_width, $crop_height); } else { if ($thumbdetail == 1) { imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, $new_w, $new_h); } elseif ($thumbdetail == 2) { imagecopyresampled($dst_img, $src_img, 0, 0, $width_ori - $new_w, 0, $new_w, $new_h, $new_w, $new_h); } elseif ($thumbdetail == 3) { imagecopyresampled($dst_img, $src_img, 0, 0, 0, $height_ori - $new_h, $new_w, $new_h, $new_w, $new_h); } elseif ($thumbdetail == 4) { imagecopyresampled($dst_img, $src_img, 0, 0, $width_ori - $new_w, $height_ori - $new_h, $new_w, $new_h, $new_w, $new_h); } else { imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $new_w, $new_h, $width_ori, $height_ori); } }
header("content-Type: image/jpeg"); header("cache-control: no-cache"); imageJpeg($dst_im); imagedestroy($src_im); imagedestroy($dst_im); break; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // png形式 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // png形式 case "3": $src_im = imagecreatefrompng($photo_path); $colortransparent = imagecolortransparent($src_im); if ($colortransparent > -1) { $dst_im = $imagecreate($re_size[0], $re_size[1]); imagepalettecopy($dst_im, $src_im); imagefill($dst_im, 0, 0, $colortransparent); imagecolortransparent($dst_im, $colortransparent); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); } else { $dst_im = $imagecreate($re_size[0], $re_size[1]); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); imagetruecolortopalette($dst_im, false, imagecolorstotal($src_im)); } header("content-Type: image/png"); header("cache-control: no-cache"); imagepng($dst_im); imagedestroy($src_im); imagedestroy($dst_im); break; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function ResizeImageFile($sourceFile, &$destinationFile, $arSize, $resizeType = BX_RESIZE_IMAGE_PROPORTIONAL, $arWaterMark = array(), $jpgQuality = false, $arFilters = false) { $io = CBXVirtualIo::GetInstance(); if (!$io->FileExists($sourceFile)) { return false; } $bNeedCreatePicture = false; if ($resizeType != BX_RESIZE_IMAGE_EXACT && $resizeType != BX_RESIZE_IMAGE_PROPORTIONAL_ALT) { $resizeType = BX_RESIZE_IMAGE_PROPORTIONAL; } if (!is_array($arSize)) { $arSize = array(); } if (!array_key_exists("width", $arSize) || intval($arSize["width"]) <= 0) { $arSize["width"] = 0; } if (!array_key_exists("height", $arSize) || intval($arSize["height"]) <= 0) { $arSize["height"] = 0; } $arSize["width"] = intval($arSize["width"]); $arSize["height"] = intval($arSize["height"]); $arSourceSize = array("x" => 0, "y" => 0, "width" => 0, "height" => 0); $arDestinationSize = array("x" => 0, "y" => 0, "width" => 0, "height" => 0); $arSourceFileSizeTmp = CFile::GetImageSize($sourceFile); if (!in_array($arSourceFileSizeTmp[2], array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_BMP))) { return false; } if (class_exists("imagick") && function_exists('memory_get_usage')) { //When memory limit reached we'll try to use ImageMagic $memoryNeeded = round(($arSourceFileSizeTmp[0] * $arSourceFileSizeTmp[1] * $arSourceFileSizeTmp['bits'] * ($arSourceFileSizeTmp['channels'] > 0 ? $arSourceFileSizeTmp['channels'] : 1) / 8 + pow(2, 16)) * 1.65); $memoryLimit = CUtil::Unformat(ini_get('memory_limit')); if (memory_get_usage() + $memoryNeeded > $memoryLimit) { if ($arSize["width"] <= 0 || $arSize["height"] <= 0) { $arSize["width"] = $arSourceFileSizeTmp[0]; $arSize["height"] = $arSourceFileSizeTmp[1]; } CFile::ScaleImage($arSourceFileSizeTmp[0], $arSourceFileSizeTmp[1], $arSize, $resizeType, $bNeedCreatePicture, $arSourceSize, $arDestinationSize); if ($bNeedCreatePicture) { $new_image = CTempFile::GetFileName(bx_basename($sourceFile)); CheckDirPath($new_image); $im = new Imagick(); try { $im->setSize($arDestinationSize["width"], $arDestinationSize["height"]); $im->readImage($io->GetPhysicalName($sourceFile)); $im->setImageFileName($new_image); $im->thumbnailImage($arDestinationSize["width"], $arDestinationSize["height"], true); $im->writeImage(); $im->destroy(); } catch (ImagickException $e) { $new_image = ""; } if ($new_image != "") { $sourceFile = $new_image; $arSourceFileSizeTmp = CFile::GetImageSize($io->GetPhysicalName($sourceFile)); } } } } if ($io->Copy($sourceFile, $destinationFile)) { switch ($arSourceFileSizeTmp[2]) { case IMAGETYPE_GIF: $sourceImage = imagecreatefromgif($io->GetPhysicalName($sourceFile)); $bHasAlpha = true; break; case IMAGETYPE_PNG: $sourceImage = imagecreatefrompng($io->GetPhysicalName($sourceFile)); $bHasAlpha = true; break; case IMAGETYPE_BMP: $sourceImage = CFile::ImageCreateFromBMP($io->GetPhysicalName($sourceFile)); $bHasAlpha = false; break; default: $sourceImage = imagecreatefromjpeg($io->GetPhysicalName($sourceFile)); $bHasAlpha = false; break; } $sourceImageWidth = intval(imagesx($sourceImage)); $sourceImageHeight = intval(imagesy($sourceImage)); if ($sourceImageWidth > 0 && $sourceImageHeight > 0) { if ($arSize["width"] <= 0 || $arSize["height"] <= 0) { $arSize["width"] = $sourceImageWidth; $arSize["height"] = $sourceImageHeight; } CFile::ScaleImage($sourceImageWidth, $sourceImageHeight, $arSize, $resizeType, $bNeedCreatePicture, $arSourceSize, $arDestinationSize); if ($bNeedCreatePicture) { if (CFile::IsGD2()) { $picture = ImageCreateTrueColor($arDestinationSize["width"], $arDestinationSize["height"]); if ($arSourceFileSizeTmp[2] == IMAGETYPE_PNG) { $transparentcolor = imagecolorallocatealpha($picture, 0, 0, 0, 127); imagefilledrectangle($picture, 0, 0, $arDestinationSize["width"], $arDestinationSize["height"], $transparentcolor); imagealphablending($picture, false); imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); imagealphablending($picture, true); } elseif ($arSourceFileSizeTmp[2] == IMAGETYPE_GIF) { imagepalettecopy($picture, $sourceImage); //Save transparency for GIFs $transparentcolor = imagecolortransparent($sourceImage); if ($transparentcolor >= 0 && $transparentcolor < imagecolorstotal($sourceImage)) { $RGB = imagecolorsforindex($sourceImage, $transparentcolor); $transparentcolor = imagecolorallocate($picture, $RGB["red"], $RGB["green"], $RGB["blue"]); imagecolortransparent($picture, $transparentcolor); imagefilledrectangle($picture, 0, 0, $arDestinationSize["width"], $arDestinationSize["height"], $transparentcolor); } imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); } else { imagecopyresampled($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); } } else { $picture = ImageCreate($arDestinationSize["width"], $arDestinationSize["height"]); imagecopyresized($picture, $sourceImage, 0, 0, $arSourceSize["x"], $arSourceSize["y"], $arDestinationSize["width"], $arDestinationSize["height"], $arSourceSize["width"], $arSourceSize["height"]); } } else { $picture = $sourceImage; } if (is_array($arFilters)) { foreach ($arFilters as $arFilter) { $bNeedCreatePicture |= CFile::ApplyImageFilter($picture, $arFilter, $bHasAlpha); } } if (is_array($arWaterMark)) { $arWaterMark["name"] = "watermark"; $bNeedCreatePicture |= CFile::ApplyImageFilter($picture, $arWaterMark, $bHasAlpha); } if ($bNeedCreatePicture) { if ($io->FileExists($destinationFile)) { $io->Delete($destinationFile); } switch ($arSourceFileSizeTmp[2]) { case IMAGETYPE_GIF: imagegif($picture, $io->GetPhysicalName($destinationFile)); break; case IMAGETYPE_PNG: imagealphablending($picture, false); imagesavealpha($picture, true); imagepng($picture, $io->GetPhysicalName($destinationFile)); break; default: if ($arSourceFileSizeTmp[2] == IMAGETYPE_BMP) { $destinationFile .= ".jpg"; } if ($jpgQuality === false) { $jpgQuality = intval(COption::GetOptionString('main', 'image_resize_quality', '95')); } if ($jpgQuality <= 0 || $jpgQuality > 100) { $jpgQuality = 95; } imagejpeg($picture, $io->GetPhysicalName($destinationFile), $jpgQuality); break; } imagedestroy($picture); } } return true; } return false; }
/** * <p>Функция выполняет масштабирование файла.</p> <p><b>Примечание</b>: обрабатываются только файлы JPEG, GIF и PNG (зависит от используемой библиотеки GD). Файл указанный в параметре arFile будет перезаписан. <br></p> * * * * * @param array $arFile Массив описывающий файл. Это может быть элемент массива $_FILES[имя] * (или $HTTP_POST_FILES[имя]), а также результат функции <a * href="http://dev.1c-bitrix.ru/api_help/main/reference/cfile/makefilearray.php">CFile::MakeFileArray</a>. * * * * @param array $arResize Массив параметров масштабирования. Содержит следующие ключи: * <br><ul> <li>WIDTH - целое число. Размер картинки будет изменен таким * образом, что ее ширина не будет превышать значения этого поля. <br> * </li> <li>HEIGHT - целое число. Размер картинки будет изменен таким * образом, что ее высота не будет превышать значения этого поля. </li> * <li>METHOD - возможные значения: resample или пусто. Значение поля равное * "resample" приведет к использованию функции масштабирования * imagecopyresampled, а не imagecopyresized. Это более качественный метод, но требует * больше серверных ресурсов. <br> </li> <li>COMPRESSION - целое от 0 до 100. Если * значение больше 0, то для изображений jpeg оно будет использовано * как параметр компрессии. 100 соответствует наилучшему качеству * при большем размере файла. </li> </ul> Параметры METHOD и COMPRESSION * применяются только если происходит изменение размера. Если * картинка вписывается в ограничения WIDTH и HEIGHT, то никаких действий * над файлом выполнено не будет. <br><br> * * * * @return array <p>Массив описывающий файл или строка с сообщением об ошибке.</p> * * * <h4>Example</h4> * <pre> * <?<br>AddEventHandler("iblock", "OnBeforeIBlockElementAdd", Array("MyHandlers", "ResizeElementProperty"));<br>AddEventHandler("iblock", "OnBeforeIBlockElementUpdate", Array("MyHandlers", "ResizeElementProperty"));<br><br>class MyHandlers<br>{<br> function ResizeElementProperty(&$arFields)<br> {<br> global $APPLICATION;<br> //Код инфоблока свойство каторого нуждается в масштабировании<br> $IBLOCK_ID = 1;<br> //Идентификатор свойства<br> $PROPERTY_ID = 15;<br> //Наш инфоблок и значения свойства в наличии<br> if(<br> $arFields["IBLOCK_ID"] == $IBLOCK_ID<br> && is_array($arFields["PROPERTY_VALUES"])<br> && array_key_exists(15, $arFields["PROPERTY_VALUES"])<br> )<br> {<br> foreach($arFields["PROPERTY_VALUES"][$PROPERTY_ID] as $key => $arFile)<br> {<br> //Изменяем размеры картинки<br> $arNewFile = CIBlock::ResizePicture($arFile, array(<br> "WIDTH" => 100,<br> "HEIGHT" => 100,<br> "METHOD" => "resample",<br> ));<br> if(is_array($arNewFile))<br> $arFields["PROPERTY_VALUES"][$PROPERTY_ID][$key] = $arNewFile;<br> else<br> {<br> //Можно вернуть ошибку<br> $APPLICATION->throwException("Ошибка масштабирования изображения в свойстве \"Файлы\":".$arNewFile);<br> return false;<br> }<br> }<br> }<br> }<br>}<br>?> * </pre> * * * * <h4>See Also</h4> * <ul> <li><a href="http://dev.1c-bitrix.ru/api_help/main/reference/cfile/makefilearray.php">CFile::MakeFileArray</a></li> * <li><a href="http://dev.1c-bitrix.ru/api_help/iblock/classes/ciblock/SetFields.php">CIBlock::SetFields</a></li> </ul><a * name="examples"></a> * * * @static * @link http://dev.1c-bitrix.ru/api_help/iblock/classes/ciblock/ResizePicture.php * @author Bitrix */ public static function ResizePicture($arFile, $arResize) { if (strlen($arFile["tmp_name"]) <= 0) { return $arFile; } if (array_key_exists("error", $arFile) && $arFile["error"] !== 0) { return GetMessage("IBLOCK_BAD_FILE_ERROR"); } $file = $arFile["tmp_name"]; if (!file_exists($file) && !is_file($file)) { return GetMessage("IBLOCK_BAD_FILE_NOT_FOUND"); } $width = intval($arResize["WIDTH"]); $height = intval($arResize["HEIGHT"]); if ($width <= 0 && $height <= 0) { return $arFile; } $orig = CFile::GetImageSize($file, true); if (!is_array($orig)) { return GetMessage("IBLOCK_BAD_FILE_NOT_PICTURE"); } if ($width > 0 && $orig[0] > $width || $height > 0 && $orig[1] > $height) { if ($arFile["COPY_FILE"] == "Y") { $new_file = CTempFile::GetFileName(basename($file)); CheckDirPath($new_file); $arFile["copy"] = true; if (copy($file, $new_file)) { $file = $new_file; } else { return GetMessage("IBLOCK_BAD_FILE_NOT_FOUND"); } } $width_orig = $orig[0]; $height_orig = $orig[1]; if ($width <= 0) { $width = $width_orig; } if ($height <= 0) { $height = $height_orig; } $height_new = $height_orig; if ($width_orig > $width) { $height_new = $width / $width_orig * $height_orig; } if ($height_new > $height) { $width = $height / $height_orig * $width_orig; } else { $height = $height_new; } $image_type = $orig[2]; if ($image_type == IMAGETYPE_JPEG) { $image = imagecreatefromjpeg($file); } elseif ($image_type == IMAGETYPE_GIF) { $image = imagecreatefromgif($file); } elseif ($image_type == IMAGETYPE_PNG) { $image = imagecreatefrompng($file); } else { return GetMessage("IBLOCK_BAD_FILE_UNSUPPORTED"); } $image_p = imagecreatetruecolor($width, $height); if ($image_type == IMAGETYPE_JPEG) { if ($arResize["METHOD"] === "resample") { imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); } else { imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); } if ($arResize["COMPRESSION"] > 0) { imagejpeg($image_p, $file, $arResize["COMPRESSION"]); } else { imagejpeg($image_p, $file); } } elseif ($image_type == IMAGETYPE_GIF && function_exists("imagegif")) { imagetruecolortopalette($image_p, true, imagecolorstotal($image)); imagepalettecopy($image_p, $image); //Save transparency for GIFs $transparentColor = imagecolortransparent($image); if ($transparentColor >= 0 && $transparentColor < imagecolorstotal($image)) { $transparentColor = imagecolortransparent($image_p, $transparentColor); imagefilledrectangle($image_p, 0, 0, $width, $height, $transparentColor); } if ($arResize["METHOD"] === "resample") { imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); } else { imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); } imagegif($image_p, $file); } else { //Save transparency for PNG $transparentColor = imagecolorallocatealpha($image_p, 0, 0, 0, 127); imagefilledrectangle($image_p, 0, 0, $width, $height, $transparentColor); $transparentColor = imagecolortransparent($image_p, $transparentColor); imagealphablending($image_p, false); if ($arResize["METHOD"] === "resample") { imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); } else { imagecopyresized($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); } imagesavealpha($image_p, true); imagepng($image_p, $file); } imagedestroy($image); imagedestroy($image_p); $arFile["size"] = filesize($file); $arFile["tmp_name"] = $file; return $arFile; } else { return $arFile; } }
/** * Resize image * * @access public * @param int $new_width (px) * @param int $new_height (px) * @proportional bool $proportional */ public function resize($new_width = null, $new_height = null, $mode = 'auto') { if (is_null($new_width) and is_null($new_height)) { throw new \Exception('specifiy output dimensions'); } list($output_width, $output_height) = $this->get_output_dimensions($new_width, $new_height, $mode); $this->image_resized = imagecreatetruecolor($output_width, $output_height); if ($this->mime_type == 'image/gif' or $this->mime_type == 'image/png') { $transparent_index = imagecolortransparent($this->image); if ($transparent_index >= 0) { // GIF imagepalettecopy($this->image, $this->image_resized); imagefill($this->image_resized, 0, 0, $transparent_index); imagecolortransparent($this->image_resized, $transparent_index); imagetruecolortopalette($this->image_resized, true, 256); } else { // PNG imagealphablending($this->image_resized, false); imagesavealpha($this->image_resized, true); $transparent = imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127); imagefilledrectangle($this->image_resized, 0, 0, $output_width, $output_height, $transparent); } } imagecopyresampled($this->image_resized, $this->image, 0, 0, 0, 0, $output_width, $output_height, $this->width, $this->height); if ($mode == 'crop') { $this->crop($output_width, $output_height, $new_width, $new_height); } }
function GenerateThumbFile($from_name, $to_name) { // if src is URL then download file first $temp = false; if (substr($from_name, 0, 7) == 'http://') { $tmpfname = tempnam("tmp/", "TmP-"); $temp = @fopen($tmpfname, "w"); if ($temp) { @fwrite($temp, @file_get_contents($from_name)) or die("Cannot download image"); @fclose($temp); $from_name = $tmpfname; } else { die("Cannot create temp file"); } } // check if file exists if (!file_exists($from_name)) { die("Source image does not exist!"); } // get source image size (width/height/type) // orig_img_type 1 = GIF, 2 = JPG, 3 = PNG list($orig_x, $orig_y, $orig_img_type, $img_sizes) = @GetImageSize($from_name); // cut image if specified by user if ($this->cut_x > 0) { $orig_x = min($this->cut_x, $orig_x); } if ($this->cut_y > 0) { $orig_y = min($this->cut_y, $orig_y); } // should we override thumb image type? $this->image_type = $this->image_type != -1 ? $this->image_type : $orig_img_type; // check for allowed image types if ($orig_img_type < 1 or $orig_img_type > 3) { die("Image type not supported"); } if ($orig_x > $this->max_x or $orig_y > $this->max_y) { // resize $per_x = $orig_x / $this->max_x; $per_y = $orig_y / $this->max_y; if ($per_y > $per_x) { $this->max_x = $orig_x / $per_y; } else { $this->max_y = $orig_y / $per_x; } } else { // keep original sizes, i.e. just copy if ($this->save_to_file) { @copy($from_name, $to_name); } else { switch ($this->image_type) { case 1: header("Content-type: image/gif"); readfile($from_name); break; case 2: header("Content-type: image/jpeg"); readfile($from_name); break; case 3: header("Content-type: image/png"); readfile($from_name); break; } } return; } if ($this->image_type == 1) { // should use this function for gifs (gifs are palette images) $ni = imagecreate($this->max_x, $this->max_y); } else { // Create a new true color image $ni = ImageCreateTrueColor($this->max_x, $this->max_y); } // Fill image with white background (255,255,255) $white = imagecolorallocate($ni, 255, 255, 255); imagefilledrectangle($ni, 0, 0, $this->max_x, $this->max_y, $white); // Create a new image from source file $im = $this->ImageCreateFromType($orig_img_type, $from_name); // Copy the palette from one image to another imagepalettecopy($ni, $im); // Copy and resize part of an image with resampling imagecopyresampled($ni, $im, 0, 0, 0, 0, $this->max_x, $this->max_y, $orig_x, $orig_y); // srcW, srcH // save thumb file $this->SaveImage($ni, $to_name); if ($temp) { unlink($tmpfname); // this removes the file } }
protected function convertGdObject($gdObject) { //create new object with restricted palette $newObject = imagecreate($this->width, $this->height); $width = imagesx($gdObject); $height = imagesy($gdObject); //create separate resource for palette holding. //this cannot be created in $newObject unfortunately due to GD conversion bug, //so we have to use intermediate object $palette = imagecreate($this->width, $this->height); //assign sxg palette colors to palette holding resource foreach ($this->splittedRgbPalette as $color) { imagecolorallocate($palette, $color[0], $color[1], $color[2]); } //here is the trick: assign palette before copying imagepalettecopy($newObject, $palette); //copy truecolor source to our new object with resampling. colors get replaced with palette as well. imagecopyresampled($newObject, $gdObject, 0, 0, 0, 0, $this->width, $this->height, $width, $height); //trick: assign palette after copying as well imagepalettecopy($newObject, $palette); // header('Content-type: image/png'); // imagepng($newObject); // exit; return $newObject; }
function GenerateThumbFile($from_name1, $to_name, $max_x, $max_y, $filename) { // if src is URL then download file first if (defined('USE_S3') && USE_S3 && $filename != 'user.png') { $from_name = $this->generateTemporaryURL($from_name1); //print_r($from_name);exit; } else { $from_name = $from_name1; } $temp = false; if (substr($from_name, 0, 7) == 'https://') { $tmpfname = tempnam("tmp/", "TmP-"); $temp = @fopen($tmpfname, "w"); if ($temp) { @fwrite($temp, @file_get_contents($from_name)) or die("Cannot download image"); @fclose($temp); $from_name = $tmpfname; } else { die("Cannot create temp file"); } } // check if file exists if (defined('USE_S3') && USE_S3 && $filename != 'user.png') { $s3 = new S3(awsAccessKey, awsSecretKey); $info = $s3->getObjectInfo(BUCKET_NAME, DIR_USER_PHOTOS_S3_FOLDER . $filename); //print_r($info); $file_mime = $info['type']; } else { if (file_exists($from_name)) { $info = 1; } else { if (file_exists(DIR_USER_PHOTOS . 'user.png')) { $from_name = DIR_USER_PHOTOS . 'user.png'; $info = 1; } } } if ($info) { // get source image size (width/height/type) // orig_img_type 1 = GIF, 2 = JPG, 3 = PNG $getimagesize = @getimagesize($from_name); //list($orig_x, $orig_y, $orig_img_type, $img_sizes) = @getimagesize($from_name); $orig_x = $getimagesize[0]; $orig_y = $getimagesize[1]; $orig_img_type = $getimagesize['2']; if (!$file_mime) { $file_mime = $getimagesize['mime']; } // cut image if specified by user if ($this->cut_x > 0) { $orig_x = min($this->cut_x, $orig_x); } if ($this->cut_y > 0) { $orig_y = min($this->cut_y, $orig_y); } // should we override thumb image type? $this->image_type = $this->image_type != -1 ? $this->image_type : $orig_img_type; // check for allowed image types if ($orig_img_type < 1 or $orig_img_type > 3) { die("Image type not supported"); } if ($orig_x > $max_x or $orig_y > $max_y) { if (!$file_mime) { $file_mime = @finfo_file(finfo_open(FILEINFO_MIME_TYPE), $from_name); } if ($file_mime) { header("Content-Type:{$file_mime}"); } // resize $per_x = $orig_x / $max_x; $per_y = $orig_y / $max_y; if ($per_y > $per_x) { $max_x = $orig_x / $per_y; } else { $max_y = $orig_y / $per_x; } } else { if ($orig_x < $max_x or $orig_y < $max_y) { $max_x = $orig_x; $max_y = $orig_y; if (!$file_mime) { $file_mime = @finfo_file(finfo_open(FILEINFO_MIME_TYPE), $from_name); } if ($file_mime) { header("Content-Type:{$file_mime}"); } } else { // keep original sizes, i.e. just copy if ($this->save_to_file) { @copy($from_name, $to_name); } else { switch ($this->image_type) { case 1: header("Content-type: image/gif"); readfile($from_name); break; case 2: header("Content-type: image/jpeg"); readfile($from_name); break; case 3: header("Content-type: image/png"); readfile($from_name); break; } } return; } } if ($this->image_type == 1) { // should use this function for gifs (gifs are palette images) $ni = imagecreate($max_x, $max_y); } else { // Create a new true color image $ni = ImageCreateTrueColor($max_x, $max_y); } // Fill image with white background (255,255,255) $white = imagecolorallocate($ni, 255, 255, 255); /* if($this->image_type == 3) { $white = imagecolorallocate($ni, 0, 0, 0); imagecolortransparent($ni, $white); } */ imagefilledrectangle($ni, 0, 0, $max_x, $max_y, $white); // Create a new image from source file $im = $this->ImageCreateFromType($orig_img_type, $from_name); // Copy the palette from one image to another imagepalettecopy($ni, $im); // Copy and resize part of an image with resampling imagecopyresampled($ni, $im, 0, 0, 0, 0, $max_x, $max_y, $orig_x, $orig_y); // srcW, srcH // save thumb file $this->SaveImage($ni, $to_name); if ($temp) { unlink($tmpfname); // this removes the file } } else { //File doesn't exists echo "Source image does not exist!"; exit; } }
/** * Actually uploads the file, and act on it according to the set processing class variables * * This function copies the uploaded file to the given location, eventually performing actions on it. * Typically, you can call {@link process} several times for the same file, * for instance to create a resized image and a thumbnail of the same file. * The original uploaded file remains intact in its temporary location, so you can use {@link process} several times. * You will be able to delete the uploaded file with {@link clean} when you have finished all your {@link process} calls. * * According to the processing class variables set in the calling file, the file can be renamed, * and if it is an image, can be resized or converted. * * When the processing is completed, and the file copied to its new location, the * processing class variables will be reset to their default value. * This allows you to set new properties, and perform another {@link process} on the same uploaded file * * It will set {@link processed} (and {@link error} is an error occurred) * * @access public * @param string $server_path Path location of the uploaded file, with an ending slash */ function process($server_path) { $this->error = ''; $this->processed = true; if (strtolower(substr(PHP_OS, 0, 3)) === 'win') { if (substr($server_path, -1, 1) != '\\') { $server_path = $server_path . '\\'; } } else { if (substr($server_path, -1, 1) != '/') { $server_path = $server_path . '/'; } } $this->log .= '<b>' . _("process file to") . ' ' . $server_path . '</b><br />'; // checks file size and mine type if ($this->uploaded) { if ($this->file_src_size > $this->file_max_size) { $this->processed = false; $this->error = _(MSG019); } else { $this->log .= '- ' . _("file size OK") . '<br />'; } // turn dangerous scripts into text files if ($this->no_script) { if ((substr($this->file_src_mime, 0, 5) == 'text/' || strpos($this->file_src_mime, 'javascript') !== false) && substr($this->file_src_name, -4) != '.txt' || preg_match('/\\.(php|pl|py|cgi|asp)$/i', $this->file_src_name) || empty($this->file_src_name_ext)) { $this->file_src_mime = 'text/plain'; $this->log .= '- ' . _("script") . ' ' . $this->file_src_name . ' ' . _("renamed as") . ' ' . $this->file_src_name . '.txt!<br />'; $this->file_src_name_ext .= empty($this->file_src_name_ext) ? 'txt' : '.txt'; } } // checks MIME type with mime_magic if ($this->mime_magic_check && function_exists('mime_content_type')) { $detected_mime = mime_content_type($this->file_src_pathname); if ($this->file_src_mime != $detected_mime) { $this->log .= '- ' . _("MIME type detected as") . ' ' . $detected_mime . ' ' . _("but given as") . ' ' . $this->file_src_mime . '!<br />'; $this->file_src_mime = $detected_mime; } } if ($this->mime_check && empty($this->file_src_mime)) { $this->processed = false; $this->error = _("MIME type can't be detected!"); } else { if ($this->mime_check && !empty($this->file_src_mime) && !array_key_exists($this->file_src_mime, array_flip($this->allowed))) { $this->processed = false; $this->error = _("Incorrect type of file"); } else { $this->log .= '- ' . _("file mime OK") . ' : ' . $this->file_src_mime . '<br />'; } } } else { $this->error = _("File not uploaded. Can't carry on a process"); $this->processed = false; } if ($this->processed) { $this->file_dst_path = $server_path; // repopulate dst variables from src $this->file_dst_name = $this->file_src_name; $this->file_dst_name_body = $this->file_src_name_body; $this->file_dst_name_ext = $this->file_src_name_ext; if ($this->file_new_name_body != '') { // rename file body $this->file_dst_name_body = $this->file_new_name_body; $this->log .= '- ' . _("new file name body") . ' : ' . $this->file_new_name_body . '<br />'; } if ($this->file_new_name_ext != '') { // rename file ext $this->file_dst_name_ext = $this->file_new_name_ext; $this->log .= '- ' . _("new file name ext") . ' : ' . $this->file_new_name_ext . '<br />'; } if ($this->file_name_body_add != '') { // append a bit to the name $this->file_dst_name_body = $this->file_dst_name_body . $this->file_name_body_add; $this->log .= '- ' . _("file name body add") . ' : ' . $this->file_name_body_add . '<br />'; } if ($this->file_safe_name) { // formats the name $this->file_dst_name_body = str_replace(array(' ', '-'), array('_', '_'), $this->file_dst_name_body); $this->file_dst_name_body = ereg_replace('[^A-Za-z0-9_]', '', $this->file_dst_name_body); $this->log .= '- ' . _("file name safe format") . '<br />'; } $this->log .= '- ' . _("destination variables") . '<br />'; $this->log .= ' file_dst_path : ' . $this->file_dst_path . '<br />'; $this->log .= ' file_dst_name_body : ' . $this->file_dst_name_body . '<br />'; $this->log .= ' file_dst_name_ext : ' . $this->file_dst_name_ext . '<br />'; // do we do some image manipulation? $image_manipulation = $this->image_resize || $this->image_convert != '' || is_numeric($this->image_brightness) || is_numeric($this->image_contrast) || is_numeric($this->image_threshold) || !empty($this->image_tint_color) || !empty($this->image_overlay_color) || !empty($this->image_text) || $this->image_greyscale || $this->image_negative || !empty($this->image_watermark) || is_numeric($this->image_rotate) || is_numeric($this->jpeg_size) || !empty($this->image_flip) || !empty($this->image_crop) || !empty($this->image_border) || $this->image_frame > 0 || $this->image_bevel > 0 || $this->image_reflection_height; if ($image_manipulation) { if ($this->image_convert == '') { $this->file_dst_name = $this->file_dst_name_body . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''); $this->log .= '- ' . _("image operation, keep extension") . '<br />'; } else { $this->file_dst_name = $this->file_dst_name_body . '.' . $this->image_convert; $this->log .= '- ' . _("image operation, change extension for conversion type") . '<br />'; } } else { $this->file_dst_name = $this->file_dst_name_body . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''); $this->log .= '- ' . _("no image operation, keep extension") . '<br />'; } if (!$this->file_auto_rename) { $this->log .= '- ' . _("no auto_rename if same filename exists") . '<br />'; $this->file_dst_pathname = $this->file_dst_path . $this->file_dst_name; } else { $this->log .= '- ' . _("checking for auto_rename") . '<br />'; $this->file_dst_pathname = $this->file_dst_path . $this->file_dst_name; $body = $this->file_dst_name_body; $cpt = 1; while (@file_exists($this->file_dst_pathname)) { $this->file_dst_name_body = $body . '_' . $cpt; $this->file_dst_name = $this->file_dst_name_body . (!empty($this->file_dst_name_ext) ? '.' . $this->file_dst_name_ext : ''); $cpt++; $this->file_dst_pathname = $this->file_dst_path . $this->file_dst_name; } if ($cpt > 1) { $this->log .= ' ' . _("auto_rename to") . ' ' . $this->file_dst_name . '<br />'; } } $this->log .= '- ' . _("destination file details") . '<br />'; $this->log .= ' file_dst_name : ' . $this->file_dst_name . '<br />'; $this->log .= ' file_dst_pathname : ' . $this->file_dst_pathname . '<br />'; if ($this->file_overwrite) { $this->log .= '- ' . _("no overwrite checking") . '<br />'; } else { if (@file_exists($this->file_dst_pathname)) { $this->processed = false; $this->error = $this->file_dst_name . ' ' . _("already exists. Please change the file name"); } else { $this->log .= '- ' . $this->file_dst_name . ' ' . _("doesn't exist already") . '<br />'; } } } else { $this->processed = false; } if (!$this->no_upload_check && !is_uploaded_file($this->file_src_pathname)) { $this->processed = false; $this->error = _("No correct source file. Can't carry on a process"); } // checks if the destination directory exists, and attempt to create it if ($this->processed && !file_exists($this->file_dst_path)) { if ($this->dir_auto_create) { $this->log .= '- ' . $this->file_dst_path . ' ' . _("doesn't exist. Attempting creation:"); if (!$this->r_mkdir($this->file_dst_path, $this->dir_chmod)) { $this->log .= ' ' . _("failed") . '<br />'; $this->processed = false; $this->error = _("Destination directory can't be created. Can't carry on a process"); } else { $this->log .= ' ' . _("success") . '<br />'; } } else { $this->error = _("Destination directory doesn't exist. Can't carry on a process"); } } if ($this->processed && !is_dir($this->file_dst_path)) { $this->processed = false; $this->error = _("Destination path is not a directory. Can't carry on a process"); } // checks if the destination directory is writeable, and attempt to make it writeable $hash = md5($this->file_dst_name_body . rand(1, 1000)); if ($this->processed && !($f = @fopen($this->file_dst_path . $hash . '.' . $this->file_dst_name_ext, 'a+'))) { if ($this->dir_auto_chmod) { $this->log .= '- ' . $this->file_dst_path . ' ' . _("is not writeable. Attempting chmod:"); if (!@chmod($this->file_dst_path, $this->dir_chmod)) { $this->log .= ' ' . _("failed") . '<br />'; $this->processed = false; $this->error = _("Destination directory can't be made writeable. Can't carry on a process"); } else { $this->log .= ' ' . _("success") . '<br />'; if (!($f = @fopen($this->file_dst_path . $hash . '.' . $this->file_dst_name_ext, 'a+'))) { // we re-check $this->processed = false; $this->error = _("Destination directory is still not writeable. Can't carry on a process"); } else { @fclose($f); } } } else { $this->processed = false; $this->error = _("Destination path is not a writeable. Can't carry on a process"); } } else { @fclose($f); @unlink($this->file_dst_path . $hash . '.' . $this->file_dst_name_ext); } if ($this->processed) { if ($image_manipulation) { // we have a writeable destination, but we need to check if we can read the file directly // if we can't (open_basedir, etc...), we will copy it with a temporary name $has_temp_file = false; if ($this->processed && !file_exists($this->file_src_pathname)) { $this->log .= '- ' . _("can't directly access the uploaded file" . '<br />'); $this->log .= ' ' . _("attempting creating a temp file:"); $hash = md5($this->file_dst_name_body . rand(1, 1000)); if (move_uploaded_file($this->file_src_pathname, $this->file_dst_path . $hash . '.' . $this->file_dst_name_ext)) { $this->file_src_pathname = $this->file_dst_path . $hash . '.' . $this->file_dst_name_ext; $this->log .= ' ' . _("file created") . '<br />'; $this->log .= ' ' . _("temp file is:") . ' ' . $this->file_src_pathname . '<br />'; $has_temp_file = true; } else { $this->log .= ' ' . _("failed") . '<br />'; $this->processed = false; $this->error = _("Can't create the temporary file. Can't carry on a process"); } } // checks if the source file is readable if ($this->processed && !($f = @fopen($this->file_src_pathname, 'r'))) { $this->processed = false; $this->error = _("Source file is not readable. Can't carry on a process"); } else { @fclose($f); } // we now do all the image manipulations $this->log .= '- ' . _("image resizing or conversion wanted") . '<br />'; if ($this->gd_version()) { switch ($this->file_src_mime) { case 'image/pjpeg': case 'image/jpeg': case 'image/jpg': if (!function_exists('imagecreatefromjpeg')) { $this->processed = false; $this->error = _("No create from JPEG support"); } else { $image_src = @imagecreatefromjpeg($this->file_src_pathname); if (!$image_src) { $this->processed = false; $this->error = _("Error in creating JPEG image from source"); } else { $this->log .= '- ' . _("source image is JPEG") . '<br />'; } } break; case 'image/x-png': case 'image/png': if (!function_exists('imagecreatefrompng')) { $this->processed = false; $this->error = _("No create from PNG support"); } else { $image_src = @imagecreatefrompng($this->file_src_pathname); if (!$image_src) { $this->processed = false; $this->error = _("Error in creating PNG image from source"); } else { $this->log .= '- ' . _("source image is PNG") . '<br />'; } } break; case 'image/gif': if (!function_exists('imagecreatefromgif')) { $this->processed = false; $this->error = _("Error in creating GIF image from source"); } else { $image_src = @imagecreatefromgif($this->file_src_pathname); if (!$image_src) { $this->processed = false; $this->error = _("No GIF read support"); } else { $this->log .= '- ' . _("source image is GIF") . '<br />'; } } break; default: $this->processed = false; $this->error = _(MSG012); } } else { $this->processed = false; $this->error = _("GD doesn't seem to be present"); } if ($this->processed && $image_src) { $this->image_src_x = imagesx($image_src); $this->image_src_y = imagesy($image_src); $this->image_dst_x = $this->image_src_x; $this->image_dst_y = $this->image_src_y; $gd_version = $this->gd_version(); $ratio_crop = null; if ($this->image_resize) { $this->log .= '- ' . _("resizing...") . '<br />'; if ($this->image_ratio_x) { $this->log .= ' ' . _("calculate x size") . '<br />'; $this->image_dst_x = round($this->image_src_x * $this->image_y / $this->image_src_y); $this->image_dst_y = $this->image_y; } else { if ($this->image_ratio_y) { $this->log .= ' ' . _("calculate y size") . '<br />'; $this->image_dst_x = $this->image_x; $this->image_dst_y = round($this->image_src_y * $this->image_x / $this->image_src_x); } else { if ($this->image_ratio || $this->image_ratio_crop || $this->image_ratio_no_zoom_in || $this->image_ratio_no_zoom_out) { $this->log .= ' ' . _("check x/y sizes") . '<br />'; if (!$this->image_ratio_no_zoom_in && !$this->image_ratio_no_zoom_out || $this->image_ratio_no_zoom_in && ($this->image_src_x > $this->image_x || $this->image_src_y > $this->image_y) || $this->image_ratio_no_zoom_out && $this->image_src_x < $this->image_x && $this->image_src_y < $this->image_y) { $this->image_dst_x = $this->image_x; $this->image_dst_y = $this->image_y; if ($this->image_ratio_crop) { if (!is_string($this->image_ratio_crop)) { $this->image_ratio_crop = ''; } $this->image_ratio_crop = strtolower($this->image_ratio_crop); if ($this->image_src_x / $this->image_x > $this->image_src_y / $this->image_y) { $this->image_dst_y = $this->image_y; $this->image_dst_x = intval($this->image_src_x * ($this->image_y / $this->image_src_y)); $ratio_crop = array(); $ratio_crop['x'] = $this->image_dst_x - $this->image_x; if (strpos($this->image_ratio_crop, 'l') !== false) { $ratio_crop['l'] = 0; $ratio_crop['r'] = $ratio_crop['x']; } else { if (strpos($this->image_ratio_crop, 'r') !== false) { $ratio_crop['l'] = $ratio_crop['x']; $ratio_crop['r'] = 0; } else { $ratio_crop['l'] = round($ratio_crop['x'] / 2); $ratio_crop['r'] = $ratio_crop['x'] - $ratio_crop['l']; } } $this->log .= ' ' . _("ratio_crop_x") . ' : ' . $ratio_crop['x'] . ' (' . $ratio_crop['l'] . ';' . $ratio_crop['r'] . ')<br />'; if (is_null($this->image_crop)) { $this->image_crop = array(0, 0, 0, 0); } } else { $this->image_dst_x = $this->image_x; $this->image_dst_y = intval($this->image_src_y * ($this->image_x / $this->image_src_x)); $ratio_crop = array(); $ratio_crop['y'] = $this->image_dst_y - $this->image_y; if (strpos($this->image_ratio_crop, 't') !== false) { $ratio_crop['t'] = 0; $ratio_crop['b'] = $ratio_crop['y']; } else { if (strpos($this->image_ratio_crop, 'b') !== false) { $ratio_crop['t'] = $ratio_crop['y']; $ratio_crop['b'] = 0; } else { $ratio_crop['t'] = round($ratio_crop['y'] / 2); $ratio_crop['b'] = $ratio_crop['y'] - $ratio_crop['t']; } } $this->log .= ' ' . _("ratio_crop_y") . ' : ' . $ratio_crop['y'] . ' (' . $ratio_crop['t'] . ';' . $ratio_crop['b'] . ')<br />'; if (is_null($this->image_crop)) { $this->image_crop = array(0, 0, 0, 0); } } } else { if ($this->image_src_x / $this->image_x > $this->image_src_y / $this->image_y) { $this->image_dst_x = $this->image_x; $this->image_dst_y = intval($this->image_src_y * ($this->image_x / $this->image_src_x)); } else { $this->image_dst_y = $this->image_y; $this->image_dst_x = intval($this->image_src_x * ($this->image_y / $this->image_src_y)); } } } else { $this->log .= ' ' . _("doesn't calculate x/y sizes") . '<br />'; $this->image_dst_x = $this->image_src_x; $this->image_dst_y = $this->image_src_y; } } else { $this->log .= ' ' . _("use plain sizes") . '<br />'; $this->image_dst_x = $this->image_x; $this->image_dst_y = $this->image_y; } } } if ($this->preserve_transparency && $this->file_src_mime != 'image/gif' && $this->file_src_mime != 'image/png') { $this->preserve_transparency = false; } if ($gd_version >= 2 && !$this->preserve_transparency) { $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); } else { $image_dst = imagecreate($this->image_dst_x, $this->image_dst_y); } if ($this->preserve_transparency) { $this->log .= '- ' . _("preserve transparency") . '<br />'; $transparent_color = imagecolortransparent($image_src); imagepalettecopy($image_dst, $image_src); imagefill($image_dst, 0, 0, $transparent_color); imagecolortransparent($image_dst, $transparent_color); } if ($gd_version >= 2 && !$this->preserve_transparency) { $res = imagecopyresampled($image_dst, $image_src, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, $this->image_src_x, $this->image_src_y); } else { $res = imagecopyresized($image_dst, $image_src, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, $this->image_src_x, $this->image_src_y); } $this->log .= ' ' . _("resized image object created") . '<br />'; $this->log .= ' image_src_x y : ' . $this->image_src_x . ' x ' . $this->image_src_y . '<br />'; $this->log .= ' image_dst_x y : ' . $this->image_dst_x . ' x ' . $this->image_dst_y . '<br />'; } else { // we only convert, so we link the dst image to the src image $image_dst =& $image_src; } // we have to set image_convert if it is not already if (empty($this->image_convert)) { $this->log .= ' ' . _("setting destination file type to") . ' ' . $this->file_src_name_ext . '<br />'; $this->image_convert = $this->file_src_name_ext; } // crop imag (and also crops if image_ratio_crop is used) if ($gd_version >= 2 && (!empty($this->image_crop) || !is_null($ratio_crop))) { if (is_array($this->image_crop)) { $vars = $this->image_crop; } else { $vars = explode(' ', $this->image_crop); } if (sizeof($vars) == 4) { $ct = $vars[0]; $cr = $vars[1]; $cb = $vars[2]; $cl = $vars[3]; } else { if (sizeof($vars) == 2) { $ct = $vars[0]; $cr = $vars[1]; $cb = $vars[0]; $cl = $vars[1]; } else { $ct = $vars[0]; $cr = $vars[0]; $cb = $vars[0]; $cl = $vars[0]; } } if (strpos($ct, '%') > 0) { $ct = $this->image_dst_y * (str_replace('%', '', $ct) / 100); } if (strpos($cr, '%') > 0) { $cr = $this->image_dst_x * (str_replace('%', '', $cr) / 100); } if (strpos($cb, '%') > 0) { $cb = $this->image_dst_y * (str_replace('%', '', $cb) / 100); } if (strpos($cl, '%') > 0) { $cl = $this->image_dst_x * (str_replace('%', '', $cl) / 100); } if (strpos($ct, 'px') > 0) { $ct = str_replace('px', '', $ct); } if (strpos($cr, 'px') > 0) { $cr = str_replace('px', '', $cr); } if (strpos($cb, 'px') > 0) { $cb = str_replace('px', '', $cb); } if (strpos($cl, 'px') > 0) { $cl = str_replace('px', '', $cl); } $ct = (int) $ct; $cr = (int) $cr; $cb = (int) $cb; $cl = (int) $cl; // we adjust the cropping if we use image_ratio_crop if (!is_null($ratio_crop)) { if (array_key_exists('t', $ratio_crop)) { $ct += $ratio_crop['t']; } if (array_key_exists('r', $ratio_crop)) { $cr += $ratio_crop['r']; } if (array_key_exists('b', $ratio_crop)) { $cb += $ratio_crop['b']; } if (array_key_exists('l', $ratio_crop)) { $cl += $ratio_crop['l']; } } $this->log .= '- ' . _("crop image") . ' : ' . $ct . ' ' . $cr . ' ' . $cb . ' ' . $cl . ' <br />'; $this->image_dst_x = $this->image_dst_x - $cl - $cr; $this->image_dst_y = $this->image_dst_y - $ct - $cb; if ($this->image_dst_x < 1) { $this->image_dst_x = 1; } if ($this->image_dst_y < 1) { $this->image_dst_y = 1; } $tmp = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($tmp, $image_dst, 0, 0, $cl, $ct, $this->image_dst_x, $this->image_dst_y); // we transfert tmp into image_dst imagedestroy($image_dst); $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($image_dst, $tmp, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y); imagedestroy($tmp); } // flip image if ($gd_version >= 2 && !empty($this->image_flip)) { $this->image_flip = strtolower($this->image_flip); $this->log .= '- ' . _("flip image") . ' : ' . $this->image_flip . '<br />'; $tmp = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); for ($x = 0; $x < $this->image_dst_x; $x++) { for ($y = 0; $y < $this->image_dst_y; $y++) { if (strpos($this->image_flip, 'v') !== false) { imagecopy($tmp, $image_dst, $this->image_dst_x - $x - 1, $y, $x, $y, 1, 1); } else { imagecopy($tmp, $image_dst, $x, $this->image_dst_y - $y - 1, $x, $y, 1, 1); } } } // we transfert tmp into image_dst imagedestroy($image_dst); $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($image_dst, $tmp, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y); imagedestroy($tmp); } // rotate image if ($gd_version >= 2 && is_numeric($this->image_rotate)) { if (!in_array($this->image_rotate, array(0, 90, 180, 270))) { $this->image_rotate = 0; } if ($this->image_rotate != 0) { if ($this->image_rotate == 90 || $this->image_rotate == 270) { $tmp = imagecreatetruecolor($this->image_dst_y, $this->image_dst_x); } else { $tmp = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); } $this->log .= '- ' . _("rotate image") . ' : ' . $this->image_rotate . '<br />'; for ($x = 0; $x < $this->image_dst_x; $x++) { for ($y = 0; $y < $this->image_dst_y; $y++) { if ($this->image_rotate == 90) { imagecopy($tmp, $image_dst, $y, $x, $x, $this->image_dst_y - $y - 1, 1, 1); } else { if ($this->image_rotate == 180) { imagecopy($tmp, $image_dst, $x, $y, $this->image_dst_x - $x - 1, $this->image_dst_y - $y - 1, 1, 1); } else { if ($this->image_rotate == 270) { imagecopy($tmp, $image_dst, $y, $x, $this->image_dst_x - $x - 1, $y, 1, 1); } else { imagecopy($tmp, $image_dst, $x, $y, $x, $y, 1, 1); } } } } } if ($this->image_rotate == 90 || $this->image_rotate == 270) { $t = $this->image_dst_y; $this->image_dst_y = $this->image_dst_x; $this->image_dst_x = $t; } // we transfert tmp into image_dst imagedestroy($image_dst); $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($image_dst, $tmp, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y); imagedestroy($tmp); } } // add color overlay if ($gd_version >= 2 && (is_numeric($this->image_overlay_percent) && !empty($this->image_overlay_color))) { $this->log .= '- ' . _("apply color overlay") . '<br />'; sscanf($this->image_overlay_color, "#%2x%2x%2x", $red, $green, $blue); $filter = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); $color = imagecolorallocate($filter, $red, $green, $blue); imagefilledrectangle($filter, 0, 0, $this->image_dst_x, $this->image_dst_y, $color); imagecopymerge($image_dst, $filter, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y, $this->image_overlay_percent); imagedestroy($filter); } // add brightness, contrast and tint, turns to greyscale and inverts colors if ($gd_version >= 2 && ($this->image_negative || $this->image_greyscale || is_numeric($this->image_threshold) || is_numeric($this->image_brightness) || is_numeric($this->image_contrast) || !empty($this->image_tint_color))) { $this->log .= '- ' . _("apply tint, light, contrast correction, negative, greyscale and threshold") . '<br />'; if (!empty($this->image_tint_color)) { sscanf($this->image_tint_color, "#%2x%2x%2x", $red, $green, $blue); } $background = imagecolorallocatealpha($image_dst, 255, 255, 255, 0); imagefill($image_dst, 0, 0, $background); imagealphablending($image_dst, TRUE); for ($y = 0; $y < $this->image_dst_y; $y++) { for ($x = 0; $x < $this->image_dst_x; $x++) { if ($this->image_greyscale) { $rgb = imagecolorat($image_dst, $x, $y); $pixel = imagecolorsforindex($image_dst, $rgb); $r = $g = $b = round(0.2125 * $pixel['red'] + 0.7154 * $pixel['green'] + 0.0721 * $pixel['blue']); $a = $pixel['alpha']; $pixelcolor = imagecolorallocatealpha($image_dst, $r, $g, $b, $a); imagesetpixel($image_dst, $x, $y, $pixelcolor); } if (is_numeric($this->image_threshold)) { $rgb = imagecolorat($image_dst, $x, $y); $pixel = imagecolorsforindex($image_dst, $rgb); $c = round($pixel['red'] + $pixel['green'] + $pixel['blue']) / 3 - 127; $r = $g = $b = $c > $this->image_threshold ? 255 : 0; $a = $pixel['alpha']; $pixelcolor = imagecolorallocatealpha($image_dst, $r, $g, $b, $a); imagesetpixel($image_dst, $x, $y, $pixelcolor); } if (is_numeric($this->image_brightness)) { $rgb = imagecolorat($image_dst, $x, $y); $pixel = imagecolorsforindex($image_dst, $rgb); $r = max(min(round($pixel['red'] + $this->image_brightness * 2), 255), 0); $g = max(min(round($pixel['green'] + $this->image_brightness * 2), 255), 0); $b = max(min(round($pixel['blue'] + $this->image_brightness * 2), 255), 0); $a = $pixel['alpha']; $pixelcolor = imagecolorallocatealpha($image_dst, $r, $g, $b, $a); imagesetpixel($image_dst, $x, $y, $pixelcolor); } if (is_numeric($this->image_contrast)) { $rgb = imagecolorat($image_dst, $x, $y); $pixel = imagecolorsforindex($image_dst, $rgb); $r = max(min(round(($this->image_contrast + 128) * $pixel['red'] / 128), 255), 0); $g = max(min(round(($this->image_contrast + 128) * $pixel['green'] / 128), 255), 0); $b = max(min(round(($this->image_contrast + 128) * $pixel['blue'] / 128), 255), 0); $a = $pixel['alpha']; $pixelcolor = imagecolorallocatealpha($image_dst, $r, $g, $b, $a); imagesetpixel($image_dst, $x, $y, $pixelcolor); } if (!empty($this->image_tint_color)) { $rgb = imagecolorat($image_dst, $x, $y); $pixel = imagecolorsforindex($image_dst, $rgb); $r = min(round($red * $pixel['red'] / 169), 255); $g = min(round($green * $pixel['green'] / 169), 255); $b = min(round($blue * $pixel['blue'] / 169), 255); $a = $pixel['alpha']; $pixelcolor = imagecolorallocatealpha($image_dst, $r, $g, $b, $a); imagesetpixel($image_dst, $x, $y, $pixelcolor); } if (!empty($this->image_negative)) { $rgb = imagecolorat($image_dst, $x, $y); $pixel = imagecolorsforindex($image_dst, $rgb); $r = round(255 - $pixel['red']); $g = round(255 - $pixel['green']); $b = round(255 - $pixel['blue']); $a = $pixel['alpha']; $pixelcolor = imagecolorallocatealpha($image_dst, $r, $g, $b, $a); imagesetpixel($image_dst, $x, $y, $pixelcolor); } } } } // adds a border if ($gd_version >= 2 && !empty($this->image_border)) { if (is_array($this->image_border)) { $vars = $this->image_border; $this->log .= '- ' . _("add border") . ' : ' . implode(' ', $this->image_border) . '<br />'; } else { $this->log .= '- ' . _("add border") . ' : ' . $this->image_border . '<br />'; $vars = explode(' ', $this->image_border); } if (sizeof($vars) == 4) { $ct = $vars[0]; $cr = $vars[1]; $cb = $vars[2]; $cl = $vars[3]; } else { if (sizeof($vars) == 2) { $ct = $vars[0]; $cr = $vars[1]; $cb = $vars[0]; $cl = $vars[1]; } else { $ct = $vars[0]; $cr = $vars[0]; $cb = $vars[0]; $cl = $vars[0]; } } if (strpos($ct, '%') > 0) { $ct = $this->image_dst_y * (str_replace('%', '', $ct) / 100); } if (strpos($cr, '%') > 0) { $cr = $this->image_dst_x * (str_replace('%', '', $cr) / 100); } if (strpos($cb, '%') > 0) { $cb = $this->image_dst_y * (str_replace('%', '', $cb) / 100); } if (strpos($cl, '%') > 0) { $cl = $this->image_dst_x * (str_replace('%', '', $cl) / 100); } if (strpos($ct, 'px') > 0) { $ct = str_replace('px', '', $ct); } if (strpos($cr, 'px') > 0) { $cr = str_replace('px', '', $cr); } if (strpos($cb, 'px') > 0) { $cb = str_replace('px', '', $cb); } if (strpos($cl, 'px') > 0) { $cl = str_replace('px', '', $cl); } $ct = (int) $ct; $cr = (int) $cr; $cb = (int) $cb; $cl = (int) $cl; $this->image_dst_x = $this->image_dst_x + $cl + $cr; $this->image_dst_y = $this->image_dst_y + $ct + $cb; if (!empty($this->image_border_color)) { sscanf($this->image_border_color, "#%2x%2x%2x", $red, $green, $blue); } $tmp = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); $background = imagecolorallocatealpha($tmp, $red, $green, $blue, 0); imagefill($tmp, 0, 0, $background); imagecopy($tmp, $image_dst, $cl, $ct, 0, 0, $this->image_dst_x - $cr - $cl, $this->image_dst_y - $cb - $ct); // we transfert tmp into image_dst imagedestroy($image_dst); $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($image_dst, $tmp, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y); imagedestroy($tmp); } // add frame border if (is_numeric($this->image_frame)) { if (is_array($this->image_frame_colors)) { $vars = $this->image_frame_colors; $this->log .= '- ' . _("add frame") . ' : ' . implode(' ', $this->image_frame_colors) . '<br />'; } else { $this->log .= '- ' . _("add frame") . ' : ' . $this->image_frame_colors . '<br />'; $vars = explode(' ', $this->image_frame_colors); } $nb = sizeof($vars); $this->image_dst_x = $this->image_dst_x + $nb * 2; $this->image_dst_y = $this->image_dst_y + $nb * 2; $tmp = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($tmp, $image_dst, $nb, $nb, 0, 0, $this->image_dst_x - $nb * 2, $this->image_dst_y - $nb * 2); for ($i = 0; $i < $nb; $i++) { sscanf($vars[$i], "#%2x%2x%2x", $red, $green, $blue); $c = imagecolorallocate($tmp, $red, $green, $blue); if ($this->image_frame == 1) { imageline($tmp, $i, $i, $this->image_dst_x - $i - 1, $i, $c); imageline($tmp, $this->image_dst_x - $i - 1, $this->image_dst_y - $i - 1, $this->image_dst_x - $i - 1, $i, $c); imageline($tmp, $this->image_dst_x - $i - 1, $this->image_dst_y - $i - 1, $i, $this->image_dst_y - $i - 1, $c); imageline($tmp, $i, $i, $i, $this->image_dst_y - $i - 1, $c); } else { imageline($tmp, $i, $i, $this->image_dst_x - $i - 1, $i, $c); imageline($tmp, $this->image_dst_x - $nb + $i, $this->image_dst_y - $nb + $i, $this->image_dst_x - $nb + $i, $nb - $i, $c); imageline($tmp, $this->image_dst_x - $nb + $i, $this->image_dst_y - $nb + $i, $nb - $i, $this->image_dst_y - $nb + $i, $c); imageline($tmp, $i, $i, $i, $this->image_dst_y - $i - 1, $c); } } // we transfert tmp into image_dst imagedestroy($image_dst); $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($image_dst, $tmp, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y); imagedestroy($tmp); } // add bevel border if ($this->image_bevel > 0) { if (empty($this->image_bevel_color1)) { $this->image_bevel_color1 = '#FFFFFF'; } if (empty($this->image_bevel_color2)) { $this->image_bevel_color2 = '#000000'; } sscanf($this->image_bevel_color1, "#%2x%2x%2x", $red1, $green1, $blue1); sscanf($this->image_bevel_color2, "#%2x%2x%2x", $red2, $green2, $blue2); imagealphablending($image_dst, true); for ($i = 0; $i < $this->image_bevel; $i++) { $alpha = round($i / $this->image_bevel * 127); $c1 = imagecolorallocatealpha($image_dst, $red1, $green1, $blue1, $alpha); $c2 = imagecolorallocatealpha($image_dst, $red2, $green2, $blue2, $alpha); imageline($image_dst, $i, $i, $this->image_dst_x - $i - 1, $i, $c1); imageline($image_dst, $this->image_dst_x - $i - 1, $this->image_dst_y - $i, $this->image_dst_x - $i - 1, $i, $c2); imageline($image_dst, $this->image_dst_x - $i - 1, $this->image_dst_y - $i - 1, $i, $this->image_dst_y - $i - 1, $c2); imageline($image_dst, $i, $i, $i, $this->image_dst_y - $i - 1, $c1); } } // add watermark image if ($this->image_watermark != '' && file_exists($this->image_watermark)) { $this->log .= '- ' . _("add watermark") . '<br />'; $this->image_watermark_position = strtolower($this->image_watermark_position); $watermark_info = getimagesize($this->image_watermark); $watermark_type = array_key_exists(2, $watermark_info) ? $watermark_info[2] : NULL; // 1 = GIF, 2 = JPG, 3 = PNG $watermark_checked = false; if ($watermark_type == 1) { if (!function_exists('imagecreatefromgif')) { $this->error = _("No create from GIF support, can't read watermark"); } else { $filter = @imagecreatefromgif($this->image_watermark); if (!$filter) { $this->error = _("No GIF read support, can't create watermark"); } else { $this->log .= ' ' . _("watermark source image is GIF") . '<br />'; $watermark_checked = true; } } } else { if ($watermark_type == 2) { if (!function_exists('imagecreatefromjpeg')) { $this->error = _("No create from JPG support, can't read watermark"); } else { $filter = @imagecreatefromjpeg($this->image_watermark); if (!$filter) { $this->error = _("No JPG read support, can't create watermark"); } else { $this->log .= ' ' . _("watermark source image is JPG") . '<br />'; $watermark_checked = true; } } } else { if ($watermark_type == 3) { if (!function_exists('imagecreatefrompng')) { $this->error = _("No create from PNG support, can't read watermark"); } else { $filter = @imagecreatefrompng($this->image_watermark); if (!$filter) { $this->error = _("No PNG read support, can't create watermark"); } else { $this->log .= ' ' . _("watermark source image is PNG") . '<br />'; $watermark_checked = true; } } } } } if ($watermark_checked) { $watermark_width = imagesx($filter); $watermark_height = imagesy($filter); $watermark_x = 0; $watermark_y = 0; if (is_numeric($this->image_watermark_x)) { if ($this->image_watermark_x < 0) { $watermark_x = $this->image_dst_x - $watermark_width + $this->image_watermark_x; } else { $watermark_x = $this->image_watermark_x; } } else { if (strpos($this->image_watermark_position, 'r') !== false) { $watermark_x = $this->image_dst_x - $watermark_width; } else { if (strpos($this->image_watermark_position, 'l') !== false) { $watermark_x = 0; } else { $watermark_x = ($this->image_dst_x - $watermark_width) / 2; } } } if (is_numeric($this->image_watermark_y)) { if ($this->image_watermark_y < 0) { $watermark_y = $this->image_dst_y - $watermark_height + $this->image_watermark_y; } else { $watermark_y = $this->image_watermark_y; } } else { if (strpos($this->image_watermark_position, 'b') !== false) { $watermark_y = $this->image_dst_y - $watermark_height; } else { if (strpos($this->image_watermark_position, 't') !== false) { $watermark_y = 0; } else { $watermark_y = ($this->image_dst_y - $watermark_height) / 2; } } } imagecopyresampled($image_dst, $filter, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height, $watermark_width, $watermark_height); } else { $this->error = _("Watermark image is of unknown type"); } } // add text if (!empty($this->image_text)) { $this->log .= '- ' . _("add text") . '<br />'; if (!is_numeric($this->image_text_padding)) { $this->image_text_padding = 0; } if (!is_numeric($this->image_text_line_spacing)) { $this->image_text_line_spacing = 0; } if (!is_numeric($this->image_text_padding_x)) { $this->image_text_padding_x = $this->image_text_padding; } if (!is_numeric($this->image_text_padding_y)) { $this->image_text_padding_y = $this->image_text_padding; } $this->image_text_position = strtolower($this->image_text_position); $this->image_text_direction = strtolower($this->image_text_direction); $this->image_text_alignment = strtolower($this->image_text_alignment); // if the font is a string, we assume that we might want to load a font if (!is_numeric($this->image_text_font) && strlen($this->image_text_font) > 4 && substr(strtolower($this->image_text_font), -4) == '.gdf') { $this->log .= ' ' . _("try to load font") . ' ' . $this->image_text_font . '... '; if ($this->image_text_font = @imageloadfont($this->image_text_font)) { $this->log .= _("success") . '<br />'; } else { $this->log .= _("error") . '<br />'; $this->image_text_font = 5; } } $text = explode("\n", $this->image_text); $char_width = ImageFontWidth($this->image_text_font); $char_height = ImageFontHeight($this->image_text_font); $text_height = 0; $text_width = 0; $line_height = 0; $line_width = 0; foreach ($text as $k => $v) { if ($this->image_text_direction == 'v') { $h = $char_width * strlen($v); if ($h > $text_height) { $text_height = $h; } $line_width = $char_height; $text_width += $line_width + ($k < sizeof($text) - 1 ? $this->image_text_line_spacing : 0); } else { $w = $char_width * strlen($v); if ($w > $text_width) { $text_width = $w; } $line_height = $char_height; $text_height += $line_height + ($k < sizeof($text) - 1 ? $this->image_text_line_spacing : 0); } } $text_width += 2 * $this->image_text_padding_x; $text_height += 2 * $this->image_text_padding_y; $text_x = 0; $text_y = 0; if (is_numeric($this->image_text_x)) { if ($this->image_text_x < 0) { $text_x = $this->image_dst_x - $text_width + $this->image_text_x; } else { $text_x = $this->image_text_x; } } else { if (strpos($this->image_text_position, 'r') !== false) { $text_x = $this->image_dst_x - $text_width; } else { if (strpos($this->image_text_position, 'l') !== false) { $text_x = 0; } else { $text_x = ($this->image_dst_x - $text_width) / 2; } } } if (is_numeric($this->image_text_y)) { if ($this->image_text_y < 0) { $text_y = $this->image_dst_y - $text_height + $this->image_text_y; } else { $text_y = $this->image_text_y; } } else { if (strpos($this->image_text_position, 'b') !== false) { $text_y = $this->image_dst_y - $text_height; } else { if (strpos($this->image_text_position, 't') !== false) { $text_y = 0; } else { $text_y = ($this->image_dst_y - $text_height) / 2; } } } // add a background, maybe transparent if (!empty($this->image_text_background)) { sscanf($this->image_text_background, "#%2x%2x%2x", $red, $green, $blue); if ($gd_version >= 2 && is_numeric($this->image_text_background_percent) && $this->image_text_background_percent >= 0 && $this->image_text_background_percent <= 100) { $filter = imagecreatetruecolor($text_width, $text_height); $background_color = imagecolorallocate($filter, $red, $green, $blue); imagefilledrectangle($filter, 0, 0, $text_width, $text_height, $background_color); imagecopymerge($image_dst, $filter, $text_x, $text_y, 0, 0, $text_width, $text_height, $this->image_text_background_percent); imagedestroy($filter); } else { $background_color = imageColorAllocate($image_dst, $red, $green, $blue); imagefilledrectangle($image_dst, $text_x, $text_y, $text_x + $text_width, $text_y + $text_height, $background_color); } } $text_x += $this->image_text_padding_x; $text_y += $this->image_text_padding_y; $t_width = $text_width - 2 * $this->image_text_padding_x; $t_height = $text_height - 2 * $this->image_text_padding_y; sscanf($this->image_text_color, "#%2x%2x%2x", $red, $green, $blue); // add the text, maybe transparent if ($gd_version >= 2 && is_numeric($this->image_text_percent) && $this->image_text_percent >= 0 && $this->image_text_percent <= 100) { if ($t_width < 0) { $t_width = 0; } if ($t_height < 0) { $t_height = 0; } $filter = imagecreatetruecolor($t_width, $t_height); $color = imagecolorallocate($filter, 0, 0, $blue == 0 ? 255 : 0); imagefill($filter, 0, 0, $color); $text_color = imagecolorallocate($filter, $red, $green, $blue); imagecolortransparent($filter, $color); foreach ($text as $k => $v) { if ($this->image_text_direction == 'v') { imagestringup($filter, $this->image_text_font, $k * ($line_width + ($k > 0 && $k < sizeof($text) ? $this->image_text_line_spacing : 0)), $text_height - 2 * $this->image_text_padding_y - ($this->image_text_alignment == 'l' ? 0 : ($t_height - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2)), $v, $text_color); } else { imagestring($filter, $this->image_text_font, $this->image_text_alignment == 'l' ? 0 : ($t_width - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2), $k * ($line_height + ($k > 0 && $k < sizeof($text) ? $this->image_text_line_spacing : 0)), $v, $text_color); } } imagecopymerge($image_dst, $filter, $text_x, $text_y, 0, 0, $t_width, $t_height, $this->image_text_percent); imagedestroy($filter); } else { $text_color = imageColorAllocate($image_dst, $red, $green, $blue); foreach ($text as $k => $v) { if ($this->image_text_direction == 'v') { imagestringup($image_dst, $this->image_text_font, $text_x + $k * ($line_width + ($k > 0 && $k < sizeof($text) ? $this->image_text_line_spacing : 0)), $text_y + $text_height - 2 * $this->image_text_padding_y - ($this->image_text_alignment == 'l' ? 0 : ($t_height - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2)), $v, $text_color); } else { imagestring($image_dst, $this->image_text_font, $text_x + ($this->image_text_alignment == 'l' ? 0 : ($t_width - strlen($v) * $char_width) / ($this->image_text_alignment == 'r' ? 1 : 2)), $text_y + $k * ($line_height + ($k > 0 && $k < sizeof($text) ? $this->image_text_line_spacing : 0)), $v, $text_color); } } } } // add a reflection if ($this->image_reflection_height) { $this->log .= '- ' . _("add reflection") . ' : ' . $this->image_reflection_height . '<br />'; // we decode image_reflection_height, which can be a integer, a string in pixels or percentage $image_reflection_height = $this->image_reflection_height; if (strpos($image_reflection_height, '%') > 0) { $image_reflection_height = $this->image_dst_y * str_replace('%', '', $image_reflection_height / 100); } if (strpos($image_reflection_height, 'px') > 0) { $image_reflection_height = str_replace('px', '', $image_reflection_height); } $image_reflection_height = (int) $image_reflection_height; if ($image_reflection_height > $this->image_dst_y) { $image_reflection_height = $this->image_dst_y; } if (empty($this->image_reflection_color)) { $this->image_reflection_color = '#FFFFFF'; } if (empty($this->image_reflection_opacity)) { $this->image_reflection_opacity = 60; } // create the new destination image $tmp = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y + $image_reflection_height + $this->image_reflection_space); sscanf($this->image_reflection_color, "#%2x%2x%2x", $red, $green, $blue); $color = imagecolorallocate($tmp, $red, $green, $blue); imagefilledrectangle($tmp, 0, 0, $this->image_dst_x, $this->image_dst_y + $image_reflection_height + $this->image_reflection_space, $color); $transparency = $this->image_reflection_opacity; // copy the original image imagecopy($tmp, $image_dst, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y + ($this->image_reflection_space < 0 ? $this->image_reflection_space : 0)); // copy the reflection for ($y = 0; $y < $image_reflection_height; $y++) { imagecopymerge($tmp, $image_dst, 0, $y + $this->image_dst_y + $this->image_reflection_space, 0, $this->image_dst_y - $y - 1 + ($this->image_reflection_space < 0 ? $this->image_reflection_space : 0), $this->image_dst_x, 1, (int) $transparency); if ($transparency > 0) { $transparency = $transparency - $this->image_reflection_opacity / $image_reflection_height; } } // copy the resulting image into the destination image $this->image_dst_y = $this->image_dst_y + $image_reflection_height + $this->image_reflection_space; imagedestroy($image_dst); $image_dst = imagecreatetruecolor($this->image_dst_x, $this->image_dst_y); imagecopy($image_dst, $tmp, 0, 0, 0, 0, $this->image_dst_x, $this->image_dst_y); imagedestroy($tmp); } if (is_numeric($this->jpeg_size) && $this->jpeg_size > 0 && ($this->image_convert == 'jpeg' || $this->image_convert == 'jpg')) { // inspired by: JPEGReducer class version 1, 25 November 2004, Author: Huda M ElMatsani, justhuda at netscape dot net $this->log .= '- ' . _("JPEG desired file size") . ' : ' . $this->jpeg_size . '<br />'; //calculate size of each image. 75%, 50%, and 25% quality ob_start(); imagejpeg($image_dst, '', 75); $buffer = ob_get_contents(); ob_end_clean(); $size75 = strlen($buffer); ob_start(); imagejpeg($image_dst, '', 50); $buffer = ob_get_contents(); ob_end_clean(); $size50 = strlen($buffer); ob_start(); imagejpeg($image_dst, '', 25); $buffer = ob_get_contents(); ob_end_clean(); $size25 = strlen($buffer); //calculate gradient of size reduction by quality $mgrad1 = 25 / ($size50 - $size25); $mgrad2 = 25 / ($size75 - $size50); $mgrad3 = 50 / ($size75 - $size25); $mgrad = ($mgrad1 + $mgrad2 + $mgrad3) / 3; //result of approx. quality factor for expected size $q_factor = round($mgrad * ($this->jpeg_size - $size50) + 50); if ($q_factor < 1) { $this->jpeg_quality = 1; } elseif ($q_factor > 100) { $this->jpeg_quality = 100; } else { $this->jpeg_quality = $q_factor; } $this->log .= ' ' . _("JPEG quality factor set to") . ' ' . $this->jpeg_quality . '<br />'; } // outputs image $this->log .= '- ' . _("converting..") . '<br />'; switch ($this->image_convert) { case 'jpeg': case 'jpg': $result = @imagejpeg($image_dst, $this->file_dst_pathname, $this->jpeg_quality); if (!$result) { $this->processed = false; $this->error = _("No JPEG create support"); } else { $this->log .= ' ' . _("JPEG image created") . '<br />'; } break; case 'png': $result = @imagepng($image_dst, $this->file_dst_pathname); if (!$result) { $this->processed = false; $this->error = _("No PNG create support"); } else { $this->log .= ' ' . _("PNG image created") . '<br />'; } break; case 'gif': $result = @imagegif($image_dst, $this->file_dst_pathname); if (!$result) { $this->processed = false; $this->error = _("No GIF create support"); } else { $this->log .= ' ' . _("GIF image created") . '<br />'; } break; default: $this->processed = false; $this->error = _("No convertion type defined"); } if ($this->processed) { if (is_resource($image_src)) { imagedestroy($image_src); } if (is_resource($image_dst)) { imagedestroy($image_dst); } $this->log .= ' ' . _("image objects destroyed") . '<br />'; } } if ($has_temp_file) { $this->log .= '- ' . _("deletes temporary file") . '<br />'; @unlink($this->file_src_pathname); } } else { $this->log .= '- ' . _("no image processing wanted") . '<br />'; if (!$this->no_upload_check) { $result = is_uploaded_file($this->file_src_pathname); } else { $result = TRUE; } if ($result) { if (!$this->no_upload_check) { if (!move_uploaded_file($this->file_src_pathname, $this->file_dst_pathname)) { $this->processed = false; $this->error = _("Error copying file on the server. move_uploaded_file() failed"); } } else { if (!copy($this->file_src_pathname, $this->file_dst_pathname)) { $this->processed = false; $this->error = _("Error copying file on the server. copy() failed"); } } } else { $this->processed = false; $this->error = _("Error copying file on the server. Incorrect source file"); } } } if ($this->processed) { $this->log .= '- <b>' . _("process OK") . '</b><br />'; } // we reinit all the var $this->init(); }
/** * Function is used to resize the image * * @access Private * @param Number $width * @param Number $height * @param String $newfile * @return Boolean */ function _resize($width, $height, $newfile = NULL) { if (!function_exists("imagecreate")) { $this->_error = "Error: GD Library is not available."; return false; } $newimg = @imagecreatetruecolor($width, $height); //imagecolortransparent( $newimg, imagecolorat( $newimg, 0, 0 ) ); if ($this->imgType == 'GIF' || $this->imgType == 'PNG') { /** Code to keep transparency of image **/ $colorcount = imagecolorstotal($this->_img); if ($colorcount == 0) { $colorcount = 256; } imagetruecolortopalette($newimg, true, $colorcount); imagepalettecopy($newimg, $this->_img); $transparentcolor = imagecolortransparent($this->_img); imagefill($newimg, 0, 0, $transparentcolor); imagecolortransparent($newimg, $transparentcolor); } @imagecopyresampled($newimg, $this->_img, 0, 0, 0, 0, $width, $height, $this->imgWidth, $this->imgHeight); if ($newfile === HAR_AUTO_NAME) { if (@preg_match("/\\..*+\$/", @basename($this->imgFile), $matches)) { $newfile = @substr_replace($this->imgFile, "_har", -@strlen($matches[0]), 0); } } elseif (!empty($newfile)) { if (!@preg_match("/\\..*+\$/", @basename($newfile))) { if (@preg_match("/\\..*+\$/", @basename($this->imgFile), $matches)) { $newfile = $newfile . $matches[0]; } } } if ($this->imgType == 'GIF') { if (!empty($newfile)) { @imagegif($newimg, $newfile); } else { @header("Content-type: image/gif"); @imagegif($newimg); } } elseif ($this->imgType == 'JPG') { if (!empty($newfile)) { @imagejpeg($newimg, $newfile, 85); } else { @header("Content-type: image/jpeg"); @imagejpeg($newimg); } } elseif ($this->imgType == 'PNG') { if (!empty($newfile)) { @imagepng($newimg, $newfile); } else { @header("Content-type: image/png"); @imagepng($newimg); } } @imagedestroy($newimg); }
function resize() { global $mtconf; $imagetype = array(1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', 8 => 'TIFF', 9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF'); if (substr(0, 7, $this->tmpFile) == 'http://') { $imginfo = getimagesize_remote($this->tmpFile); } else { $imginfo = getimagesize($this->tmpFile); } $imginfo[2] = $imagetype[$imginfo[2]]; # GD can only handle GIF, JPG & PNG images if ($imginfo[2] != 'JPG' && $imginfo[2] != 'PNG' && $imginfo[2] != 'GIF' && ($this->method == 'gd1' || $this->method == 'gd2')) { die("ERROR: GD can only handle JPG, GIF and PNG files!"); } # height/width $srcWidth = $imginfo[0]; $srcHeight = $imginfo[1]; # Generate new width/height $ratio = max($srcWidth, $srcHeight) / $this->size; $ratio = max($ratio, 1.0); $destWidth = (int) ($srcWidth / $ratio); $destHeight = (int) ($srcHeight / $ratio); $offWidth = 0; $offHeight = 0; if ($this->square && $srcWidth > $this->size && $srcHeight > $this->size) { if ($srcWidth > $srcHeight) { $offWidth = ($srcWidth - $srcHeight) / 2; $offHeight = 0; $srcWidth = $srcHeight; $destHeight = $destWidth; } elseif ($srcHeight > $srcWidth) { $offWidth = 0; $offHeight = ($srcHeight - $srcWidth) / 2; $srcHeight = $srcWidth; $destWidth = $destHeight; } } # Method for thumbnails creation switch ($this->method) { case "gd1": if (!function_exists('imagecreatefromjpeg')) { die('GD image library not installed!'); } if ($imginfo[2] == 'JPG') { $src_img = imagecreatefromjpeg($this->tmpFile); } else { $src_img = imagecreatefrompng($this->tmpFile); } if (!$src_img) { $ERROR = $lang_errors['invalid_image']; return false; } $dst_img = imagecreate($destWidth, $destHeight); imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int) $destHeight, $srcWidth, $srcHeight); ob_start(); imagejpeg($dst_img, null, $this->quality); $this->imageData = ob_get_contents(); ob_end_clean(); imagedestroy($src_img); imagedestroy($dst_img); break; case "gd2": if (!function_exists('imagecreatefromjpeg')) { die('GD image library not installed!'); } if (!function_exists('imagecreatetruecolor')) { die('GD2 image library does not support truecolor thumbnailing!'); } switch ($imginfo[2]) { case 'JPG': $src_img = imagecreatefromjpeg($this->tmpFile); $dst_img = imagecreatetruecolor($destWidth, $destHeight); break; case 'PNG': $src_img = imagecreatefrompng($this->tmpFile); $dst_img = $this->imagecreatetruecolortransparent($destWidth, $destHeight); break; case 'GIF': $src_img = imagecreatefromgif($this->tmpFile); $dst_img = imagecreatetruecolor($destWidth, $destHeight); $colorTransparent = imagecolortransparent($src_img); imagepalettecopy($src_img, $dst_img); imagefill($dst_img, 0, 0, $colorTransparent); imagecolortransparent($dst_img, $colorTransparent); imagetruecolortopalette($dst_img, true, 256); break; } imagecopyresampled($dst_img, $src_img, 0, 0, $offWidth, $offHeight, $destWidth, (int) $destHeight, $srcWidth, $srcHeight); ob_start(); switch ($imginfo[2]) { case 'GIF': imagegif($dst_img); break; case 'PNG': imagepng($dst_img); break; case 'JPG': default: imagejpeg($dst_img, null, $this->quality); break; } $this->imageData = ob_get_contents(); ob_end_clean(); imagedestroy($src_img); imagedestroy($dst_img); break; case "netpbm": if ($mtconf->get('img_netpbmpath')) { if (!is_dir($mtconf->get('img_netpbmpath'))) { echo "NetPbm path incorrect"; die; } } if ($imginfo[2] == 'PNG') { $cmd = $mtconf->get('img_netpbmpath') . "pngtopnm {$this->tmpFile} | " . $mtconf->get('img_netpbmpath') . "pnmscale -xysize {$destWidth} " . (int) $destHeight . " | " . $mtconf->get('img_netpbmpath') . "pnmtopng > " . JPATH_ROOT . DS . 'media' . DS . $this->imageName; } else { if ($imginfo[2] == 'JPG') { $cmd = $mtconf->get('img_netpbmpath') . "jpegtopnm {$this->tmpFile} | " . $mtconf->get('img_netpbmpath') . "pnmscale -xysize {$destWidth} " . (int) $destHeight . " | " . $mtconf->get('img_netpbmpath') . "pnmtojpeg -quality={$this->quality} > " . JPATH_ROOT . DS . 'media' . DS . $this->imageName; } else { if ($imginfo[2] == 'GIF') { $cmd = $mtconf->get('img_netpbmpath') . "giftopnm {$this->tmpFile} | " . $mtconf->get('img_netpbmpath') . "pnmscale -xysize {$destWidth} " . (int) $destHeight . " | " . $mtconf->get('img_netpbmpath') . "ppmquant 256 | " . $mtconf->get('img_netpbmpath') . "ppmtogif > " . JPATH_ROOT . DS . 'media' . DS . $this->imageName; } } } exec($cmd); break; case "imagemagick": $tmp_name = substr(strrchr($this->directory . $this->imageName, "/"), 1); copy($this->tmpFile, JPATH_ROOT . DS . 'media' . DS . $tmp_name); $uploadfile = JPATH_ROOT . DS . 'media' . DS . $tmp_name; $cmd = $mtconf->get('img_impath') . "convert -resize " . $destWidth . "x" . (int) $destHeight . " {$uploadfile} " . JPATH_ROOT . DS . 'media' . DS . $this->imageName; exec($cmd); unlink($uploadfile); break; } if ($this->method == 'netpbm' || $this->method == 'imagemagick') { $filename = JPATH_ROOT . DS . 'media' . DS . $this->imageName; $handle = fopen($filename, "r"); $this->imageData = fread($handle, filesize($filename)); fclose($handle); unlink(JPATH_ROOT . DS . 'media' . DS . $this->imageName); } # Set mode of uploaded picture if (file_exists($this->directory . $this->imageName)) { chmod($this->directory . $this->imageName, octdec('755')); # We check that the image is valid $imginfo = getimagesize($this->directory . $this->imageName); if ($imginfo == null) { return false; } else { return true; } } else { return false; } }
/** * Resize * * @param integer $width Width * @param integer $height Height * * @return boolean */ public function resize($width, $height) { $result = false; if ($this->image) { $newImage = imagecreatetruecolor($width, $height); $transparentIndex = imagecolortransparent($this->image); if ($transparentIndex >= 0) { imagepalettecopy($this->image, $newImage); imagefill($newImage, 0, 0, $transparentIndex); imagecolortransparent($newImage, $transparentIndex); imagetruecolortopalette($newImage, true, 256); } else { imagealphablending($newImage, false); imagesavealpha($newImage, true); $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127); imagefilledrectangle($newImage, 0, 0, $width, $height, $transparent); } $result = imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height); if ($result) { imagedestroy($this->image); $this->image = $newImage; $this->width = $width; $this->height = $height; if (\XLite::getInstance()->getOptions(array('images', 'unsharp_mask_filter_on_resize'))) { include_once LC_DIR_LIB . 'phpunsharpmask.php'; $unsharpImage = UnsharpMask($this->image); if ($unsharpImage) { $this->image = $unsharpImage; } } } } return $result; }
/** * Creates new GD resource * of defined intWidth and intHeight * takes clues from hdlOrig about what type * of GD resource to create and wheather or not * to set transparancy */ protected function createGDResource($intWidth = 0, $intHeight = 0, $bTrueColor = false) { $this->checkHdlOrig(); if (!is_numeric($intWidth) || !is_numeric($intHeight)) { throw new \Lampcms\ImageException('$intWidth and $intHeight must be numeric. Supplied value were $intWidth: ' . $intWidth . ' $intHeight: ' . $intHeight); } $intWidth = $intWidth > 0 ? $intWidth : $this->aOrigSize[0]; $intHeight = $intHeight > 0 ? $intHeight : $this->aOrigSize[1]; /** * @todo * Should we check if this->hdlWork * already exists? * It should not exist because work size canvas is * always destroyed after work image * is saved */ $this->bTrueColor = false !== $bTrueColor ? (bool) $bTrueColor : imageistruecolor($this->hdlOrig); d('bTrueColor: ' . $this->bTrueColor); if ($this->bTrueColor) { $hdlGD = \imagecreatetruecolor($intWidth, $intHeight); /** * Transparancy thingy * Only png can have transparancy and be truecolor */ if ('png' === $this->origType) { \imagealphablending($hdlGD, false); $color = \imagecolorallocatealpha($hdlGD, 0, 0, 0, 127); \imagefill($hdlGD, 0, 0, $color); \imagesavealpha($hdlGD, true); } } if (!isset($hdlGD)) { d('cp'); $hdlGD = \imagecreate($intWidth, $intHeight); \imagepalettecopy($hdlGD, $this->hdlOrig); $color = \imagecolortransparent($this->hdlOrig); if ($color != -1) { \imagecolortransparent($hdlGD, $color); \imagefill($hdlGD, 0, 0, $color); } d('$hdlGD: ' . gettype($hdlGD)); } return $hdlGD; }
/** * Returns a new image for temporary processing * * @param int $width width of the new image * @param int $height height of the new image * @param bool $trueColor force which type of image to create * @return resource a GD image resource * @access protected */ function _createImage($width = -1, $height = -1, $trueColor = null) { if ($width == -1) { $width = $this->new_x; } if ($height == -1) { $height = $this->new_y; } $new_img = null; if (is_null($trueColor)) { if (function_exists('imageistruecolor')) { $createtruecolor = imageistruecolor($this->imageHandle); } else { $createtruecolor = true; } } else { $createtruecolor = $trueColor; } if ($createtruecolor && function_exists('ImageCreateTrueColor')) { $new_img = @ImageCreateTrueColor($width, $height); } if (!$new_img) { $new_img = ImageCreate($width, $height); imagepalettecopy($new_img, $this->imageHandle); $color = imagecolortransparent($this->imageHandle); if ($color != -1) { imagecolortransparent($new_img, $color); imagefill($new_img, 0, 0, $color); } } return $new_img; }
/** * Copies the captcha image to the final image with distortion applied */ protected function distortedCopy() { $numpoles = 3; // distortion factor // make array of poles AKA attractor points for ($i = 0; $i < $numpoles; ++$i) { $px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8); $py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8); $rad[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8); $tmp = -$this->frand() * 0.15 - 0.15; $amp[$i] = $this->perturbation * $tmp; } $bgCol = imagecolorat($this->tmpimg, 0, 0); $width2 = $this->iscale * $this->image_width; $height2 = $this->iscale * $this->image_height; imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across // loop over $img pixels, take pixels from $tmpimg with distortion field for ($ix = 0; $ix < $this->image_width; ++$ix) { for ($iy = 0; $iy < $this->image_height; ++$iy) { $x = $ix; $y = $iy; for ($i = 0; $i < $numpoles; ++$i) { $dx = $ix - $px[$i]; $dy = $iy - $py[$i]; if ($dx == 0 && $dy == 0) { continue; } $r = sqrt($dx * $dx + $dy * $dy); if ($r > $rad[$i]) { continue; } $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]); $x += $dx * $rscale; $y += $dy * $rscale; } $c = $bgCol; $x *= $this->iscale; $y *= $this->iscale; if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) { $c = imagecolorat($this->tmpimg, $x, $y); } if ($c != $bgCol) { // only copy pixels of letters to preserve any background image imagesetpixel($this->im, $ix, $iy, $c); } } } }
/** * @param WideImage_Image $image * @param int $radius * @param int $color * @param int $smoothness * @return WideImage_Image */ function execute($image, $radius, $color, $smoothness, $corners) { if ($smoothness < 1) { $sample_ratio = 1; } elseif ($smoothness > 16) { $sample_ratio = 16; } else { $sample_ratio = $smoothness; } $corner = WideImage::createTrueColorImage($radius * $sample_ratio, $radius * $sample_ratio); if ($color === null) { imagepalettecopy($corner->getHandle(), $image->getHandle()); $bg_color = $corner->allocateColor(0, 0, 0); $corner->fill(0, 0, $bg_color); $fg_color = $corner->allocateColor(255, 255, 255); $corner->getCanvas()->filledEllipse($radius * $sample_ratio, $radius * $sample_ratio, $radius * 2 * $sample_ratio, $radius * 2 * $sample_ratio, $fg_color); $corner = $corner->resize($radius, $radius); $result = $image->asTrueColor(); $tc = $result->getTransparentColor(); if ($tc == -1) { $tc = $result->allocateColorAlpha(255, 255, 255, 127); imagecolortransparent($result->getHandle(), $tc); $result->setTransparentColor($tc); } if ($corners & WideImage::SIDE_TOP_LEFT || $corners & WideImage::SIDE_LEFT || $corners & WideImage::SIDE_TOP) { $result = $result->applyMask($corner, -1, -1); } $corner = $corner->rotate(90); if ($corners & WideImage::SIDE_TOP_RIGHT || $corners & WideImage::SIDE_TOP || $corners & WideImage::SIDE_RIGHT) { $result = $result->applyMask($corner, $result->getWidth() - $corner->getWidth() + 1, -1, 100); } $corner = $corner->rotate(90); if ($corners & WideImage::SIDE_BOTTOM_RIGHT || $corners & WideImage::SIDE_RIGHT || $corners & WideImage::SIDE_BOTTOM) { $result = $result->applyMask($corner, $result->getWidth() - $corner->getWidth() + 1, $result->getHeight() - $corner->getHeight() + 1, 100); } $corner = $corner->rotate(90); if ($corners & WideImage::SIDE_BOTTOM_LEFT || $corners & WideImage::SIDE_LEFT || $corners & WideImage::SIDE_BOTTOM) { $result = $result->applyMask($corner, -1, $result->getHeight() - $corner->getHeight() + 1, 100); } return $result; } else { $bg_color = $color; $corner->fill(0, 0, $bg_color); $fg_color = $corner->allocateColorAlpha(127, 127, 127, 127); $corner->getCanvas()->filledEllipse($radius * $sample_ratio, $radius * $sample_ratio, $radius * 2 * $sample_ratio, $radius * 2 * $sample_ratio, $fg_color); $corner = $corner->resize($radius, $radius); $result = $image->copy(); if ($corners & WideImage::SIDE_TOP_LEFT || $corners & WideImage::SIDE_LEFT || $corners & WideImage::SIDE_TOP) { $result = $result->merge($corner, -1, -1, 100); } $corner = $corner->rotate(90); if ($corners & WideImage::SIDE_TOP_RIGHT || $corners & WideImage::SIDE_TOP || $corners & WideImage::SIDE_RIGHT) { $result = $result->merge($corner, $result->getWidth() - $corner->getWidth() + 1, -1, 100); } $corner = $corner->rotate(90); if ($corners & WideImage::SIDE_BOTTOM_RIGHT || $corners & WideImage::SIDE_RIGHT || $corners & WideImage::SIDE_BOTTOM) { $result = $result->merge($corner, $result->getWidth() - $corner->getWidth() + 1, $result->getHeight() - $corner->getHeight() + 1, 100); } $corner = $corner->rotate(90); if ($corners & WideImage::SIDE_BOTTOM_LEFT || $corners & WideImage::SIDE_LEFT || $corners & WideImage::SIDE_BOTTOM) { $result = $result->merge($corner, -1, $result->getHeight() - $corner->getHeight() + 1, 100); } return $result; } }
public function _AutoGenerateInsThumb($ImageName, $Size = "thumb", $OverrideExisting = false) { // Takes the filename of an image already uploaded into the // image directory, generates a thumbnal from it, stores it // in the image directory and returns its name $imgFile = realpath(ISC_BASE_PATH . "/install_images"); $imgFile .= "/" . $ImageName; if ($ImageName == '' || !file_exists($imgFile)) { return false; } // A list of thumbnails too $tmp = explode(".", $imgFile); $ext = isc_strtolower($tmp[count($tmp) - 1]); // If overriding the existing image, set the output filename to the input filename //Large and medium size images by Simha if ($Size == 'large') { $thumbFileName = $ImageName; } else { if ($Size == 'medium') { $thumbFileName = GenRandFileName($ImageName, $Size); } else { if ($OverrideExisting == true) { $thumbFileName = $ImageName; } else { $thumbFileName = GenRandFileName($ImageName, $Size); } } } $attribs = @getimagesize($imgFile); $width = $attribs[0]; $height = $attribs[1]; if (!is_array($attribs)) { return false; } // Check if we have enough available memory to create this image - if we don't, attempt to bump it up setImageFileMemLimit($imgFile); $thumbFile = realpath(ISC_BASE_PATH . "/install_images"); $thumbFile .= "/" . $thumbFileName; if ($ext == "jpg") { $srcImg = @imagecreatefromjpeg($imgFile); } else { if ($ext == "gif") { $srcImg = @imagecreatefromgif($imgFile); if (!function_exists("imagegif")) { $gifHack = 1; } } else { $srcImg = @imagecreatefrompng($imgFile); } } if (!$srcImg) { return false; } $srcWidth = @imagesx($srcImg); $srcHeight = @imagesy($srcImg); //Large and medium size images by Simha if ($Size == 'large') { $AutoThumbSize = 800; } else { if ($Size == 'medium') { $AutoThumbSize = 70; } else { if ($Size == "tiny") { $AutoThumbSize = ISC_TINY_THUMB_SIZE; } else { $AutoThumbSize = GetConfig('AutoThumbSize'); } } } // This thumbnail is smaller than the Interspire Shopping Cart dimensions, simply copy the image and return if ($srcWidth <= $AutoThumbSize && $srcHeight <= $AutoThumbSize) { @imagedestroy($srcImg); if ($OverrideExisting == false) { @copy($imgFile, $thumbFile); } return $thumbFileName; } // Make sure the thumb has a constant height $thumbWidth = $width; $thumbHeight = $height; if ($width > $AutoThumbSize) { $thumbWidth = $AutoThumbSize; $thumbHeight = ceil($height * ($AutoThumbSize * 100 / $width) / 100); $height = $thumbHeight; $width = $thumbWidth; } if ($height > $AutoThumbSize) { $thumbHeight = $AutoThumbSize; $thumbWidth = ceil($width * ($AutoThumbSize * 100 / $height) / 100); } $thumbImage = @imagecreatetruecolor($thumbWidth, $thumbHeight); if ($ext == "gif" && !isset($gifHack)) { $colorTransparent = @imagecolortransparent($srcImg); @imagepalettecopy($srcImg, $thumbImage); @imagecolortransparent($thumbImage, $colorTransparent); @imagetruecolortopalette($thumbImage, true, 256); } else { if ($ext == "png") { @ImageColorTransparent($thumbImage, @ImageColorAllocate($thumbImage, 0, 0, 0)); @ImageAlphaBlending($thumbImage, false); } } @imagecopyresampled($thumbImage, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $srcWidth, $srcHeight); if ($ext == "jpg") { @imagejpeg($thumbImage, $thumbFile, 100); } else { if ($ext == "gif") { if (isset($gifHack) && $gifHack == true) { $thumbFile = isc_substr($thumbFile, 0, -3) . "jpg"; @imagejpeg($thumbImage, $thumbFile, 100); } else { @imagegif($thumbImage, $thumbFile); } } else { @imagepng($thumbImage, $thumbFile); } } @imagedestroy($thumbImage); @imagedestroy($srcImg); // Change the permissions on the thumbnail file isc_chmod($thumbFile, ISC_WRITEABLE_FILE_PERM); return $thumbFileName; }
/** * Faster method than only calling imagecopyresampled() * * @return boolean Success/fail */ function fastImageCopyResampled(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $system, $quality = 3) { /* Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. 1 = Up to 600 times faster. Poor results, just uses imagecopyresized but removes black edges. 2 = Up to 95 times faster. Images may appear too sharp, some people may prefer it. 3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled. 4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images. 5 = No speedup. Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled. */ if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; } if (preg_match("/png/", $system[0]) || preg_match("/gif/", $system[0])) { $colorcount = imagecolorstotal($src_image); if ($colorcount <= 256 && $colorcount != 0) { imagetruecolortopalette($dst_image, true, $colorcount); imagepalettecopy($dst_image, $src_image); $transparentcolor = imagecolortransparent($src_image); imagefill($dst_image, 0, 0, $transparentcolor); imagecolortransparent($dst_image, $transparentcolor); } else { imageAlphaBlending($dst_image, false); imageSaveAlpha($dst_image, true); //If the image has Alpha blending, lets save it } } if ($quality < 5 && ($dst_w * $quality < $src_w || $dst_h * $quality < $src_h)) { $temp = imagecreatetruecolor($dst_w * $quality + 1, $dst_h * $quality + 1); if (preg_match("/png/", $system[0])) { $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 } imagecopyresized($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h); imagecopyresampled($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality); imagedestroy($temp); } else { imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); } return true; }
private function SaveQValueAssociationImage() { if (!array_key_exists('associationimage', $_FILES) || $_FILES['associationimage']['error'] !== 0 || strtolower(substr($_FILES['associationimage']['type'], 0, 6)) !== 'image/') { return false; } // Attempt to set the memory limit setImageFileMemLimit($_FILES['associationimage']['tmp_name']); // Generate the destination path $randomDir = strtolower(chr(rand(65, 90))); $destPath = realpath(ISC_BASE_PATH . '/' . GetConfig('ImageDirectory')); if (!is_dir($destPath . '/' . $randomDir)) { if (!@mkdir($destPath . '/' . $randomDir, 0777)) { $randomDir = ''; } } $destFile = GenRandFileName($_FILES['associationimage']['name'], 'category'); $destPath = $destPath . '/' . $randomDir . '/' . $destFile; $returnPath = $randomDir . '/' . $destFile; $tmp = explode('.', $_FILES['associationimage']['name']); $ext = strtolower($tmp[count($tmp) - 1]); if ($ext == 'jpg') { $srcImg = imagecreatefromjpeg($_FILES['associationimage']['tmp_name']); } else { if ($ext == 'gif') { $srcImg = imagecreatefromgif($_FILES['associationimage']['tmp_name']); if (!function_exists('imagegif')) { $gifHack = 1; } } else { $srcImg = imagecreatefrompng($_FILES['associationimage']['tmp_name']); } } $srcWidth = imagesx($srcImg); $srcHeight = imagesy($srcImg); $widthLimit = GetConfig('BrandImageWidth'); $heightLimit = GetConfig('BrandImageHeight'); // If the image is small enough, simply move it and leave it as is if ($srcWidth <= $widthLimit && $srcHeight <= $heightLimit) { imagedestroy($srcImg); move_uploaded_file($_FILES['associationimage']['tmp_name'], $destPath); return $returnPath; } // Otherwise, the image needs to be resized $attribs = getimagesize($_FILES['associationimage']['tmp_name']); $width = $attribs[0]; $height = $attribs[1]; if ($width > $widthLimit) { $height = ceil($widthLimit / $width * $height); $width = $widthLimit; } if ($height > $heightLimit) { $width = ceil($heightLimit / $height * $width); $height = $heightLimit; } $dstImg = imagecreatetruecolor($width, $height); if ($ext == "gif" && !isset($gifHack)) { $colorTransparent = imagecolortransparent($srcImg); imagepalettecopy($srcImg, $dstImg); imagecolortransparent($dstImg, $colorTransparent); imagetruecolortopalette($dstImg, true, 256); } else { if ($ext == "png") { ImageColorTransparent($dstImg, ImageColorAllocate($dstImg, 0, 0, 0)); ImageAlphaBlending($dstImg, false); } } imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight); if ($ext == "jpg") { imagejpeg($dstImg, $destPath, 100); } else { if ($ext == "gif") { if (isset($gifHack) && $gifHack == true) { $thumbFile = isc_substr($destPath, 0, -3) . "jpg"; imagejpeg($dstImg, $destPath, 100); } else { imagegif($dstImg, $destPath); } } else { imagepng($dstImg, $destPath); } } @imagedestroy($dstImg); @imagedestroy($srcImg); @unlink($_FILES['associationimage']['tmp_name']); // Change the permissions on the thumbnail file isc_chmod($returnPath, ISC_WRITEABLE_FILE_PERM); return $returnPath; }
<?php header("Content-type: image/gif"); // Obtenemos la imagen original $imagen = imagecreatefromjpeg(include "flickr_back.php"); // Convertimos la imagen a indexada imagetruecolortopalette($imagen, true, 256); // Esta será la imagen para la escala de grises $escala = imagecreatefromgif("images/escala.gif"); // Copiamos la paleta de escala a la imagen imagepalettecopy($imagen, $escala); imagedestroy($escala); imagegif($imagen); imagedestroy($imagen);
/** * Generate a thumbnail version of a particular image. * * @param string The file system path of the image to create a thumbnail of. * @param string The file system path of the name/location to save the thumbnail. * @param int The maximum width of the image. * @param boolean If the image is small enough, copy it to destLocation, otherwise just return. */ function GenerateThumbnail($sourceLocation, $destLocation, $maxWidth, $maxHeight = null) { if (is_null($maxHeight)) { $maxHeight = $maxWidth; } if ($sourceLocation == '' || !file_exists($sourceLocation)) { return false; } else { if (!is_dir(dirname($destLocation)) || !is_writable(dirname($destLocation))) { return false; } } // A list of thumbnails too $tmp = explode(".", $sourceLocation); $ext = isc_strtolower($tmp[count($tmp) - 1]); $attribs = @getimagesize($sourceLocation); $srcWidth = $attribs[0]; $srcHeight = $attribs[1]; if (!is_array($attribs)) { return false; } // Check if we have enough available memory to create this image - if we don't, attempt to bump it up SetImageFileMemLimit($sourceLocation); if ($ext == "jpg") { $srcImg = @imagecreatefromjpeg($sourceLocation); } else { if ($ext == "gif") { $srcImg = @imagecreatefromgif($sourceLocation); if (!function_exists("imagegif")) { $gifHack = 1; } } else { $srcImg = @imagecreatefrompng($sourceLocation); } } if (!$srcImg) { return false; } // This image dimensions. Simply copy and return if ($srcWidth <= $maxWidth && $srcHeight <= $maxHeight) { @imagedestroy($srcImg); if ($sourceLocation != $destLocation && copy($sourceLocation, $destLocation)) { return true; } } // Make sure the thumb has a constant height $width = $srcWidth; $thumbWidth = $srcWidth; $height = $srcHeight; $thumbHeight = $srcHeight; if ($width > $maxWidth) { $thumbWidth = $maxWidth; $thumbHeight = $maxWidth / $srcWidth * $srcHeight; } else { $thumbHeight = $maxHeight; $thumbWidth = $maxHeight / $srcHeight * $srcWidth; } $thumbImage = @imagecreatetruecolor($thumbWidth, $thumbHeight); if ($ext == "gif" && !isset($gifHack)) { $colorTransparent = @imagecolortransparent($srcImg); @imagepalettecopy($srcImg, $thumbImage); @imagecolortransparent($thumbImage, $colorTransparent); @imagetruecolortopalette($thumbImage, true, 256); } else { if ($ext == "png") { @ImageColorTransparent($thumbImage, @ImageColorAllocate($thumbImage, 0, 0, 0)); @ImageAlphaBlending($thumbImage, false); } } @imagecopyresampled($thumbImage, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $srcWidth, $srcHeight); if ($ext == "jpg") { @imagejpeg($thumbImage, $destLocation, 100); } else { if ($ext == "gif") { if (isset($gifHack) && $gifHack == true) { $thumbFile = isc_substr($thumbFile, 0, -3) . "jpg"; @imagejpeg($thumbImage, $destLocation, 100); } else { @imagegif($thumbImage, $destLocation); } } else { @imagepng($thumbImage, $destLocation); } } @imagedestroy($thumbImage); @imagedestroy($srcImg); // Change the permissions on the thumbnail file isc_chmod($destLocation, ISC_WRITEABLE_FILE_PERM); return true; }
function Main($path, $width, $height, $dst_file, $header = false) { if (!isset($path)) { return array(0, "イメージのパスが設定されていません。"); } if (!file_exists($path)) { return array(0, "指定されたパスにファイルが見つかりません。"); } // 画像の大きさをセット if ($width) { $this->imgMaxWidth = $width; } if ($height) { $this->imgMaxHeight = $height; } $size = @GetimageSize($path); $re_size = $size; //アスペクト比固定処理 if ($this->imgMaxWidth != 0) { $tmp_w = $size[0] / $this->imgMaxWidth; } if ($this->imgMaxHeight != 0) { $tmp_h = $size[1] / $this->imgMaxHeight; } if ($tmp_w > 1 || $tmp_h > 1) { if ($this->imgMaxHeight == 0) { if ($tmp_w > 1) { $re_size[0] = $this->imgMaxWidth; $re_size[1] = $size[1] * $this->imgMaxWidth / $size[0]; } } else { if ($tmp_w > $tmp_h) { $re_size[0] = $this->imgMaxWidth; $re_size[1] = $size[1] * $this->imgMaxWidth / $size[0]; } else { $re_size[1] = $this->imgMaxHeight; $re_size[0] = $size[0] * $this->imgMaxHeight / $size[1]; } } } $imagecreate = function_exists("imagecreatetruecolor") ? "imagecreatetruecolor" : "imagecreate"; $imageresize = function_exists("imagecopyresampled") ? "imagecopyresampled" : "imagecopyresized"; switch ($size[2]) { // gif形式 case "1": if (function_exists("imagecreatefromgif")) { $src_im = imagecreatefromgif($path); $dst_im = $imagecreate($re_size[0], $re_size[1]); $transparent = imagecolortransparent($src_im); $colorstotal = imagecolorstotal($src_im); $dst_im = imagecreate($re_size[0], $re_size[1]); if (0 <= $transparent && $transparent < $colorstotal) { imagepalettecopy($dst_im, $src_im); imagefill($dst_im, 0, 0, $transparent); imagecolortransparent($dst_im, $transparent); } $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); if (function_exists("imagegif")) { // 画像出力 if ($header) { header("Content-Type: image/gif"); imagegif($dst_im); return ""; } else { $dst_file = $dst_file . ".gif"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imagegif($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); } else { // 画像出力 if ($header) { header("Content-Type: image/png"); imagepng($dst_im); return ""; } else { $dst_file = $dst_file . ".png"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imagepng($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); } } else { // サムネイル作成不可の場合(旧バージョン対策) $dst_im = imageCreate($re_size[0], $re_size[1]); imageColorAllocate($dst_im, 255, 255, 214); //背景色 // 枠線と文字色の設定 $black = imageColorAllocate($dst_im, 0, 0, 0); $red = imageColorAllocate($dst_im, 255, 0, 0); imagestring($dst_im, 5, 10, 10, "GIF {$size['0']}x{$size['1']}", $red); imageRectangle($dst_im, 0, 0, $re_size[0] - 1, $re_size[1] - 1, $black); // 画像出力 if ($header) { header("Content-Type: image/png"); imagepng($dst_im); return ""; } else { $dst_file = $dst_file . ".png"; imagepng($dst_im, $dst_file); } imagedestroy($src_im); imagedestroy($dst_im); } break; // jpg形式 // jpg形式 case "2": $src_im = imageCreateFromJpeg($path); $dst_im = $imagecreate($re_size[0], $re_size[1]); $imageresize($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); // 画像出力 if ($header) { header("Content-Type: image/jpeg"); imageJpeg($dst_im); return ""; } else { $dst_file = $dst_file . ".jpg"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imageJpeg($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); break; // png形式 // png形式 case "3": $src_im = imageCreateFromPNG($path); $colortransparent = imagecolortransparent($src_im); $has_alpha = ord(file_get_contents($path, false, null, 25, 1)) & 0x4; if ($colortransparent > -1 || $has_alpha) { $dst_im = $imagecreate($re_size[0], $re_size[1]); // アルファチャンネルが存在する場合はそちらを使用する if ($has_alpha) { imagealphablending($dst_im, false); imagesavealpha($dst_im, true); } imagepalettecopy($dst_im, $src_im); imagefill($dst_im, 0, 0, $colortransparent); imagecolortransparent($dst_im, $colortransparent); imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); } else { $dst_im = $imagecreate($re_size[0], $re_size[1]); imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $re_size[0], $re_size[1], $size[0], $size[1]); imagecolorstotal($src_im) == 0 ? $colortotal = 65536 : ($colortotal = imagecolorstotal($src_im)); imagetruecolortopalette($dst_im, true, $colortotal); } // 画像出力 if ($header) { header("Content-Type: image/png"); imagepng($dst_im); return ""; } else { $dst_file = $dst_file . ".png"; if ($re_size[0] == $size[0] && $re_size[1] == $size[1]) { // サイズが同じ場合には、そのままコピーする。(画質劣化を防ぐ) copy($path, $dst_file); } else { imagepng($dst_im, $dst_file); } } imagedestroy($src_im); imagedestroy($dst_im); break; default: return array(0, "イメージの形式が不明です。"); } return array(1, $dst_file); }