function ThumbnailImage($path, $maxdimension = 100) { $this->maxdimension = $maxdimension; //check path is_file($path) or die("File: {$path} doesn't exist."); //check type $extension = substr($path, strpos($path, ".") + 1); $extension = strtolower($extension); in_array($extension, $this->types) or die("Incorrect file type."); $this->fileextension = $extension; $this->setMimeType($extension); //get dimensions by creating imageproperties $this->imageproperties = GetImageSize($path); //create image if ($extension == "jpeg" || $extension == "jpg") { $this->image = imagecreatefromJPEG($path); } elseif ($extension == "gif") { $this->image = imagecreatefromGIF($path); } elseif ($extension == "png") { $this->image = imagecreatefromPNG($path); } else { die("Couldn't create image."); } $this->createThumb(); }
function tile_img($file, $xorig, $yorig, $width, $height, $mode) { $size = getimagesize($file); $input_format = $size[2]; switch ($input_format) { case 1: $im = @imagecreatefromGIF($file); if (!$im) { $this->PrintError("tile_img:() Unable to open {$file} as a GIF."); return FALSE; } break; case 2: $im = @imagecreatefromJPEG($file); if (!$im) { $this->PrintError("tile_img(): Unable to open {$file} as a JPG."); return FALSE; } break; case 3: $im = @imagecreatefromPNG($file); if (!$im) { $this->PrintError("tile_img(): Unable to open {$file} as a PNG."); return FALSE; } break; default: $this->PrintError('tile_img(): Please select a gif, jpg, or png image.'); return FALSE; break; } if ($mode == 'scale') { imagecopyresized($this->img, $im, $xorig, $yorig, 0, 0, $width, $height, $size[0], $size[1]); return TRUE; } else { if ($mode == 'centeredtile') { $x0 = -floor($size[0] / 2); // Make the tile look better $y0 = -floor($size[1] / 2); } else { if ($mode = 'tile') { $x0 = 0; $y0 = 0; } } } // Actually draw the tile // But first on a temporal image. $tmp = ImageCreate($width, $height); if (!$tmp) { $this->PrintError('tile_img(): Could not create image resource.'); } for ($x = $x0; $x < $width; $x += $size[0]) { for ($y = $y0; $y < $height; $y += $size[1]) { imagecopy($tmp, $im, $x, $y, 0, 0, $size[0], $size[1]); } } // Copy the temporal image onto the final one. imagecopy($this->img, $tmp, $xorig, $yorig, 0, 0, $width, $height); // Free resources imagedestroy($tmp); imagedestroy($im); return TRUE; }
function imager_makeGray($img_path, &$temp = false) { $dirs = infra_dirs(); $type = imager_type($img_path); $name = md5($img_path); $temp = tmpfile(); fwrite($temp, ''); $meta = stream_get_meta_data($temp); $output_path = $meta['uri']; $type_img = exif_imagetype($img_path); $gd = gd_info(); if ($type_img == 3 and $gd['PNG Support'] == 1) { $img_png = imagecreatefromPNG($img_path); imagesavealpha($img_png, true); if ($img_png and imagefilter($img_png, IMG_FILTER_GRAYSCALE)) { imagepng($img_png, $output_path); } imagedestroy($img_png); } elseif ($type_img == 2) { $img = imagecreatefromJPEG($img_path); if ($img and imagefilter($img, IMG_FILTER_GRAYSCALE)) { imagejpeg($img, $output_path); } imagedestroy($img); /* if(!$color_total = imagecolorstotal($img_jpg)) { $color_total = 256; } imagetruecolortopalette( $img_jpg, FALSE, $color_total ); for( $c = 0; $c < $color_total; $c++ ) { $col = imagecolorsforindex( $img_jpg, $c ); $i = ( $col['red']+$col['green']+$col['blue'] )/3; imagecolorset( $img_jpg, $c, $i, $i, $i ); } @unlink( $output_path ); imagejpeg( $img_jpg, $output_path ); imagedestroy( $img_jpg );*/ } elseif ($type_img == 1) { $img = imagecreatefromGIF($img_path); if ($img and imagefilter($img, IMG_FILTER_GRAYSCALE)) { imagegif($img, $output_path); } imagedestroy($img); /*if(!$color_total = imagecolorstotal( $img_gif )) { $color_total = 256; } imagetruecolortopalette( $img_gif, FALSE, $color_total ); for( $c = 0; $c < $color_total; $c++ ) { $col = imagecolorsforindex( $img_gif, $c ); $i = ( $col['red']+$col['green']+$col['blue'] )/3; imagecolorset( $img_gif, $c, $i, $i, $i ); } @unlink( $output_path ); imagegif( $img_gif, $output_path ); imagedestroy( $img_gif );*/ } else { return $img_path; } return $output_path; }
function thumb($source_dir, $thumb_dir, $width = 85, $height = 85, $op = false) { $source_dir = Import::gz_iconv()->ec_iconv('UTF8', 'GB2312', $source_dir); $thumb_dir = Import::gz_iconv()->ec_iconv('UTF8', 'GB2312', $thumb_dir); $this->checkDir($thumb_dir); if (!file_exists($source_dir) && is_dir(dirname($source_dir))) { $this->seterror("不能生成缩略图,源文件不存在!<br />"); return false; } $DS = $this->DS; $data = getimagesize($source_dir); switch ($data[2]) { case 1: $im = @imagecreatefromgif($source_dir); break; case 2: $im = @imagecreatefromjpeg($source_dir); break; case 3: $im = @imagecreatefrompng($source_dir); break; } $srcW = imagesx($im); $this->setwidth($srcW); $srcH = imagesy($im); $this->setheight($srcH); /*if($srcW>$srcH){ //宽大于高 if($srcW<$width){ $width = $srcW; $height = $srcH*($width/$srcW); } }else{ //高大于宽 if($srcH<$height){ $height = $srcH; $width = $srcW*($height/$srcH); } } $tw = $width; $th = $height; $ni=imagecreatetruecolor($width,$height); //用白色填充 sscanf('FFFFFF', "%2x%2x%2x", $red, $green, $blue); $clr = imagecolorallocate($ni, $red, $green, $blue); imagefilledrectangle($ni, 0, 0, $width, $height, $clr); $mult = $width/$srcW; if($height/$srcH<$mult) { $mult = $height/$srcH; } $width = $srcW*$mult; $height =$srcH*$mult; $dst_x = ($tw - $width) / 2; $dst_y = ($th - $height) / 2; // imagecopyresized($ni,$im,0,0,0,0,$width,$height,$srcW,$srcH); //生成一般缩略图 imagecopyresampled($ni,$im, $dst_x, $dst_y, 0, 0,$width,$height,$srcW,$srcH); //生成高清缩略图 必须支持GD2 // imagecopyresampled($ni,$im, 0, 0, 0, 0,$width,$height,$srcW,$srcH); //生成高清缩略图 $cr = imagejpeg($ni,$thumb_dir); chmod($thumb_dir, 0777); */ $mult = $width / $srcW; if ($height / $srcH < $mult) { $mult = $height / $srcH; } $width = $srcW * $mult; $height = $srcH * $mult; /* $dst_x = ($tw - $width) / 2; $dst_y = ($th - $height) / 2; */ $ni = imagecreatetruecolor($width, $height); sscanf('FFFFFF', "%2x%2x%2x", $red, $green, $blue); $clr = imagecolorallocate($ni, $red, $green, $blue); imagefilledrectangle($ni, 0, 0, $width, $height, $clr); // imagecopyresized($ni,$im,0,0,0,0,$width,$height,$srcW,$srcH); //生成一般缩略图 //imagecopyresampled($ni,$im, $dst_x, $dst_y, 0, 0,$width,$height,$srcW,$srcH); //生成高清缩略图 必须支持GD2 imagecopyresampled($ni, $im, 0, 0, 0, 0, $width, $height, $srcW, $srcH); //生成高清缩略图 //imagecolorallocatealpha(); $cr = imagejpeg($ni, $thumb_dir); chmod($thumb_dir, 0777); if (!$cr) { $this->seterror("缩略图生成失败 <br />"); return false; } //是否添加水印 if ($this->is_upload) { if ($this->watermark == 1) { $iinfo = getimagesize($thumb_dir); $nimage = imagecreatetruecolor($iinfo[0], $iinfo[1]); $white = imagecolorallocate($nimage, 255, 255, 255); $black = imagecolorallocate($nimage, 0, 0, 0); $red = imagecolorallocate($nimage, 255, 0, 0); switch ($iinfo[2]) { case 1: $simage = imagecreatefromgif($thumb_dir); break; case 2: $simage = imagecreatefromjpeg($thumb_dir); break; case 3: $simage = imagecreatefrompng($thumb_dir); break; case 6: $simage = imagecreatefromwbmp($thumb_dir); break; default: $this->seterror("不支持的文件类 <br />型"); $this->is_upload = false; return false; } imagecopy($nimage, $simage, 0, 0, 0, 0, $iinfo[0], $iinfo[1]); switch ($this->watertype) { case 1: //加水印字符串 imagestring($nimage, 2, 3, $iinfo[1] - 15, $this->waterstring, $black); break; case 2: $inn = getimagesize($this->waterimg); switch ($inn[2]) { //1:GIG 2:JPEG 3:PNG case 1: $in = @imagecreatefromGIF($this->waterimg); break; case 2: $in = @imagecreatefromJPEG($this->waterimg); break; case 3: $in = @imagecreatefromPNG($this->waterimg); break; } $wh = imagecolorallocate($in, 255, 255, 255); imagecolortransparent($in, $wh); imagecopy($nimage, $in, rand(20, $iinfo[0] - 100), rand(20, $iinfo[1] - 100), 0, 0, $inn[0], $inn[1]); imagedestroy($in); break; } switch ($iinfo[2]) { case 1: imagejpeg($nimage, $thumb_dir); break; case 2: imagejpeg($nimage, $thumb_dir); break; case 3: imagepng($nimage, $thumb_dir); break; case 6: imagewbmp($nimage, $thumb_dir); break; } } //end 水印IF } //end 是否符合上传IF return true; }
/** * The filename must have an extension and it must be one of the following: jpg, gif, png, jpeg, or bmp. * If a thumbnail already exists in the source files' directory, this function automatically appends an * incremental numeric suffix. * * If the output filename already exists on disk, this function will revert to auto-creating a thumbnail filename. * * @param string $filename The filename to process * @param string $outputFilename The name of the file to write to * @param string $outputDirectory The name of the directory that holds our outputfile * @param integer $width The width in pixels of the created thumbnail * @param integer $height The height in pixels of the created thumbnail * @param boolean $max If set to true then the image aspect ratio is preserved * with the max length of either width or height being {@link $width} or {@link $height} * @param boolean $crop If set to true, the image will be cropped to the dimensions specified. * If set to false, the image will be resized. * * @return string the name of the file where the thumbnail can be found * @throws ThumbnailsException If any of the parameters are invalid. * * @see generateThumbnail(...) */ protected function generateThumbnail($filename, $outputFilename, $outputDirectory, $width = 0, $height = 0, $max = false, $crop = false, $ext = null, $quality = null) { if (!is_file($filename)) { throw new ThumbnailsException("Source file does not exist '" . $filename . "'"); } $path = pathinfo($filename); if (empty($path['extension'])) { throw new ThumbnailsException("Source file does not have an extension '" . $filename . "'"); } $originalExt = strtolower(trim($path['extension'])); if (empty($ext)) { $ext = $originalExt; } if (!in_array($ext, $this->supportedExtensions)) { throw new ThumbnailsException("Thumbnail file extension [{$ext}] is not supported"); } if ($outputDirectory != null && !is_dir($outputDirectory)) { throw new ThumbnailsException("Output directory does not exist or is not a valid directory '{$outputDirectory}'"); } //parameter validation if ($width === 0 && $height === 0) { throw new ThumbnailsException("Width and/or height must be specified"); } if (!is_int($width)) { throw new ThumbnailsException("Width [{$width}] is not a valid integer"); } if (!is_int($height)) { throw new ThumbnailsException("Height [{$height}] is not a valid integer"); } if ($width < 0) { throw new ThumbnailsException("Width cannot be negative"); } if ($height < 0) { throw new ThumbnailsException("Height cannot be negative"); } if ($max === true && ($width === 0 || $height === 0)) { throw new ThumbnailsException("If max is true then width and height must be positive"); } if ($crop === true && ($width === 0 || $height === 0 || $max === true)) { throw new ThumbnailsException("If crop is true then width and height must be positive and max must be false"); } if ($outputDirectory == null) { $outputDirectory = $path['dirname']; } else { $outputDirectory = rtrim($outputDirectory, '/'); } //check for existing thumbnail in same directory, increment filename $outfile = $outputFilename == null ? "{$path['filename']}{$this->autoNameSuffix}.{$ext}" : $outputFilename; $inc = 1; while (is_file("{$outputDirectory}/{$outfile}")) { $outfile = "{$path['filename']}{$this->autoNameSuffix}-{$inc}.{$ext}"; $inc++; } //list($origwidth, $origheight) = getimagesize($filename); //build ImageMagick operation if ($this->convertMode == 'exec_imagick') { if ($max === true) { $op = "-resize {$width}x{$height}\\>"; } else { if ($crop === true) { if ($this->imageMagickCompatMode == false) { // As of IM v6.3.8-3 the special resize option flag '^' was added // to make cutting the image to fit easier. $op = "-resize {$width}x{$height}\\>^ -gravity {$this->cropGravity} -crop {$width}x{$height}+0+0 +repage"; } else { // Complex trickiness to perform the cut to fit resize // Calculate the thumbnail aspect ratio. // > 1 is a wide thumb // < 1 is a tall thumb // 1 is a square thumb $thumb_aspect_ratio = $width / $height; // Get the dimensions of the image $dimensions = getimagesize($filename); $image_aspect_ratio = $dimensions[0] / $dimensions[1]; // Definitions: // width-crop = Resize the image to the full width of the thumbnail and trim the top and bottom // height-crop = Resize the image to the full height of the thumbnail and trip the sides // Behavior: // If image_aspect_ratio < thumb_aspect_ratio perform a width-crop // If image_aspect_ratio >= thumb_aspect_ratio perform a height-crop if ($image_aspect_ratio < $thumb_aspect_ratio) { $op = "-resize {$width}x\\> -gravity {$this->cropGravity} -crop {$width}x{$height}+0+0 +repage"; } else { $op = "-resize x{$height}\\> -gravity {$this->cropGravity} -crop {$width}x{$height}+0+0 +repage"; } } } else { if ($height === 0) { $op = "-resize {$width}x\\>"; } else { if ($width === 0) { $op = "-resize x{$height}\\>"; } else { $op = "-resize {$width}x{$height}!\\>"; } } } } $qualityArg = $quality ? '-quality ' . escapeshellarg($quality) : ($qualityArg = ''); $outPath = escapeshellarg("{$outputDirectory}/{$outfile}"); //full ImageMagick command; redirect STDERR to STDOUT $filename = escapeshellarg($filename); $cmd = "{$this->pathToImageMagickConvert} {$filename} {$op} {$qualityArg} {$outPath} 2>&1"; $retval = 1; $output = array(); $this->Logger->debug("Excecuting [{$cmd}]"); exec($cmd, $output, $retval); if ($retval > 0) { throw new ThumbnailsException("Generation failed '" . $cmd . "\n" . implode("\n", $output) . "'"); } } elseif ($this->convertMode == 'pecl_imagick') { $image = new Imagick($filename); if ($max == true) { $image->scaleImage($width, $height, true); } elseif ($crop === true) { // Because Imagick::cropThumbnailImage() doesn't support different gravities, // we need to expand the functionality out here. PITA! if ($this->cropGravity == 'center') { $image->cropThumbnailImage($width, $height); } else { // Resize full image by default so the smallest edge is // the max width/height if ($image->getImageWidth() > $image->getImageHeight()) { $image->scaleImage(0, $height); } else { $image->scaleImage($width, 0); } // Then crop out the needed section. $image_width = $image->getImageWidth(); $image_height = $image->getImageHeight(); switch (strtolower($this->cropGravity)) { case 'northwest': $x = $image_width - $width; $y = 0; break; case 'north': $x = $image_width / 2 - $width / 2; $y = 0; break; case 'northeast': $x = 0; $y = 0; break; case 'west': $x = 0; $y = $image_height / 2 - $height / 2; break; case 'east': $x = $image_width - $width; $y = $image_height / 2 - $height / 2; break; case 'southwest': $x = 0; $y = $image_height - $height; break; case 'south': $x = $image_width / 2 - $width / 2; $y = $image_height - $height; break; case 'southeast': $x = $image_width - $width; $y = $image_height - $height; break; default: throw new ThumbnailsException("Unsupported crop gravity: {$this->cropGravity}"); } $x = floor($x); $y = floor($y); $image->cropImage($width, $height, $x, $y); } } elseif ($height === 0) { $image->scaleImage($width, $height); } elseif ($width === 0) { $image->scaleImage($width, $height); } else { $image->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1); } if ($quality) { $image->setImageCompressionQuality($quality); } // Imagick will infer the file format from the filename extension $image->writeImage("{$outputDirectory}/{$outfile}"); $image->clear(); $image->destroy(); } elseif ($this->convertMode == 'gd') { $origImage = null; switch ($originalExt) { case 'jpg': case 'jpeg': $origImage = imagecreatefromJPEG($filename); break; case 'gif': $origImage = imagecreatefromGIF($filename); break; case 'png': $origImage = imagecreatefromPNG($filename); break; case 'bmp': $origImage = imagecreatefromWBMP($filename); break; default: throw new ThumbnailsException('GD does not know how to handle .' . $originalExt . ' files.'); } if (function_exists('imageantialias')) { imageantialias($origImage, true); } $image_attr = getimagesize($filename); $image_width = $image_attr[0]; $image_height = $image_attr[1]; $dst_x = 0; $dst_y = 0; $src_x = null; $src_y = null; $dst_w = null; $dst_h = null; $src_w = null; $src_h = null; if ($max === true) { // resize to dimensions, preserving aspect ratio $src_x = 0; $src_y = 0; $src_w = $image_width; $src_h = $image_height; if ($image_width > $image_height) { $dst_w = $width; $dst_h = (int) floor($image_height * ($width / $image_width)); } else { $dst_h = $height; $dst_w = (int) floor($image_width * ($height / $image_height)); } } else { if ($crop === true) { // crop the image with cropGravity $dst_w = $width; $dst_h = $height; // By default, resize the whole image $src_w = $image_attr[0]; $src_h = $image_attr[1]; $thumb_aspect_ratio = $width / $height; $image_aspect_ratio = $image_attr[0] / $image_attr[1]; if ($image_aspect_ratio < $thumb_aspect_ratio) { // width-crop $src_w = $image_attr[0]; // original-width $resize_ratio = $image_attr[0] / $width; // original-width / thumbnail-width $src_h = floor($height * $resize_ratio); // thumbnail-height * original-width / thumbnail-width } else { // height-crop $src_h = $image_attr[1]; // original-height $resize_ratio = $image_attr[1] / $height; // original-height / thumbnail-height $src_w = floor($width * $resize_ratio); // thumbnail-width * original-height / thumbnail-height } $dst_x = 0; $dst_y = 0; $dst_w = $width; $dst_h = $height; switch (strtolower($this->cropGravity)) { case 'center': $src_x = floor(($image_attr[0] - $src_w) / 2); $src_y = floor(($image_attr[1] - $src_h) / 2); break; case 'northeast': $src_x = 0; $src_y = 0; break; case 'north': $src_x = floor(($image_attr[0] - $src_w) / 2); $src_y = 0; break; case 'south': $src_x = floor($image_attr[0] - $image_width); $src_y = floor($image_attr[1] - $image_height); break; default: throw new ThumbnailsException("Unsupported cropGravity for GD: {$this->cropGravity}"); } } else { if ($height === 0) { // resize to max width, preserving aspect ratio $src_x = 0; $src_y = 0; $src_w = $image_width; $src_h = $image_height; $dst_w = $width; $dst_h = $image_height * ($width / $image_width); } else { if ($width === 0) { // resize to max height, preserving aspect ratio $src_x = 0; $src_y = 0; $src_w = $image_width; $src_h = $image_height; $dst_h = $height; $dst_w = $image_width * ($height / $image_height); } else { // resize, ignoring aspect ratio $src_x = 0; $src_y = 0; $src_w = $image_width; $src_h = $image_height; $dst_w = $width; $dst_h = $height; } } } } $newImage = imagecreateTrueColor($dst_w, $dst_h); //preserve transparency $transindex = -1; if ($ext == 'gif') { imagealphablending($newImage, false); $transindex = imagecolortransparent($origImage); if ($transindex >= 0) { $transcol = imagecolorsforindex($origImage, $transindex); $transindex = imagecolorallocatealpha($newImage, $transcol['red'], $transcol['green'], $transcol['blue'], 127); imagefill($newImage, 0, 0, $transindex); } } @imagecopyResampled($newImage, $origImage, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); //preserve transparency if ($ext == 'gif') { if ($transindex >= 0) { imagecolortransparent($newImage, $transindex); for ($y = 0; $y < $dst_h; ++$y) { for ($x = 0; $x < $dst_w; ++$x) { if ((imagecolorat($newImage, $x, $y) >> 24 & 0x7f) >= 100) { imagesetpixel($newImage, $x, $y, $transindex); } } } imagetruecolortopalette($newImage, true, 255); imagesavealpha($newImage, false); } } // echo "<pre>"; var_dump($dst_h); die("</pre>"); $outfilepath = "{$outputDirectory}/{$outfile}"; switch ($ext) { case 'jpg': case 'jpeg': imageJPEG($newImage, $outfilepath, $quality); break; case 'gif': imageGIF($newImage, $outfilepath); break; case 'png': imagePNG($newImage, $outfilepath, $quality); break; case 'bmp': imageWBMP($newImage, $outfilepath); break; } imagedestroy($newImage); imagedestroy($origImage); } return $outfile; }