Example #1
0
 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();
 }
Example #2
0
 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;
 }
Example #3
0
 public function getResizedImage($image, $newWidth, $newHeight, $option = 'crop', $quality = '90')
 {
     // Import libraries
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     //windows or linux, set variables
     $full_site_dir = JURI::base();
     $site_dir = JURI::base(true) . '/';
     $jpath = str_replace('\\', '/', JPATH_ROOT);
     $jpath_win = str_replace('/', '\\', JPATH_ROOT);
     $replace = array($full_site_dir, $site_dir == '/' ? '' : $site_dir, $jpath == '/' ? '' : $jpath, $jpath_win == '\\' ? '' : $jpath_win);
     $image = str_replace($replace, '', $image);
     $cache_dir = $site_dir . 'media/plg_jblibrary/imagecache/';
     $local_image = str_replace('\\' . '\\', '\\', str_replace('//', '/', str_replace('\\', '/', $site_dir . $image)));
     if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {
         //windows
         $site_root = $jpath_win . '\\';
         $cache_root = $site_root . 'media\\plg_jblibrary\\imagecache\\';
         $image = str_replace('\\' . '\\', '\\', str_replace('//', '/', $site_root . str_replace('/', '\\', $image)));
     } else {
         //linux
         $site_root = $jpath . '/';
         $cache_root = $site_root . 'media/plg_jblibrary/imagecache/';
         $image = str_replace('\\' . '\\', '\\', str_replace('//', '/', $site_root . str_replace('\\', '/', $image)));
     }
     $lastmod = filemtime($image);
     $image_file = JFile::getName($image);
     $extension = '.' . JFile::getExt($image_file);
     //open the image
     switch ($extension) {
         case '.jpg':
         case '.jpeg':
             $img = imagecreatefromjpeg($image);
             break;
         case '.JPG':
         case '.JPEG':
             $img = imagecreatefromJPEG($image);
             break;
         case '.gif':
         case '.GIF':
             $img = imagecreatefromgif($image);
             break;
         case '.png':
         case '.PNG':
             $img = imagecreatefrompng($image);
             break;
         default:
             $img = false;
             break;
     }
     $extension = strtolower($extension);
     //Retrieve its width and Height
     $width = imagesx($img);
     $height = imagesy($img);
     //name for our new image & path to save to
     $new_image = md5($image . '-' . $newWidth . 'x' . $newHeight . '-' . $option . '-' . $lastmod);
     $savePath = $cache_root . $new_image . $extension;
     //if the original image is smaller than specified we just return the original
     if ($width < $newWidth && $height < $newHeight) {
         return $local_image;
     }
     //if we have already created the image once at the same size we just return that one
     if (file_exists($cache_root . $new_image . $extension)) {
         return $cache_dir . $new_image . $extension;
     }
     //Make sure the cache exists. If it doesn't, then create it
     if (!JFolder::exists($cache_root)) {
         JFolder::create($cache_root, 0755);
     }
     //set permissions if they are not correct
     if (JFolder::exists($cache_root) && JPath::setPermissions($cache_root) != '0755') {
         JPath::setPermissions($cache_root, $filemode = '0755', $foldermode = '0755');
     }
     //Get optimal width and height - based on $option
     $optionArray = resizeImageHelper::getDimensions($newWidth, $newHeight, $width, $height, $option);
     $optimalWidth = $optionArray['optimalWidth'];
     $optimalHeight = $optionArray['optimalHeight'];
     //Resample - create image canvas of x, y size
     $imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
     if ($extension == '.png' || $extension == '.gif') {
         resizeImageHelper::setTransparency($imageResized, $img);
     }
     imagecopyresampled($imageResized, $img, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $width, $height);
     //if option is 'crop', then crop too
     if ($option == 'crop') {
         //Find center - this will be used for the crop
         $cropStartX = $optimalWidth / 2 - $newWidth / 2;
         $cropStartY = $optimalHeight / 2 - $newHeight / 2;
         $crop = $imageResized;
         //Now crop from center to exact requested size
         $imageResized = imagecreatetruecolor($newWidth, $newHeight);
         if ($extension == '.png' || $extension == '.gif') {
             resizeImageHelper::setTransparency($imageResized, $img);
         }
         imagecopyresampled($imageResized, $crop, 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight, $newWidth, $newHeight);
     }
     //if option is 'topleft', then crop w/o resize
     if ($option == 'topleft') {
         $crop = $img;
         //Now crop from top left to exact requested size
         $imageResized = imagecreatetruecolor($newWidth, $newHeight);
         if ($extension == '.png' || $extension == '.gif') {
             resizeImageHelper::setTransparency($imageResized, $img);
         }
         imagecopyresampled($imageResized, $crop, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight);
     }
     //if option is 'topleft', then crop w/o resize
     if ($option == 'center') {
         //Find center - this will be used for the crop
         $cropStartX = $width / 2 - $optimalWidth / 2;
         $cropStartY = $height / 2 - $optimalHeight / 2;
         $cropEndX = $cropStartX + $optimalWidth;
         $cropEndY = $cropStartY + $optimalHeight;
         $crop = $img;
         //Now crop from center to exact requested size
         $imageResized = imagecreatetruecolor($newWidth, $newHeight);
         if ($extension == '.png' || $extension == '.gif') {
             resizeImageHelper::setTransparency($imageResized, $img);
         }
         imagecopyresampled($imageResized, $crop, 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight, $newWidth, $newHeight);
     }
     switch ($extension) {
         case '.jpg':
         case '.jpeg':
             // Sharpen the image before we save it
             $sharpness = resizeImageHelper::findSharp($width, $optimalWidth);
             $sharpenMatrix = array(array(-1, -2, -1), array(-2, $sharpness + 12, -2), array(-1, -2, -1));
             $divisor = $sharpness;
             $offset = 0;
             if (function_exists('imageconvolution')) {
                 imageconvolution($imageResized, $sharpenMatrix, $divisor, $offset);
             } else {
                 createImageConvolution::imageConvolution($imageResized, $sharpenMatrix, $divisor, $offset);
             }
             if (imagetypes() & IMG_JPG) {
                 imagejpeg($imageResized, $savePath, $quality);
             }
             break;
         case '.gif':
             if (imagetypes() & IMG_GIF) {
                 imagegif($imageResized, $savePath);
             }
             break;
         case '.png':
             //Scale quality from 0-100 to 0-9
             $scaleQuality = round($quality / 100 * 9);
             //Invert quality setting as 0 is best, not 9
             $invertScaleQuality = 9 - $scaleQuality;
             if (imagetypes() & IMG_PNG) {
                 imagepng($imageResized, $savePath, $invertScaleQuality);
             }
             break;
         default:
             break;
     }
     imagedestroy($imageResized);
     return $cache_dir . $new_image . $extension;
 }
<?php

$image = './picture/test0.jpg';
$file_path = './picture/test.jpg';
//画像のサイズ変更
$size = getimagesize($image);
// 画像のコピーを作成
$image_in = @imagecreatefromJPEG($image);
//空の画像を生成
//$image_out = imagecreate(1200, 1200 * $size[1]/$size[0]);
// 画像のコピーを空の画像にコピー
//imagecopyresized( $image_out, $image_in, 0, 0, 0, 0, 640, 640 * $size[1]/$size[0], $size[0], $size[1]);
//imagecopyresampled( $image_out, $image_in, 0, 0, 0, 0, 1200, 1200 * $size[1]/$size[0], $size[0], $size[1]);
// イメージをファイルに出力
//imagejpeg($image_out, $file_path,50);
imagejpeg($image_in, $file_path, 50);
//メモリ解放
imagedestroy($image_in);
//imagedestroy( $image_out );
echo "成功です";
Example #5
0
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;
}
 /**
  * Upload a new attachment
  *
  * Creating a new attachment is done in two steps: uploading the data, then
  * setting the post. This is achieved by first creating an attachment, then
  * editing the post data for it.
  *
  * @param array $_files Data from $_FILES
  * @param array $_headers HTTP headers from the request
  * @return array|WP_Error Attachment data or error
  */
 public function upload_attachment($_files, $_headers, $post_id = 0)
 {
     $post_type = get_post_type_object('attachment');
     if ($post_id == 0) {
         $post_parent_type = get_post_type_object('post');
     } else {
         $post_parent_type = get_post_type_object(get_post_type($post_id));
     }
     // Make sure we have an int or 0
     $post_id = (int) $post_id;
     if (!$post_type) {
         return new WP_Error('json_invalid_post_type', __('Invalid post type'), array('status' => 400));
     }
     // Permissions check - Note: "upload_files" cap is returned for an attachment by $post_type->cap->create_posts
     if (!current_user_can($post_type->cap->create_posts) || !current_user_can($post_type->cap->edit_posts)) {
         return new WP_Error('json_cannot_create', __('Sorry, you are not allowed to post on this site.'), array('status' => 400));
     }
     // If a user is trying to attach to a post make sure they have permissions. Bail early if post_id is not being passed
     if ($post_id !== 0 && !current_user_can($post_parent_type->cap->edit_post, $post_id)) {
         return new WP_Error('json_cannot_edit', __('Sorry, you are not allowed to edit this post.'), array('status' => 401));
     }
     // Get the file via $_FILES or raw data
     if (empty($_files)) {
         $file = $this->upload_from_data($_files, $_headers);
     } else {
         $file = $this->upload_from_file($_files, $_headers);
     }
     if (is_wp_error($file)) {
         return $file;
     }
     $name = basename($file['file']);
     $name_parts = pathinfo($name);
     $name = trim(substr($name, 0, -(1 + strlen($name_parts['extension']))));
     $url = $file['url'];
     $type = $file['type'];
     $file = $file['file'];
     $title = $name;
     $content = '';
     // use image exif/iptc data for title and caption defaults if possible
     if ($image_meta = @wp_read_image_metadata($file)) {
         if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
             $title = $image_meta['title'];
         }
         if (trim($image_meta['caption'])) {
             $content = $image_meta['caption'];
         }
         // fix orientation
         if (!empty($image_meta['orientation'])) {
             $temp = imagecreatefromJPEG($file);
             switch ($image_meta['orientation']) {
                 case 3:
                     $img = imagerotate($temp, 180, 0);
                     break;
                 case 6:
                     $img = imagerotate($temp, -90, 0);
                     break;
                 case 8:
                     $img = imagerotate($temp, 90, 0);
                     break;
             }
             // overwrite original file upload
             imagejpeg($img, $file, 100);
         }
     }
     // Construct the attachment array
     $post_data = array();
     $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content);
     // This should never be set as it would then overwrite an existing attachment.
     if (isset($attachment['ID'])) {
         unset($attachment['ID']);
     }
     // Save the data
     $id = wp_insert_attachment($attachment, $file, $post_id);
     if (!is_wp_error($id)) {
         wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file));
     }
     $headers = array('Location' => json_url('/media/' . $id));
     return new WP_JSON_Response($this->get_post($id, 'edit'), 201, $headers);
 }
 function mark_img($image_dir = '', $formname = '', $x = 0, $y = 0)
 {
     $iinfo = getimagesize($image_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);
     $simage = imagecreatefromjpeg($image_dir);
     imagecopy($nimage, $simage, 0, 0, 0, 0, $iinfo[0], $iinfo[1]);
     $inn = getimagesize($formname);
     $in = @imagecreatefromJPEG($formname);
     $wh = imagecolorallocate($in, 255, 255, 255);
     imagecolortransparent($in, $wh);
     imagecopy($nimage, $in, $x, $y, 0, 0, $inn[0], $inn[1]);
     imagedestroy($in);
     imagejpeg($nimage, $image_dir);
     return "true";
 }
Example #8
0
<?php
set_time_limit(1000);

$file = "example";
if( isset($_GET["file"]) ) $file = $_GET["file"];
$output = $file . "_output.jpg";
$file .= ".jpg";

// Open input and output image
$src = imagecreatefromJPEG($file) or die('Problem with source');

echo "<pre>";

for ($x = 0; $x < imagesx($src); $x++) {
	for ($y = 0; $y < imagesy($src); $y++) {
		$src_pix = imagecolorat($src,$x,$y);
		$ycbcr = rgb_to_ycbcr_array($src_pix);
		
		echo "$ycbcr[0]\t$ycbcr[1]\t$ycbcr[2]\n";
	}
}
         
echo "</pre>";

function rgb_to_ycbcr_array($rgb)
{
   $r = ($rgb >> 16) & 0xFF;
   $g = ($rgb >> 8) & 0xFF;
   $b = $rgb & 0xFF;

	$ycbcr = Array();
Example #9
0
            $cey = 19;
            $cex = $x;
            $cc->loadImage('output.jpg');
            $cc->cropToDimensions($csx, $csy, $cex, $cey);
            $cc->saveImage('ltr' . $ino . '.jpg');
            $ino++;
            $started = 0;
            $csx . "," . $csy . "," . $cex . "," . $cey;
            "<br />";
        }
    }
    $white = 1;
}
$srr = '';
for ($ino = 0; $ino < 6; $ino++) {
    $src = imagecreatefromJPEG('ltr' . $ino . '.jpg') or die('Problem with source');
    $out = ImageCreateTrueColor(imagesx($src), imagesy($src)) or die('Problem In Creating image');
    $string = '';
    // scan image pixels
    for ($x = 0; $x < imagesx($src); $x++) {
        for ($y = 0; $y < imagesy($src); $y++) {
            $src_pix = imagecolorat($src, $x, $y);
            $src_pix_array = rgb_to_array($src_pix);
            if ($src_pix_array[0] > 100 && $src_pix_array[1] > 100 && $src_pix_array[2] > 100) {
                $string .= '0';
            } else {
                $string .= '1';
            }
        }
    }
    $string .= '1';
Example #10
0
$file .= ".jpg";

$cb = 54.234;
if( isset($_GET["cb"]) ) $cb = $_GET["cb"];

$cr = 34.089;
if( isset($_GET["cr"]) ) $cb = $_GET["cr"];

$a = 90;
if( isset($_GET["a"]) ) $a = $_GET["a"];

$b = 100;
if( isset($_GET["b"]) ) $b = $_GET["b"];

// Open input and output image
$src = imagecreatefromJPEG('content/images/'.$file) or die('Problem with source');

$size = Array(imagesx($src),imagesy($src));

$out = imagecreatetruecolor($size[0],$size[1]) or die('Problem In Creating image');

imagealphablending($out, false);
imagesavealpha($out, true);

// scan image pixels
for ($x = 0; $x < imagesx($src); $x++) {
	for ($y = 0; $y < imagesy($src); $y++) {
		$src_pix = imagecolorat($src,$x,$y);

		$ycbcr = rgb_to_ycbcr_array($src_pix);
      $o = colorclose($ycbcr[1], $ycbcr[2], $cb, $cr, $a, $b);
 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;
 }
Example #12
0
 /**
  * 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;
 }