function image_createThumb($src, $dest, $maxWidth, $maxHeight, $quality = 75) { if (file_exists($src) && isset($dest)) { // path info $destInfo = pathInfo($dest); // image src size $srcSize = getImageSize($src); // image dest size $destSize[0] = width, $destSize[1] = height $srcRatio = $srcSize[0] / $srcSize[1]; // width/height ratio $destRatio = $maxWidth / $maxHeight; if ($destRatio > $srcRatio) { $destSize[1] = $maxHeight; $destSize[0] = $maxHeight * $srcRatio; } else { $destSize[0] = $maxWidth; $destSize[1] = $maxWidth / $srcRatio; } // path rectification if ($destInfo['extension'] == "gif") { $dest = substr_replace($dest, 'jpg', -3); } // true color image, with anti-aliasing $destImage = imageCreateTrueColor($destSize[0], $destSize[1]); // imageAntiAlias($destImage,true); // src image switch ($srcSize[2]) { case 1: //GIF $srcImage = imageCreateFromGif($src); break; case 2: //JPEG $srcImage = imageCreateFromJpeg($src); break; case 3: //PNG $srcImage = imageCreateFromPng($src); break; default: return false; break; } // resampling imageCopyResampled($destImage, $srcImage, 0, 0, 0, 0, $destSize[0], $destSize[1], $srcSize[0], $srcSize[1]); // generating image switch ($srcSize[2]) { case 1: case 2: imageJpeg($destImage, $dest, $quality); break; case 3: imagePng($destImage, $dest); break; } return true; } else { return 'No such File'; } }
function resize_image_crop($src_image, $width, $height) { $src_width = imageSX($src_image); $src_height = imageSY($src_image); $width = $width <= 0 ? $src_width : $width; $height = $height <= 0 ? $src_height : $height; $prop_width = $src_width / $width; $prop_height = $src_height / $height; if ($prop_height > $prop_width) { $crop_width = $src_width; $crop_height = round($prop_width * $height); $srcX = 0; $srcY = round($src_height / 2) - round($crop_height / 2); } else { $crop_width = round($prop_height * $width); $crop_height = $src_height; $srcX = round($src_width / 2) - round($crop_width / 2); $srcY = 0; } $new_image = imageCreateTrueColor($width, $height); $tmp_image = imageCreateTrueColor($crop_width, $crop_height); imageCopy($tmp_image, $src_image, 0, 0, $srcX, $srcY, $crop_width, $crop_height); imageCopyResampled($new_image, $tmp_image, 0, 0, 0, 0, $width, $height, $crop_width, $crop_height); imagedestroy($tmp_image); image_unsharp_mask($new_image); return $new_image; }
function imageResize($file, $info, $destination) { $height = $info[1]; //высота $width = $info[0]; //ширина //определяем размеры будущего превью $y = 150; if ($width > $height) { $x = $y * ($width / $height); } else { $x = $y / ($height / $width); } $to = imageCreateTrueColor($x, $y); switch ($info['mime']) { case 'image/jpeg': $from = imageCreateFromJpeg($file); break; case 'image/png': $from = imageCreateFromPng($file); break; case 'image/gif': $from = imageCreateFromGif($file); break; default: echo "No prevue"; break; } imageCopyResampled($to, $from, 0, 0, 0, 0, imageSX($to), imageSY($to), imageSX($from), imageSY($from)); imagepng($to, $destination); imagedestroy($from); imagedestroy($to); }
function create_thumb($path, $thumb_path, $width = THUMB_WIDTH, $height = THUMB_HEIGHT) { $image_info = getImageSize($path); // see EXIF for faster way switch ($image_info['mime']) { case 'image/gif': if (imagetypes() & IMG_GIF) { // not the same as IMAGETYPE $o_im = @imageCreateFromGIF($path); } else { throw new Exception('GIF images are not supported'); } break; case 'image/jpeg': if (imagetypes() & IMG_JPG) { $o_im = @imageCreateFromJPEG($path); } else { throw new Exception('JPEG images are not supported'); } break; case 'image/png': if (imagetypes() & IMG_PNG) { $o_im = @imageCreateFromPNG($path); } else { throw new Exception('PNG images are not supported'); } break; case 'image/wbmp': if (imagetypes() & IMG_WBMP) { $o_im = @imageCreateFromWBMP($path); } else { throw new Exception('WBMP images are not supported'); } break; default: throw new Exception($image_info['mime'] . ' images are not supported'); break; } list($o_wd, $o_ht, $html_dimension_string) = $image_info; $ratio = $o_wd / $o_ht; $t_ht = $width; $t_wd = $height; if (1 > $ratio) { $t_wd = round($o_wd * $t_wd / $o_ht); } else { $t_ht = round($o_ht * $t_ht / $o_wd); } $t_wd = $t_wd < 1 ? 1 : $t_wd; $t_ht = $t_ht < 1 ? 1 : $t_ht; $t_im = imageCreateTrueColor($t_wd, $t_ht); imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht); imagejpeg($t_im, $thumb_path, 85); chmod($thumb_path, 0664); imageDestroy($o_im); imageDestroy($t_im); return array($t_wd, $t_ht); }
function generate_thumbnail($file, $mime) { global $config; gd_capabilities(); list($file_type, $exact_type) = explode("/", $mime); if (_JB_GD_INSTALLED && ($file_type = "image")) { if ($exact_type != "gif" && $exact_type != "png" && $exact_type != "jpeg") { return false; } if ($exact_type == "gif" && !_JB_GD_GIF) { return false; } if ($exact_type == "png" && !_JB_GD_PNG) { return false; } if ($exact_type == "jpeg" && !_JB_GD_JPG) { return false; } // Load up the original and get size // NOTE: use imageCreateFromString to avoid to have to check what type of image it is $original = imageCreateFromString(file_get_contents($file)); $original_w = imagesX($original); $original_h = imagesY($original); // Only if the image is really too big, resize it // NOTE: if image is smaller than target size, don't do anything. // We *could* copy the original to filename_thumb, but since it's the same // it would be a waste of precious resources if ($original_w > $config['uploader']['thumb_w'] || $original_h > $config['uploader']['thumb_h']) { // If original is wider than it's high, resize the width and vice versa // NOTE: '>=' cause otherwise it's possible that $scale isn't computed if ($original_w >= $original_h) { $scaled_w = $config['uploader']['thumb_w']; // Figure out how much smaller that target is than original // and apply it to height $scale = $config['uploader']['thumb_w'] / $original_w; $scaled_h = ceil($original_h * $scale); } elseif ($original_w <= $original_h) { $scaled_h = $config['uploader']['thumb_h']; $scale = $config['uploader']['thumb_h'] / $original_h; $scaled_w = ceil($original_w * $scale); } } else { // Break out of if($file_type = image) since no resize is possible return false; } // Scale the image $scaled = imageCreateTrueColor($scaled_w, $scaled_h); imageCopyResampled($scaled, $original, 0, 0, 0, 0, $scaled_w, $scaled_h, $original_w, $original_h); // Store thumbs in jpeg, hope no one minds the 100% quality lol imageJpeg($scaled, $file . "_thumb", 100); // Let's be nice to our server imagedestroy($scaled); imagedestroy($original); return true; } }
/** * Draws the pie chart, with optional supersampled anti-aliasing. * @param int $aa */ public function draw($aa = 4) { $this->canvas = imageCreateTrueColor($this->width, $this->height); // Set anti-aliasing for the pie chart. imageAntiAlias($this->canvas, true); imageFilledRectangle($this->canvas, 0, 0, $this->width, $this->height, $this->_convertColor($this->backgroundColor)); $total = 0; $sliceStart = -90; // Start at 12 o'clock. $titleHeight = $this->_drawTitle(); $legendWidth = $this->_drawLegend($titleHeight); // Account for the space occupied by the legend and its padding. $pieCentreX = ($this->width - $legendWidth) / 2; // Account for the space occupied by the title. $pieCentreY = $titleHeight + ($this->height - $titleHeight) / 2; // 10% padding on the top and bottom of the pie. $pieDiameter = round(min($this->width - $legendWidth, $this->height - $titleHeight) * 0.85); foreach ($this->slices as $slice) { $total += $slice['value']; } // If anti-aliasing is enabled, we supersample the pie to work around // the fact that GD does not provide anti-aliasing natively. if ($aa > 0) { $ssDiameter = $pieDiameter * $aa; $ssCentreX = $ssCentreY = $ssDiameter / 2; $superSample = imageCreateTrueColor($ssDiameter, $ssDiameter); imageFilledRectangle($superSample, 0, 0, $ssDiameter, $ssDiameter, $this->_convertColor($this->backgroundColor)); foreach ($this->slices as $slice) { $sliceWidth = 360 * $slice['value'] / $total; // Skip slices that are too small to draw / be visible. if ($sliceWidth == 0) { continue; } $sliceEnd = $sliceStart + $sliceWidth; imageFilledArc($superSample, $ssCentreX, $ssCentreY, $ssDiameter, $ssDiameter, $sliceStart, $sliceEnd, $this->_convertColor($slice['color']), IMG_ARC_PIE); // Move along to the next slice. $sliceStart = $sliceEnd; } imageCopyResampled($this->canvas, $superSample, $pieCentreX - $pieDiameter / 2, $pieCentreY - $pieDiameter / 2, 0, 0, $pieDiameter, $pieDiameter, $ssDiameter, $ssDiameter); imageDestroy($superSample); } else { // Draw the slices. foreach ($this->slices as $slice) { $sliceWidth = 360 * $slice['value'] / $total; // Skip slices that are too small to draw / be visible. if ($sliceWidth == 0) { continue; } $sliceEnd = $sliceStart + $sliceWidth; imageFilledArc($this->canvas, $pieCentreX, $pieCentreY, $pieDiameter, $pieDiameter, $sliceStart, $sliceEnd, $this->_convertColor($slice['color']), IMG_ARC_PIE); // Move along to the next slice. $sliceStart = $sliceEnd; } } }
function Resize($maxwidth = 10000, $maxheight, $imagename, $filetype, $how = 'keep_aspect') { $target_temp_file = tempnam("jinn/temp", "gdlib_"); unlink($target_temp_file); $target_temp_file .= '.' . $filetype; if (!$maxheight) { $maxheight = 10000; } if (!$maxwidth) { $maxwidth = 10000; } $qual = 100; $filename = $imagename; $ext = $filetype; list($curwidth, $curheight) = getimagesize($filename); $factor = min($maxwidth / $curwidth, $maxheight / $curheight); $sx = 0; $sy = 0; $sw = $curwidth; $sh = $curheight; $dx = 0; $dy = 0; $dw = $curwidth * $factor; $dh = $curheight * $factor; if ($ext == "JPEG") { $src = ImageCreateFromJPEG($filename); } if ($ext == "GIF") { $src = ImageCreateFromGIF($filename); } if ($ext == "PNG") { $src = ImageCreateFromPNG($filename); } if (function_exists('ImageCreateTrueColor')) { $dst = ImageCreateTrueColor($dw, $dh); } else { $dst = ImageCreate($dw, $dh); } if (function_exists('ImageCopyResampled')) { imageCopyResampled($dst, $src, $dx, $dy, $sx, $sy, $dw, $dh, $sw, $sh); } else { imageCopyResized($dst, $src, $dx, $dy, $sx, $sy, $dw, $dh, $sw, $sh); } if ($ext == "JPEG") { ImageJPEG($dst, $target_temp_file, $qual); } if ($ext == "PNG") { ImagePNG($dst, $target_temp_file, $qual); } if ($ext == "GIF") { ImagePNG($dst, $target_temp_file, $qual); } ImageDestroy($dst); return $target_temp_file; }
function image_create_thumb($img_file_path, $thumb_file_path, $width, $height) { if (($image = _image_load($img_file_path)) === false) { return false; } $src_x = 0; $src_y = 0; $src_w = 0; $src_h = 0; $dst_w = 0; $dst_h = 0; _image_calculate_dimensions(imagesx($image), imagesy($image), $width, $height, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); //die('initial image width is ' . $original_width . ', requested width is ' . $width . ', new image width is ' . $new_img_width . ', src_x is ' . $src_x); $thumb_image = imageCreateTrueColor($dst_w, $dst_h); imageCopyResampled($thumb_image, $image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); return _image_save($thumb_file_path, $thumb_image); }
function resize($width = 400, $height = 400, $aspectradio = true) { $o_wd = imagesx($this->image); $o_ht = imagesy($this->image); if (isset($aspectradio) && $aspectradio) { $w = round($o_wd * $height / $o_ht); $h = round($o_ht * $width / $o_wd); if ($height - $h < $width - $w) { $width =& $w; } else { $height =& $h; } } $this->temp = imageCreateTrueColor($width, $height); imageCopyResampled($this->temp, $this->image, 0, 0, 0, 0, $width, $height, $o_wd, $o_ht); $this->sync(); return; }
function resizeImage($file, $max_x, $max_y, $forcePng = false) { if ($max_x <= 0 || $max_y <= 0) { $max_x = 5; $max_y = 5; } $src = BASEDIR . '/avatars/' . $file; list($width, $height, $type) = getImageSize($src); $scale = min($max_x / $width, $max_y / $height); $newWidth = $width * $scale; $newHeight = $height * $scale; $img = imagecreatefromstring(file_get_contents($src)); $black = imagecolorallocate($img, 0, 0, 0); $resizedImage = imageCreateTrueColor($newWidth, $newHeight); imagecolortransparent($resizedImage, $black); imageCopyResampled($resizedImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imageDestroy($img); unlink($src); if (!$forcePng) { switch ($type) { case IMAGETYPE_JPEG: imageJpeg($resizedImage, BASEDIR . '/avatars/' . $file); break; case IMAGETYPE_GIF: imageGif($resizedImage, BASEDIR . '/avatars/' . $file); break; case IMAGETYPE_PNG: imagePng($resizedImage, BASEDIR . '/avatars/' . $file); break; default: imagePng($resizedImage, BASEDIR . '/avatars/' . $file); break; } } else { imagePng($resizedImage, BASEDIR . '/avatars/' . $file . '.png'); } return; }
/** * Shows an image, possibly resized in the desired... size! * * Call it like: localhost/index.php?r=images/show&src=images/boats/3/boat.jpg&width=100 * If only one dimension is given, aspect ratio is maintained. * If both dimensions are given, and are far from aspect ratio, * the action tries to return a meaningful portion of the image. */ public function show($src = '', $width = '', $height = '') { // sometime in the future, we should cache the result of the resize to make it fast. // we do not check for "is_file", because sometimes we are asked to resize remote images. //if (!is_file($src)) // throw new CHttpException(404); // if nothing given, simply redirect to the file. if ($width == '' && $height == '' || $width == 0 && $height == 0) { $this->_send_headers($src); header('Location: ' . $src); Yii::app()->end(); } // we need to resize.. if (!($source_image = $this->_img_load($src))) { throw new CHttpException(500); } $original_width = imagesx($source_image); $original_height = imagesy($source_image); $requested_width = $width; $requested_height = $height; $src_x = 0; $src_y = 0; $dst_x = 0; $dst_y = 0; $src_w = 0; $src_h = 0; $dst_w = 0; $dst_h = 0; $this->_calculate_dimensions($original_width, $original_height, $requested_width, $requested_height, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h); //die('initial image width is ' . $original_width . ', requested width is ' . $width . ', new image width is ' . $new_img_width . ', src_x is ' . $src_x); $target_image = imageCreateTrueColor($dst_w, $dst_h); imageCopyResampled($target_image, $source_image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); // send it. $this->_send_headers($src); $this->_img_send($target_image, $src); }
/** * Copy an existing internal image resource, or part of it, to this Image instance * @param resource existing internal image resource as source for the copy * @param int x x-coordinate where the copy starts * @param int y y-coordinate where the copy starts * @param int resourceX starting x coordinate of the source image resource * @param int resourceY starting y coordinate of the source image resource * @param int width resulting width of the copy (not of the resulting image) * @param int height resulting height of the copy (not of the resulting image) * @param int resourceWidth width of the source image resource to copy * @param int resourceHeight height of the source image resource to copy * @return null */ protected function copyResource($resource, $x, $y, $resourceX, $resourceY, $width, $height, $resourceWidth, $resourceHeight) { if (!imageCopyResampled($this->resource, $resource, $x, $y, $resourceX, $resourceY, $width, $height, $resourceWidth, $resourceHeight)) { if (!imageCopyResized($this->resource, $resource, $x, $y, $resourceX, $resourceY, $width, $height, $resourceWidth, $resourceHeight)) { throw new ImageException('Could not copy the image resource'); } } $transparent = imageColorAllocate($this->resource, 0, 0, 0); imageColorTransparent($this->resource, $transparent); $this->width = $width; $this->height = $height; }
function thumb_img3($src, $width, $height, $save_file) { $get_size = getImageReSize2($width, $height, imagesx($src), imagesy($src)); //$thumb = ImageCreate($get_size[0],$get_size[1]); $thumb = imagecreatetruecolor($get_size[0], $get_size[1]); // ImageCopyResized($thumb,$src,0,0,0,0,$get_size[0],$get_size[1],ImageSX($src),ImageSY($src)); imageCopyResampled($thumb, $src, 0, 0, 0, 0, $get_size[0], $get_size[1], ImageSX($src), ImageSY($src)); ImageJPEG($thumb, $save_file); ImageDestroy($thumb); }
/** * Resamples (convert/resize) an image file. You can specify a new width, height and type * @param string $file Image path and file name * @param int $w Width * @param int $h Height * @param string $type Supported image types: gif,png,jpg,bmp,xbmp,wbmp. Defaults to jpg * @return boolean */ public static function imageResample($file, $w, $h, $type = null) { if (!function_exists('imagecreatefromstring')) { Raxan::log('Function imagecreatefromstring does not exists - The GD image processing library is required.', 'warn', 'Raxan::imageResample'); return false; } $info = @getImageSize($file); if ($info) { // maintain aspect ratio if ($h == 0) { $h = $info[1] * ($w / $info[0]); } if ($w == 0) { $w = $info[0] * ($h / $info[1]); } if ($w == 0 && $h == 0) { $w = $info[0]; $h = $info[1]; } // resize/resample image $img = @imageCreateFromString(file_get_contents($file)); if (!$img) { return false; } $newImg = function_exists('imagecreatetruecolor') ? imageCreateTrueColor($w, $h) : imageCreate($w, $h); if (function_exists('imagecopyresampled')) { imageCopyResampled($newImg, $img, 0, 0, 0, 0, $w, $h, $info[0], $info[1]); } else { imageCopyResized($newImg, $img, 0, 0, 0, 0, $w, $h, $info[0], $info[1]); } imagedestroy($img); $type = !$type ? $info[2] : strtolower(trim($type)); if ($type == 1 || $type == 'gif') { $f = 'imagegif'; } else { if ($type == 3 || $type == 'png') { $f = 'imagepng'; } else { if ($type == 6 || $type == 16 || $type == 'bmp' || $type == 'xbmp') { $f = 'imagexbm'; } else { if ($type == 15 || $type == 'wbmp') { $f = 'image2wbmp'; } else { $f = 'imagejpeg'; } } } } if (function_exists($f)) { $f($newImg, $file); } imagedestroy($newImg); return true; } return false; }
function resizePhoto($vstup, $vystup, $width, $height, $aspectratio, $quality) { /* $vstup //cesta k původnímu obrázku $vystup //cesta ke zmenšenému obrázku $width //šířka zmenšeného obrázku $height //délka zmenšeného obrázku $aspectratio //zachovávat poměr stran (0/1) $quality //komprese (100 - nejlepsi) - doporucuji 75 */ if (file_exists($vstup)) { //nejprve zjistíme, zda-li byl zadán vstup a existuje $vstup = ImageCreateFromJPEG($vstup); //načteme si obrázek do proměnné } else { echo "resizePhoto: Nebyl zadán vstup !"; return false; } $vstup_wd = imagesx($vstup); //zjistíme šířku původního obrázku $vstup_ht = imagesy($vstup); //zjistíme délku původního obrázku if ($vstup_wd <= $width && $vstup_ht <= $height) { //pokud je obrázek menší než požadovaná velikost nebudeme počítat nové hodnoty $width = $vstup_wd; $height = $vstup_ht; } else { if ($aspectratio) { //pokud je zaplý aspect ratio spočítáme novou velikost v daném poměru $w = round($vstup_wd * $height / $vstup_ht); $h = round($vstup_ht * $width / $vstup_wd); if ($height - $h < $width - $w) { $width =& $w; } else { $height =& $h; } } } $temp = imageCreateTrueColor($width, $height); //vytvoříme obrázek o rozměrech zmenšeného obrázku imageCopyResampled($temp, $vstup, 0, 0, 0, 0, $width, $height, $vstup_wd, $vstup_ht); //obrázky zkopíruje na sebe, takže dojde vlastně ke zmenšení výsledného obrázku ImageJPEG($temp, $vystup, $quality); //uložíme zmenšený obrázek na výstup imagedestroy($vstup); //uvolnime pamět imagedestroy($temp); //uvolnime pamět }
/** * Open the source and target image for processing it * * @param Asido_TMP &$tmp * @return boolean * @access protected */ function __open(&$tmp) { $error_source = false; $error_target = false; // get image dimensions // if ($i = @getImageSize($tmp->source_filename)) { $tmp->image_width = $i[0]; $tmp->image_height = $i[1]; } // image type ? // switch (@$i[2]) { case 1: // GIF $error_source = false == ($tmp->source = @imageCreateFromGIF($tmp->source_filename)); $error_target = false == ($tmp->target = imageCreateTrueColor($tmp->image_width, $tmp->image_height)); $error_target &= imageCopyResampled($tmp->target, $tmp->source, 0, 0, 0, 0, $tmp->image_width, $tmp->image_height, $tmp->image_width, $tmp->image_height); break; case 2: // JPG $error_source = false == ($tmp->source = imageCreateFromJPEG($tmp->source_filename)); $error_target = false == ($tmp->target = imageCreateFromJPEG($tmp->source_filename)); break; case 3: // PNG $error_source = false == ($tmp->source = @imageCreateFromPNG($tmp->source_filename)); $error_target = false == ($tmp->target = @imageCreateFromPNG($tmp->source_filename)); break; case 15: // WBMP $error_source = false == ($tmp->source = @imageCreateFromWBMP($tmp->source_filename)); $error_target = false == ($tmp->target = @imageCreateFromWBMP($tmp->source_filename)); break; case 16: // XBM $error_source = false == ($tmp->source = @imageCreateFromXBM($tmp->source_filename)); $error_target = false == ($tmp->target = @imageCreateFromXBM($tmp->source_filename)); break; case 4: // SWF // SWF case 5: // PSD // PSD case 6: // BMP // BMP case 7: // TIFF(intel byte order) // TIFF(intel byte order) case 8: // TIFF(motorola byte order) // TIFF(motorola byte order) case 9: // JPC // JPC case 10: // JP2 // JP2 case 11: // JPX // JPX case 12: // JB2 // JB2 case 13: // SWC // SWC case 14: // IFF // IFF default: $error_source = false == ($tmp->source = @imageCreateFromString(file_get_contents($tmp->source_filename))); $error_target = false == ($tmp->source = @imageCreateFromString(file_get_contents($tmp->source_filename))); break; } return !($error_source || $error_target); }
/** * Creates a new image given an original path, a new path, a target width and height. * Optionally crops image to exactly match given width and height. * @params string $originalPath, string $newpath, int $width, int $height, bool $crop * @return void */ public function create($originalPath, $newPath, $width, $height, $crop = false) { // first, we grab the original image. We shouldn't ever get to this function unless the image is valid $imageSize = @getimagesize($originalPath); $oWidth = $imageSize[0]; $oHeight = $imageSize[1]; $finalWidth = 0; //For cropping, this is really "scale to width before chopping extra height" $finalHeight = 0; //For cropping, this is really "scale to height before chopping extra width" $do_crop_x = false; $do_crop_y = false; $crop_src_x = 0; $crop_src_y = 0; // first, if what we're uploading is actually smaller than width and height, we do nothing if ($oWidth < $width && $oHeight < $height) { $finalWidth = $oWidth; $finalHeight = $oHeight; $width = $oWidth; $height = $oHeight; } else { if ($crop && ($height >= $oHeight && $width <= $oWidth)) { //crop to width only -- don't scale anything $finalWidth = $oWidth; $finalHeight = $oHeight; $height = $oHeight; $do_crop_x = true; } else { if ($crop && ($width >= $oWidth && $height <= $oHeight)) { //crop to height only -- don't scale anything $finalHeight = $oHeight; $finalWidth = $oWidth; $width = $oWidth; $do_crop_y = true; } else { // otherwise, we do some complicated stuff // first, we divide original width and height by new width and height, and find which difference is greater $wDiff = $oWidth / $width; $hDiff = $oHeight / $height; if (!$crop && $wDiff > $hDiff) { //no cropping, just resize down based on target width $finalWidth = $width; $finalHeight = $oHeight / $wDiff; } else { if (!$crop) { //no cropping, just resize down based on target height $finalWidth = $oWidth / $hDiff; $finalHeight = $height; } else { if ($crop && $wDiff > $hDiff) { //resize down to target height, THEN crop off extra width $finalWidth = $oWidth / $hDiff; $finalHeight = $height; $do_crop_x = true; } else { if ($crop) { //resize down to target width, THEN crop off extra height $finalWidth = $width; $finalHeight = $oHeight / $wDiff; $do_crop_y = true; } } } } } } } //Calculate cropping to center image if ($do_crop_x) { /* //Get half the difference between scaled width and target width, // and crop by starting the copy that many pixels over from the left side of the source (scaled) image. $nudge = ($width / 10); //I have *no* idea why the width isn't centering exactly -- this seems to fix it though. $crop_src_x = ($finalWidth / 2.00) - ($width / 2.00) + $nudge; */ $crop_src_x = round(($oWidth - $width * $oHeight / $height) * 0.5); } if ($do_crop_y) { /* //Calculate cropping... //Get half the difference between scaled height and target height, // and crop by starting the copy that many pixels down from the top of the source (scaled) image. $crop_src_y = ($finalHeight / 2.00) - ($height / 2.00); */ $crop_src_y = round(($oHeight - $height * $oWidth / $width) * 0.5); } //create "canvas" to put new resized and/or cropped image into if ($crop) { $image = @imageCreateTrueColor($width, $height); } else { $image = @imageCreateTrueColor($finalWidth, $finalHeight); } switch ($imageSize[2]) { case IMAGETYPE_GIF: $im = @imageCreateFromGIF($originalPath); break; case IMAGETYPE_JPEG: $im = @imageCreateFromJPEG($originalPath); break; case IMAGETYPE_PNG: $im = @imageCreateFromPNG($originalPath); break; } if ($im) { // Better transparency - thanks for the ideas and some code from mediumexposure.com if ($imageSize[2] == IMAGETYPE_GIF || $imageSize[2] == IMAGETYPE_PNG) { $trnprt_indx = imagecolortransparent($im); // If we have a specific transparent color if ($trnprt_indx >= 0) { // Get the original image's transparent color's RGB values $trnprt_color = imagecolorsforindex($im, $trnprt_indx); // Allocate the same color in the new image resource $trnprt_indx = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); // Completely fill the background of the new image with allocated color. imagefill($image, 0, 0, $trnprt_indx); // Set the background color for new image to transparent imagecolortransparent($image, $trnprt_indx); } else { if ($imageSize[2] == IMAGETYPE_PNG) { // Turn off transparency blending (temporarily) imagealphablending($image, false); // Create a new transparent color for image $color = imagecolorallocatealpha($image, 0, 0, 0, 127); // Completely fill the background of the new image with allocated color. imagefill($image, 0, 0, $color); // Restore transparency blending imagesavealpha($image, true); } } } $res = @imageCopyResampled($image, $im, 0, 0, $crop_src_x, $crop_src_y, $finalWidth, $finalHeight, $oWidth, $oHeight); if ($res) { switch ($imageSize[2]) { case IMAGETYPE_GIF: $res2 = imageGIF($image, $newPath); break; case IMAGETYPE_JPEG: $compression = defined('AL_THUMBNAIL_JPEG_COMPRESSION') ? AL_THUMBNAIL_JPEG_COMPRESSION : 80; $res2 = imageJPEG($image, $newPath, $compression); break; case IMAGETYPE_PNG: $res2 = imagePNG($image, $newPath); break; } } } }
public static function resize_full_image($src, $size, $width, $height) { if ($size[0] > $width || $size[1] > $height) { $ratio = $size[0] > $size[1] ? $size[0] / $width : $size[1] / $height; $dst_width = $size[0] / $ratio; $dst_height = $size[1] / $ratio; } else { $dst_width = $size[0]; $dst_height = $size[1]; } $dst = imageCreateTrueColor($dst_width, $dst_height); imageCopyResampled($dst, $src, 0, 0, 0, 0, $dst_width, $dst_height, $size[0], $size[1]); return $dst; }
/** * Generate images of alternate sizes. */ function resizeImage($cnvrt_arry) { global $platform, $imgs, $cnvrt_path, $reqd_image, $convert_writable, $convert_magick, $convert_GD, $convert_cmd, $cnvrt_alt, $cnvrt_mesgs, $compat_quote; if (empty($imgs) || $convert_writable == FALSE) { return; } if ($convert_GD == TRUE && !($gd_version = gdVersion())) { return; } if ($cnvrt_alt['no_prof'] == TRUE) { $strip_prof = ' +profile "*"'; } else { $strip_prof = ''; } if ($cnvrt_alt['mesg_on'] == TRUE) { $str = ''; } foreach ($imgs as $img_file) { if ($cnvrt_alt['indiv'] == TRUE && $img_file != $reqd_image['file']) { continue; } $orig_img = $reqd_image['pwd'] . '/' . $img_file; $cnvrtd_img = $cnvrt_path . '/' . $cnvrt_arry['prefix'] . $img_file; if (!is_file($cnvrtd_img)) { $img_size = GetImageSize($orig_img); $height = $img_size[1]; $width = $img_size[0]; $area = $height * $width; $maxarea = $cnvrt_arry['maxwid'] * $cnvrt_arry['maxwid'] * 0.9; $maxheight = $cnvrt_arry['maxwid'] * 0.75 + 1; if ($area > $maxarea || $width > $cnvrt_arry['maxwid'] || $height > $maxheight) { if ($width / $cnvrt_arry['maxwid'] >= $height / $maxheight) { $dim = 'W'; } if ($height / $maxheight >= $width / $cnvrt_arry['maxwid']) { $dim = 'H'; } if ($dim == 'W') { $cnvt_percent = round(0.9375 * $cnvrt_arry['maxwid'] / $width * 100, 2); } if ($dim == 'H') { $cnvt_percent = round(0.75 * $cnvrt_arry['maxwid'] / $height * 100, 2); } // convert it if ($convert_magick == TRUE) { // Image Magick image conversion if ($platform == 'Win32' && $compat_quote == TRUE) { $winquote = '"'; } else { $winquote = ''; } exec($winquote . $convert_cmd . ' -geometry ' . $cnvt_percent . '%' . ' -quality ' . $cnvrt_arry['qual'] . ' -sharpen ' . $cnvrt_arry['sharpen'] . $strip_prof . ' "' . $orig_img . '"' . ' "' . $cnvrtd_img . '"' . $winquote); $using = $cnvrt_mesgs['using IM']; } elseif ($convert_GD == TRUE) { // GD image conversion if (eregi('\\.jpg$|\\.jpeg$', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) { $src_img = imageCreateFromJpeg($orig_img); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) { $src_img = imageCreateFromPng($orig_img); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) { $src_img = imageCreateFromGif($orig_img); } else { continue; } $src_width = imageSx($src_img); $src_height = imageSy($src_img); $dest_width = $src_width * ($cnvt_percent / 100); $dest_height = $src_height * ($cnvt_percent / 100); if ($gd_version >= 2) { $dst_img = imageCreateTruecolor($dest_width, $dest_height); imageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height); } else { $dst_img = imageCreate($dest_width, $dest_height); imageCopyResized($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $src_width, $src_height); } imageDestroy($src_img); if (eregi('\\.jpg$|\\.jpeg$/i', $img_file) == TRUE && (imageTypes() & IMG_JPG) == TRUE) { imageJpeg($dst_img, $cnvrtd_img, $cnvrt_arry['qual']); } elseif (eregi('\\.gif$', $img_file) == TRUE && (imageTypes() & IMG_PNG) == TRUE) { imagePng($dst_img, $cnvrtd_img); } elseif (eregi('\\.gif$/i', $img_file) == TRUE && (imageTypes() & IMG_GIF) == TRUE) { imageGif($dst_img, $cnvrtd_img); } imageDestroy($dst_img); $using = $cnvrt_mesgs['using GD'] . $gd_version; } if ($cnvrt_alt['mesg_on'] == TRUE && is_file($cnvrtd_img)) { $str .= " <small>\n" . ' ' . $cnvrt_mesgs['generated'] . $cnvrt_arry['txt'] . $cnvrt_mesgs['converted'] . $cnvrt_mesgs['image_for'] . $img_file . $using . ".\n" . " </small>\n <br />\n"; } } } } if (isset($str)) { return $str; } }
/** * function _mainTransform (integer $posX=0, integer $posY=0, integer $width=0, integer $height=0, boolean $proportions = true) * * Process the image transform * * return boolean */ function _mainTransform($posX = 0, $posY = 0, $width = 0, $height = 0, $proportions = true) { $newImage = $this->imageDefine(); if (!$newImage) { return $this->debug($this->image . ' isn\'t JPG, GIF nor PGN'); } if ($proportions) { list($dX, $dY) = $this->proportions($this->data[0], $this->data[1]); list($width, $height) = array($this->data[0], $this->data[1]); } else { list($dX, $dY) = array($this->size[0], $this->size[1]); } list($posX, $posY) = $this->maxSize($posX, $posY, $width, $height); $thumb = $this->transparency($newImage, imageCreateTrueColor($dX, $dY)); imageCopyResampled($thumb, $newImage, 0, 0, $posX, $posY, $dX, $dY, $width, $height); if ($this->imageCreate($thumb)) { return true; } else { return $this->debug('A problem occours creating the image. I can\'t finish the task.'); } }
/** * Scale an image to the specified size using GD. */ function image_gd_resize($source, $destination, $width, $height) { if (!file_exists($source)) { return false; } $info = image_get_info($source); if (!$info) { return false; } $im = image_gd_open($source, $info['extension']); if (!$im) { return false; } $res = imageCreateTrueColor($width, $height); imageCopyResampled($res, $im, 0, 0, 0, 0, $width, $height, $info['width'], $info['height']); $result = image_gd_close($res, $destination, $info['extension']); imageDestroy($res); imageDestroy($im); return $result; }
function crop($options = array('source_image' => '', 'storage_dir' => '', 'base_filename' => '', 'extension' => '', 'crop_coords' => array('x' => '100', 'y' => '100', 'w' => '100', 'h' => '100'), 'target_size' => array('w' => '300', 'h' => '300'), 'cropped_filename_suffix' => '_cropped')) { if (isset($options['source_image'])) { $source_path = $options['source_image']; } else { $source_path = $options['storage_dir'] . DS . $options['base_filename'] . $options['extension']; } $this->fixOrientation($source_path); $original_dimensions = getImageSize($source_path); $cropped_image_filename = $options['storage_dir'] . DS . $options['base_filename'] . $options['cropped_filename_suffix'] . $options['extension']; $cropped_image_filename = str_replace(DS . DS, DS, $cropped_image_filename); $source_image_resource = $this->openImage($options['source_image']); //imageCreateFromJPEG($options['source_image']); $cropped_image_resource = imageCreateTrueColor($options['target_size']['w'], $options['target_size']['h']); // look for transparency in gif or png if ($original_dimensions[2] == IMAGETYPE_GIF || $original_dimensions[2] == IMAGETYPE_PNG) { $transparency = imagecolortransparent($source_image_resource); if ($transparency >= 0) { $transparent_color = imagecolorsforindex($source_image_resource, $transparency); $transparency = imagecolorallocate($cropped_image_resource, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); imagefill($cropped_image_resource, 0, 0, $transparency); imagecolortransparent($cropped_image_resource, $transparency); } elseif ($original_dimensions[2] == IMAGETYPE_PNG) { imagealphablending($cropped_image_resource, false); $color = imagecolorallocatealpha($cropped_image_resource, 0, 0, 0, 127); imagefill($cropped_image_resource, 0, 0, $color); imagesavealpha($cropped_image_resource, true); } } imageCopyResampled($cropped_image_resource, $source_image_resource, 0, 0, $options['crop_coords']['x'], $options['crop_coords']['y'], $options['target_size']['w'], $options['target_size']['h'], $options['crop_coords']['w'], $options['crop_coords']['h']); if ($this->saveImage($cropped_image_resource, $cropped_image_filename)) { imageDestroy($cropped_image_resource); imageDestroy($source_image_resource); return true; } else { imageDestroy($cropped_image_resource); imageDestroy($source_image_resource); return false; } }
protected function imageCopyResampled($src, $dstX = 0, $dstY = 0, $srcX = 0, $srcY = 0, $dstW = null, $dstH = null, $srcW = null, $srcH = null) { $imageDetails = $this->buildImage($src); if ($imageDetails === false) { return false; } list($src, $srcWidth, $srcHeight) = $imageDetails; if (is_null($dstW)) { $dstW = $this->width - $dstW; } if (is_null($dstH)) { $dstH = $this->height - $dstY; } if (is_null($srcW)) { $srcW = $srcWidth - $srcX; } if (is_null($srcH)) { $srcH = $srcHeight - $srcY; } return imageCopyResampled($this->image, $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH); }
$file_size = $_FILES['myfile']['size']; $sql = "select count(id)+1 from pe.file_allegati allegati where pratica={$idpratica} and allegato={$idallegato}"; if ($desc) { $sql = "insert into pe.file_allegati (pratica,allegato,nome_file,tipo_file,size_file,ordine,chk,uidins,tmsins,form,note) values ({$idpratica},{$idallegato},'{$file_name}','{$file_type}',{$file_size},({$sql}),1," . $_SESSION["USER_ID"] . "," . time() . ",'{$form}','{$desc}');"; } else { $sql = "insert into pe.file_allegati (pratica,allegato,nome_file,tipo_file,size_file,ordine,chk,uidins,tmsins,form) values ({$idpratica},{$idallegato},'{$file_name}','{$file_type}',{$file_size},({$sql}),1," . $_SESSION["USER_ID"] . "," . time() . ",'{$form}');"; } $db->sql_query($sql); $_SESSION["ADD_NEW"] = 1; if (DEBUG) { echo $sql; } //creo l'oggetto immagine se il file è tipo immagine if (ereg("jpeg", $file_type)) { $im_file_name = $updDir . $file_name; $image_attribs = getimagesize($im_file_name); $im_old = @imageCreateFromJpeg($im_file_name); //setto le dimensioni del thumbnail $th_max_width = 100; $th_max_height = 100; $ratio = $width > $height ? $th_max_width / $image_attribs[0] : $th_max_height / $image_attribs[1]; $th_width = $image_attribs[0] * $ratio; $th_height = $image_attribs[1] * $ratio; $im_new = imagecreatetruecolor($th_width, $th_height); //@imageantialias ($im_new,true); //creo la thumbnail e la copio sul disco $th_file_name = $updDir . "tmb/tmb_" . $file_name; @imageCopyResampled($im_new, $im_old, 0, 0, 0, 0, $th_width, $th_height, $image_attribs[0], $image_attribs[1]); @imageJpeg($im_new, $th_file_name, 100); ini_set('max_execution_time', $var); }
/** * Create a thumbnail for an image * * @param string $sImage Full path of the original image * @param string $sDestination Full path for the newly created thumbnail * @param int $nMaxW Max width of the thumbnail * @param int $nMaxH Max height of the thumbnail * @param bool $bRatio TRUE to keep the aspect ratio and FALSE to not keep it * @param bool $bSkipCdn Skip the CDN routine * @return mixed FALSE on failure, TRUE or NULL on success */ public function createThumbnail($sImage, $sDestination, $nMaxW, $nMaxH, $bRatio = true, $bSkipCdn = false) { if (!$this->_load($sImage)) { return false; } if (defined('PHPFOX_IS_HOSTED_SCRIPT')) { $sImage = str_replace(PHPFOX_DIR, rtrim(Phpfox::getParam('core.rackspace_url'), '/') . '/', $sImage); } if ($bRatio) { list($nNewW, $nNewH) = $this->_calcSize($nMaxW, $nMaxH); } else { return $this->createSquareThumbnail($sImage, $sDestination, $nMaxW, $nMaxH, $bSkipCdn); } if ($this->nW < $nNewW || $this->nH < $nNewH || $this->nW == $nNewW && $this->nH == $nNewH) { @copy($this->sPath, $sDestination); if (Phpfox::getParam('core.allow_cdn')) { if ($bSkipCdn === true && $nNewW > 150 || $bSkipCdn === 'force_skip') { } else { Phpfox::getLib('cdn')->put($sDestination); } } return true; } // if (function_exists('memory_get_usage') && ($sMemoryLimit = @ini_get('memory_limit')) && $sMemoryLimit != -1) if (!PHPFOX_SAFE_MODE) { @ini_set('memory_limit', '500M'); /* $iMemoryLimit = (int) $sMemoryLimit; $iMemoryUsage = memory_get_usage(); $iFreeMemory = $iMemoryLimit - $iMemoryUsage; $iTotalMemory = $this->nW * $this->nH * ($this->_aInfo[2] == 2 ? 5 : 2) + 7372.8 + sqrt(sqrt($this->nW * $this->nH)); $iTotalMemory += 166000; if ($iFreeMemory > 0 AND $iTotalMemory > $iFreeMemory AND $iTotalMemory <= ($iMemoryLimit * 3) && !PHPFOX_SAFE_MODE) { ini_set('memory_limit', $iMemoryLimit + $iTotalMemory); $sMemoryLimit = @ini_get('memory_limit'); $iMemoryLimit = (int) $sMemoryLimit; $iMemoryUsage = memory_get_usage(); $iFreeMemory = $iMemoryLimit - $iMemoryUsage; } if ($iFreeMemory > 0 AND $iTotalMemory > $iFreeMemory) { return Phpfox_Error::set('Ran out of memory.', E_USER_ERROR); } */ } switch ($this->_aInfo[2]) { case 1: $hFrm = imageCreateFromGif($this->sPath); break; case 3: $hFrm = imageCreateFromPng($this->sPath); break; default: $hFrm = imageCreateFromJpeg($this->sPath); break; } if ((int) $nNewH === 0) { $nNewH = 1; } if ((int) $nNewW === 0) { $nNewW = 1; } $hTo = imagecreatetruecolor($nNewW, $nNewH); switch ($this->sType) { case 'gif': $iBlack = imagecolorallocate($hTo, 0, 0, 0); imagecolortransparent($hTo, $iBlack); break; case 'jpeg': case 'jpg': case 'jpe': imagealphablending($hTo, true); break; case 'png': imagealphablending($hTo, false); imagesavealpha($hTo, true); break; } if ($this->thumbLargeThenPic === false && $this->nH <= $nNewH && $this->nW <= $nNewW) { $hTo = $hFrm; } else { if ($hFrm) { imageCopyResampled($hTo, $hFrm, 0, 0, 0, 0, $nNewW, $nNewH, $this->nW, $this->nH); } } if (file_exists($sDestination)) { if (@unlink($sDestination) != true) { @rename($sDestination, $sDestination . '_' . rand(10, 99)); } } switch ($this->sType) { case 'gif': if (!$hTo) { @copy($this->sPath, $sDestination); } else { @imagegif($hTo, $sDestination); } break; case 'png': imagepng($hTo, $sDestination); imagealphablending($hTo, false); imagesavealpha($hTo, true); break; default: @imagejpeg($hTo, $sDestination); break; } @imageDestroy($hTo); @imageDestroy($hFrm); if (($this->sType == 'jpg' || $this->sType == 'jpeg') && function_exists('exif_read_data')) { @getimagesize($sImage, $aInfo); if (isset($aInfo['APP1']) && preg_match('/exif/i', $aInfo['APP1'])) { $exif = @exif_read_data($sImage); if (!empty($exif['Orientation'])) { switch ($exif['Orientation']) { case 1: case 2: break; case 3: case 4: // 90 degrees $this->rotate($sDestination, 'right'); // 180 degrees $this->rotate($sDestination, 'right'); break; case 5: case 6: // 90 degrees right $this->rotate($sDestination, 'right'); break; case 7: case 8: // 90 degrees left $this->rotate($sDestination, 'left'); break; default: break; } } } } if (Phpfox::getParam('core.allow_cdn')) { if ($bSkipCdn === true && $nNewW > 150 || $bSkipCdn === 'force_skip') { } else { Phpfox::getLib('cdn')->put($sDestination); } } }
public function MakeSpecialThumbnail($o_file, $fileName, $quality, $width, $height) { $image_info = getImageSize($o_file); switch ($image_info['mime']) { case 'image/gif': if (imagetypes() & IMG_GIF) { // not the same as IMAGETYPE $o_im = imageCreateFromGIF($o_file); } break; case 'image/jpeg': if (imagetypes() & IMG_JPG) { $o_im = imageCreateFromJPEG($o_file); } break; case 'image/png': if (imagetypes() & IMG_PNG) { $o_im = imageCreateFromPNG($o_file); } break; case 'image/wbmp': if (imagetypes() & IMG_WBMP) { $o_im = imageCreateFromWBMP($o_file); } break; default: break; } $o_wd = imagesx($o_im); $o_ht = imagesy($o_im); $t_wd = $width; $t_ht = $height; // thumbnail width = target * original width / original height if ($o_ht > $o_wd) { $t_wd = round($o_wd * $height / $o_ht); $t_ht = $height; } else { $t_ht = round($o_ht * $width / $o_wd); $t_wd = $width; } if ($t_ht > $height) { $t_wd = round($o_wd * $height / $o_ht); $t_ht = $height; } $t_im = imageCreateTrueColor($width, $height); $white = imagecolorallocate($t_im, 255, 255, 255); imagefill($t_im, 0, 0, $white); $new_x = $new_x = 0; if ($t_wd > $t_ht) { // The image is longer $new_y = ($height - $t_ht) / 2; $new_x = ($width - $t_wd) / 2; } else { // The image is higher $new_y = ($height - $t_ht) / 2; $new_x = ($width - $t_wd) / 2; } imageCopyResampled($t_im, $o_im, $new_x, $new_y, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht); imageJPEG($t_im, $fileName, 100); imageDestroy($o_im); imageDestroy($t_im); return true; }
<?php ## Увеличение картинки со сглаживанием. $from = imageCreateFromJpeg("sample2.jpg"); $to = imageCreateTrueColor(2000, 2000); imageCopyResampled($to, $from, 0, 0, 0, 0, imageSX($to), imageSY($to), imageSX($from), imageSY($from)); header("Content-type: image/jpeg"); imageJpeg($to);
public function edit($path, $crop_x, $crop_y, $crop_w, $crop_h, $target_w, $target_h) { $imageSize = @getimagesize($path); $img_type = $imageSize[2]; //create "canvas" to put new resized and/or cropped image into $image = @imageCreateTrueColor($target_w, $target_h); switch($img_type) { case IMAGETYPE_GIF: $im = @imageCreateFromGIF($path); break; case IMAGETYPE_JPEG: $im = @imageCreateFromJPEG($path); break; case IMAGETYPE_PNG: $im = @imageCreateFromPNG($path); break; } if ($im) { // Better transparency - thanks for the ideas and some code from mediumexposure.com if (($img_type == IMAGETYPE_GIF) || ($img_type == IMAGETYPE_PNG)) { $trnprt_indx = imagecolortransparent($im); // If we have a specific transparent color if ($trnprt_indx >= 0) { // Get the original image's transparent color's RGB values $trnprt_color = imagecolorsforindex($im, $trnprt_indx); // Allocate the same color in the new image resource $trnprt_indx = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); // Completely fill the background of the new image with allocated color. imagefill($image, 0, 0, $trnprt_indx); // Set the background color for new image to transparent imagecolortransparent($image, $trnprt_indx); } else if ($img_type == IMAGETYPE_PNG) { // Turn off transparency blending (temporarily) imagealphablending($image, false); // Create a new transparent color for image $color = imagecolorallocatealpha($image, 0, 0, 0, 127); // Completely fill the background of the new image with allocated color. imagefill($image, 0, 0, $color); // Restore transparency blending imagesavealpha($image, true); } } $res = @imageCopyResampled($image, $im, 0, 0, $crop_x, $crop_y, $target_w, $target_h, $crop_w, $crop_h); if ($res) { switch($img_type) { case IMAGETYPE_GIF: $res2 = imageGIF($image, $path); break; case IMAGETYPE_JPEG: $compression = defined('AL_THUMBNAIL_JPEG_COMPRESSION') ? AL_THUMBNAIL_JPEG_COMPRESSION : 80; $res2 = imageJPEG($image, $path, $compression); break; case IMAGETYPE_PNG: $res2 = imagePNG($image, $path); break; } } } }
function cropAndResize($Media, $cropLeft, $cropTop, $cropWidth, $cropHeight, $resizeWidth, $resizeHeight) { $cropLeft = (int) $cropLeft; $cropTop = (int) $cropTop; $cropWidth = (int) $cropWidth; $cropHeight = (int) $cropHeight; $resizeWidth = (int) $resizeWidth; $resizeHeight = (int) $resizeHeight; $Image = imageCreateTrueColor($resizeWidth, $resizeHeight); $this->_adjustTransparency($Media->resources['gd'], $Image); if ($this->_isTransparent($Media->resources['gd'])) { imageCopyResized($Image, $Media->resources['gd'], 0, 0, $cropLeft, $cropTop, $resizeWidth, $resizeHeight, $cropWidth, $cropHeight); } else { imageCopyResampled($Image, $Media->resources['gd'], 0, 0, $cropLeft, $cropTop, $resizeWidth, $resizeHeight, $cropWidth, $cropHeight); } if ($this->_isResource($Image)) { $Media->resources['gd'] = $Image; return true; } return false; }
/** * Creates a thumbnail picture (jpg/png) of a big image * * @param boolean $rescale * @return string thumbnail */ public function makeThumbnail($rescale = false) { list($width, $height, $this->imageType) = @getImageSize($this->sourceFile); // check image size if ($this->checkSize($width, $height, $rescale)) { return false; } // try to extract the embedded thumbnail first (faster) $thumbnail = false; if (!$rescale && $this->useEmbedded) { $thumbnail = $this->extractEmbeddedThumbnail(); } if (!$thumbnail) { // calculate uncompressed filesize // and cancel to avoid a memory_limit error $memoryLimit = self::getMemoryLimit(); if ($memoryLimit && $memoryLimit != -1) { $fileSize = $width * $height * ($this->imageType == 3 ? 4 : 3); if ($fileSize * 2.1 + memory_get_usage() > $memoryLimit) { return false; } } // calculate new picture size $x = $y = 0; if ($this->quadratic) { $newWidth = $newHeight = $this->maxWidth; if ($this->appendSourceInfo) { $newHeight -= self::$sourceInfoLineHeight * 2; } if ($width > $height) { $x = ceil(($width - $height) / 2); $width = $height; } else { $y = ceil(($height - $width) / 2); $height = $width; } } else { $maxHeight = $this->maxHeight; if ($this->appendSourceInfo) { $maxHeight -= self::$sourceInfoLineHeight * 2; } if ($this->maxWidth / $width < $maxHeight / $height) { $newWidth = $this->maxWidth; $newHeight = round($height * ($newWidth / $width)); } else { $newHeight = $maxHeight; $newWidth = round($width * ($newHeight / $height)); } } // resize image $imageResource = false; // jpeg image if ($this->imageType == 2 && function_exists('imagecreatefromjpeg')) { $imageResource = @imageCreateFromJPEG($this->sourceFile); } // gif image if ($this->imageType == 1 && function_exists('imagecreatefromgif')) { $imageResource = @imageCreateFromGIF($this->sourceFile); } // png image if ($this->imageType == 3 && function_exists('imagecreatefrompng')) { $imageResource = @imageCreateFromPNG($this->sourceFile); } // could not create image if (!$imageResource) { return false; } // resize image if (function_exists('imageCreateTrueColor') && function_exists('imageCopyResampled')) { $imageNew = @imageCreateTrueColor($newWidth, $newHeight); imageAlphaBlending($imageNew, false); @imageCopyResampled($imageNew, $imageResource, 0, 0, $x, $y, $newWidth, $newHeight, $width, $height); imageSaveAlpha($imageNew, true); } else { if (function_exists('imageCreate') && function_exists('imageCopyResized')) { $imageNew = @imageCreate($newWidth, $newHeight); imageAlphaBlending($imageNew, false); @imageCopyResized($imageNew, $imageResource, 0, 0, $x, $y, $newWidth, $newHeight, $width, $height); imageSaveAlpha($imageNew, true); } else { return false; } } // create thumbnail ob_start(); if ($this->imageType == 1 && function_exists('imageGIF')) { @imageGIF($imageNew); $this->mimeType = 'image/gif'; } else { if (($this->imageType == 1 || $this->imageType == 3) && function_exists('imagePNG')) { @imagePNG($imageNew); $this->mimeType = 'image/png'; } else { if (function_exists('imageJPEG')) { @imageJPEG($imageNew, null, 90); $this->mimeType = 'image/jpeg'; } else { return false; } } } @imageDestroy($imageNew); $thumbnail = ob_get_contents(); ob_end_clean(); } if ($thumbnail && $this->appendSourceInfo && !$rescale) { $thumbnail = $this->appendSourceInfo($thumbnail); } return $thumbnail; }