Andy's Blog » wordpress ͼƬ, @andydest, wordpress处理图片的代码 » WordPress 图片处理相关函数

WordPress 图片处理相关函数

前段时间挖出来看的,没地方放,再占个位置。。。
下次看容易找,放出我整理后的,不依赖其他文件的函数集,可直接使用,代码里含例子了
主要是删除了注释和简单改了错误处理方式而已

andy_wp_img_fun.php
<?php
 
    
define('ROOT', dirname(__FILE__).'/');
 
    
// $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90
    
echo image_resize( ROOT.'1.jpg', 200, 200, true, 'andy', ROOT.'4.jpg', 90 );
 
    
// 函数部份
    
function error($code = '', $message = '', $data = '') {
        
echo '<font color="red">', $code , '<br />', $message, '<br />', $data, '</font>';
        
exit;
    
}
 
    
function wp_crop_image( $src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
        
if ( $src_abs ) {
                
$src_w -= $src_x;
                
$src_h -= $src_y;
        
}
        
if ( !$dst_file )
                
$dst_file = str_replace( basename( $src_file ), 'cropped-'.basename( $src_file ), $src_file );
        
$dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
        
$cmd = sprintf("/usr/bin/convert %s -crop %dx%d+%d+%d -resize %dx%d %s",
                      
$src_file,
                      
$src_w,$src_h,$src_x,$src_y,
                      
$dst_w,$dst_h,
                      
$dst_file);
        
system($cmd,$retcode);
        
return $dst_file;
    
}
 
    
function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
        
$magic = '/usr/bin/convert '; //place full or symbolized unix file path to ImageMagick here...
        
$size = @getimagesize( $file );
        
if ( !$size )
            
return error('invalid_image', 'Could not read image size', $file);
        
list($orig_w, $orig_h, $orig_type) = $size;
        
$dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
        
if ( !$dims )
            
return $dims;
        
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
        
// $suffix will be appended to the destination filename, just before the extension
        
if ( !$suffix )
            
$suffix = "{$dst_w}x{$dst_h}";
        
$info = pathinfo($file);
        
$dir = $info['dirname'];
        
$ext = $info['extension'];
        
$name = basename($file, ".{$ext}");
        
if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
            
$dir = $_dest_path;
        
$destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
        
if ( IMAGETYPE_GIF == $orig_type ) {
            
$crop = ($crop) ? "^ -gravity center -extent {$dst_w}x{$dst_h}" : "";
            
exec($magic." -limit memory 50mb -limit map 128mb -size {$dst_w}x{$dst_h} '{$file}' -thumbnail {$dst_w}x{$dst_h}{$crop} '{$destfilename}'");
        
} elseif ( IMAGETYPE_PNG == $orig_type ) {
            
$crop = ($crop) ? "^ -gravity center -extent {$dst_w}x{$dst_h}" : "";
            
exec($magic." -limit memory 50mb -limit map 128mb -size {$dst_w}x{$dst_h} '{$file}' -thumbnail {$dst_w}x{$dst_h}{$crop} '{$destfilename}'");
        
} else {
            
// all other formats are converted to jpg
            
$destfilename = "{$dir}/{$name}-{$suffix}.jpg";
            
$crop = ($crop) ? "^ -gravity center -extent {$dst_w}x{$dst_h}" : "";
            
exec($magic." -limit memory 50mb -limit map 128mb -size {$dst_w}x{$dst_h} '{$file}' -thumbnail {$dst_w}x{$dst_h}{$crop} '{$destfilename}'");
        
}
        
// Set correct file permissions
        
$stat = stat( dirname( $destfilename ));
        
$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
        @
chmod( $destfilename, $perms );
        
return $destfilename;
    
}
 
    
function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
        
if ( !$max_width and !$max_height )
            
return array( $current_width, $current_height );
        
$width_ratio = $height_ratio = 1.0;
        
if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width )
            
$width_ratio = $max_width / $current_width;
        
if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height )
            
$height_ratio = $max_height / $current_height;
        
// the smaller ratio is the one we need to fit it to the constraining box
        
$ratio = min( $width_ratio, $height_ratio );
        
return array( intval($current_width * $ratio), intval($current_height * $ratio) );
    
}
 
    
function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
        
if ($orig_w <= 0 || $orig_h <= 0)
            
return false;
        
// at least one of dest_w or dest_h must be specific
        
if ($dest_w <= 0 && $dest_h <= 0)
            
return false;
        
if ( $crop ) {
            
// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
            
$aspect_ratio = $orig_w / $orig_h;
            
$new_w = min($dest_w, $orig_w);
            
$new_h = min($dest_h, $orig_h);
            
if ( !$new_w ) {
                
$new_w = intval($new_h * $aspect_ratio);
            
}
            
if ( !$new_h ) {
                
$new_h = intval($new_w / $aspect_ratio);
            
}
            
$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
            
$crop_w = round($new_w / $size_ratio);
            
$crop_h = round($new_h / $size_ratio);
            
$s_x = floor( ($orig_w - $crop_w) / 2 );
            
$s_y = floor( ($orig_h - $crop_h) / 2 );
        
} else {
            
// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
            
$crop_w = $orig_w;
            
$crop_h = $orig_h;
            
$s_x = 0;
            
$s_y = 0;
            
list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
        
}
        
// if the resulting image would be the same size or larger we don't want to resize it
        
if ( $new_w >= $orig_w && $new_h >= $orig_h )
            
return false;
        
// the return array matches the parameters to imagecopyresampled()
        
// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
        
return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
    
}

下面这些代码是 WordPress 里的,晕,也被我改过了。。

<?php
 
function image_hwstring($width, $height) {
    
$out = '';
    
if ($width)
        
$out .= 'width="'.intval($width).'" ';
    
if ($height)
        
$out .= 'height="'.intval($height).'" ';
    
return $out;
}
 
/**
 * Calculates the new dimentions for a downsampled image.
 *
 * Same as {@link wp_shrink_dimensions()}, except the max parameters are
 * optional. If either width or height are empty, no constraint is applied on
 * that dimension.
 *
 *
@since 2.5.0
 *
 *
@param int $current_width Current width of the image.
 *
@param int $current_height Current height of the image.
 *
@param int $max_width Optional. Maximum wanted width.
 *
@param int $max_height Optional. Maximum wanted height.
 *
@return array First item is the width, the second item is the height.
 */

function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
    
if ( !$max_width and !$max_height )
        
return array( $current_width, $current_height );
 
    
$width_ratio = $height_ratio = 1.0;
 
    
if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width )
        
$width_ratio = $max_width / $current_width;
 
    
if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height )
        
$height_ratio = $max_height / $current_height;
 
    
// the smaller ratio is the one we need to fit it to the constraining box
    
$ratio = min( $width_ratio, $height_ratio );
 
    
return array( intval($current_width * $ratio), intval($current_height * $ratio) );
}
 
/**
 * Retrieve calculated resized dimensions for use in imagecopyresampled().
 *
 * Calculate dimensions and coordinates for a resized image that fits within a
 * specified width and height. If $crop is true, the largest matching central
 * portion of the image will be cropped out and resized to the required size.
 *
 *
@since 2.5.0
 *
 *
@param int $orig_w Original width.
 *
@param int $orig_h Original height.
 *
@param int $dest_w New width.
 *
@param int $dest_h New height.
 *
@param bool $crop Optional, default is false. Whether to crop image or resize.
 *
@return bool|array False, on failure. Returned array matches parameters for imagecopyresampled() PHP function.
 */

function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
 
    
if ($orig_w <= 0 || $orig_h <= 0)
        
return false;
    
// at least one of dest_w or dest_h must be specific
    
if ($dest_w <= 0 && $dest_h <= 0)
        
return false;
 
    
if ( $crop ) {
        
// crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
        
$aspect_ratio = $orig_w / $orig_h;
        
$new_w = min($dest_w, $orig_w);
        
$new_h = min($dest_h, $orig_h);
 
        
if ( !$new_w ) {
            
$new_w = intval($new_h * $aspect_ratio);
        
}
 
        
if ( !$new_h ) {
            
$new_h = intval($new_w / $aspect_ratio);
        
}
 
        
$size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
 
        
$crop_w = round($new_w / $size_ratio);
        
$crop_h = round($new_h / $size_ratio);
 
        
$s_x = floor( ($orig_w - $crop_w) / 2 );
        
$s_y = floor( ($orig_h - $crop_h) / 2 );
    
} else {
        
// don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
        
$crop_w = $orig_w;
        
$crop_h = $orig_h;
 
        
$s_x = 0;
        
$s_y = 0;
 
        
list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
    
}
 
    
// if the resulting image would be the same size or larger we don't want to resize it
    
if ( $new_w >= $orig_w && $new_h >= $orig_h )
        
return false;
 
    
// the return array matches the parameters to imagecopyresampled()
    
// int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
    
return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
 
}
 
/**
 * Scale down an image to fit a particular size and save a new copy of the image.
 *
 * The PNG transparency will be preserved using the function, as well as the
 * image type. If the file going in is PNG, then the resized image is going to
 * be PNG. The only supported image types are PNG, GIF, and JPEG.
 *
 * Some functionality requires API to exist, so some PHP version may lose out
 * support. This is not the fault of WordPress (where functionality is
 * downgraded, not actual defects), but of your PHP version.
 *
 *
@since 2.5.0
 *
 *
@param string $file Image file path.
 *
@param int $max_w Maximum width to resize to.
 *
@param int $max_h Maximum height to resize to.
 *
@param bool $crop Optional. Whether to crop image or resize.
 *
@param string $suffix Optional. File Suffix.
 *
@param string $dest_path Optional. New image file path.
 *
@param int $jpeg_quality Optional, default is 90. Image quality percentage.
 *
@return mixed WP_Error on failure. String with new destination path. Array of dimensions from {@link image_resize_dimensions()}
 */

function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) {
 
    
$image = wp_load_image( $file );
    
if ( !is_resource( $image ) )
        
return error('error_loading_image', $image);
 
    
$size = @getimagesize( $file );
    
if ( !$size )
        
return error('invalid_image', 'Could not read image size', $file);
    
list($orig_w, $orig_h, $orig_type) = $size;
 
    
$dims = image_resize_dimensions($orig_w, $orig_h, $max_w, $max_h, $crop);
    
if ( !$dims )
        
return $dims;
    
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = $dims;
 
    
$newimage = wp_imagecreatetruecolor( $dst_w, $dst_h );
 
    
imagecopyresampled( $newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
 
    
// convert from full colors to index colors, like original PNG.
    
if ( IMAGETYPE_PNG == $orig_type && !imageistruecolor( $image ) )
        
imagetruecolortopalette( $newimage, false, imagecolorstotal( $image ) );
 
    
// we don't need the original in memory anymore
    
imagedestroy( $image );
 
    
// $suffix will be appended to the destination filename, just before the extension
    
if ( !$suffix )
        
$suffix = "{$dst_w}x{$dst_h}";
 
    
$info = pathinfo($file);
    
$dir = $info['dirname'];
    
$ext = $info['extension'];
    
$name = basename($file, ".{$ext}");
    
if ( !is_null($dest_path) and $_dest_path = realpath($dest_path) )
        
$dir = $_dest_path;
    
$destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
 
    
if ( IMAGETYPE_GIF == $orig_type ) {
        
if ( !imagegif( $newimage, $destfilename ) )
            
return error('resize_path_invalid', 'Resize path invalid');
    
} elseif ( IMAGETYPE_PNG == $orig_type ) {
        
if ( !imagepng( $newimage, $destfilename ) )
            
return error('resize_path_invalid', 'Resize path invalid');
    
} else {
        
// all other formats are converted to jpg
        
$destfilename = "{$dir}/{$name}-{$suffix}.jpg";
        
if ( !imagejpeg( $newimage, $destfilename, $jpeg_quality ) )
            
return error('resize_path_invalid', 'Resize path invalid');
    
}
 
    
imagedestroy( $newimage );
 
    
// Set correct file permissions
    
$stat = stat( dirname( $destfilename ));
    
$perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
    @
chmod( $destfilename, $perms );
 
    
return $destfilename;
}
 
function gd_edit_image_support($mime_type) {
    
if ( function_exists('imagetypes') ) {
        
switch( $mime_type ) {
            
case 'image/jpeg':
                
return (imagetypes() & IMG_JPG) != 0;
            
case 'image/png':
                
return (imagetypes() & IMG_PNG) != 0;
            
case 'image/gif':
                
return (imagetypes() & IMG_GIF) != 0;
        
}
    
} else {
        
switch( $mime_type ) {
            
case 'image/jpeg':
                
return function_exists('imagecreatefromjpeg');
            
case 'image/png':
                
return function_exists('imagecreatefrompng');
            
case 'image/gif':
                
return function_exists('imagecreatefromgif');
        
}
    
}
    
return false;
}
 
/**
 * Create new GD image resource with transparency support
 *
 *
@since 2.9.0
 *
 *
@param $width
 *
@param $height
 *
@return image resource
 */

function wp_imagecreatetruecolor($width, $height) {
    
$img = imagecreatetruecolor($width, $height);
    
if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
        
imagealphablending($img, false);
        
imagesavealpha($img, true);
    
}
    
return $img;
}
 
/**
 * Crop an Image to a given size.
 *
 *
@since 2.1.0
 *
 *
@param string|int $src_file The source file or Attachment ID.
 *
@param int $src_x The start x position to crop from.
 *
@param int $src_y The start y position to crop from.
 *
@param int $src_w The width to crop.
 *
@param int $src_h The height to crop.
 *
@param int $dst_w The destination width.
 *
@param int $dst_h The destination height.
 *
@param int $src_abs Optional. If the source crop points are absolute.
 *
@param string $dst_file Optional. The destination file to write to.
 *
@return string New filepath on success, String error message on failure.
 */

 
function wp_crop_image( $src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
 
    
$src = wp_load_image( $src_file );
 
    
if ( !is_resource( $src ))
        
return $src;
 
    
$dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
 
    
if ( $src_abs ) {
        
$src_w -= $src_x;
        
$src_h -= $src_y;
    
}
 
    
if (function_exists('imageantialias'))
        
imageantialias( $dst, true );
 
    
imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
 
    
imagedestroy( $src ); // Free up memory
 
    
if ( ! $dst_file )
        
$dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
 
    
$dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
 
    
if ( imagejpeg( $dst, $dst_file, 90 ) )
        
return $dst_file;
    
else
        
return false;
}
 
/**
 * Load an image from a string, if PHP supports it.
 *
 *
@since 2.1.0
 *
 *
@param string $file Filename of the image to load.
 *
@return resource The resulting image resource on success, Error string on failure.
 */

 
function wp_load_image( $file ) {
    
if ( ! file_exists( $file ) )
        
return sprintf('File &#8220;%s&#8221; doesn&#8217;t exist?', $file);
 
    
if ( ! function_exists('imagecreatefromstring') )
        
return 'The GD image library is not installed.';
 
    
// Set artificially high because GD uses uncompressed images in memory
    @
ini_set('memory_limit', '256M');
    
$image = imagecreatefromstring( file_get_contents( $file ) );
 
    
if ( !is_resource( $image ) )
        
return sprintf('File &#8220;%s&#8221; is not an image.', $file);
 
    
return $image;
}

Incoming search terms:

Tags: wordpress, ImageMagick, 图片处理

本文地址: http://www.21andy.com/new/20100410/1841.html

1 评论 to “PHP开源CMS之MODx”

  1. 绿叶 于 2011-05-30 11:18:03 发表:

    怎么用啊?