使用GD库对图片的缩放功能函数

最近在网上找了些资料,然后稍微修改重新封装成了一个可以直接调用的公共函数
<?php

define ('IMG_FILTER_CACHE_SIZE', 250); // number of files to store before clearing cache
define ('IMG_FILTER_CACHE_CLEAR', 5); // maximum number of files to delete on each cache clear
define ('IMG_FILTER_VERSION', '1.09'); // version number (to force a cache refresh


/**
* 缩小图片的处理函数,当$width和$height都为零时,函数默认为100x100的图片
* 使用示例1:minifyPicture(UPLOAD_PIC_DIR.$main_imagename, 0, 0, 0, 100);
* 这个语句会调用函数将目标图片等比例转换为100x100的图片,图片质量设为100(即最高质量)
* 使用示例2:minifyPicture(UPLOAD_PIC_DIR.$main_imagename, 150, 150, 0, 50);
* 这个语句会调用函数将目标图片等比例转换为150x150的图片,图片质量设为50
* @param string $src, 文件的绝对路径
* @param int $width, 缩小后的图片宽
* @param int $height, 缩小后的图片高
* @param int $zoom_crop, 是否等比例缩放,为0时按等比例缩小,为1则只取图片一部分
* @param int $quality, 缩小图片的画面质量,取值在(0,100],100为画面最高质量
* @return string,操作成功,返回空字符串,否则返回错误提示信息
*/
function minifyPicture($src, $width, $height, $zoom_crop, $quality){
$imageFilters = array(
"1" => array("IMG_FILTER_NEGATE", 0),
"2" => array("IMG_FILTER_GRAYSCALE", 0),
"3" => array("IMG_FILTER_BRIGHTNESS", 1),
"4" => array("IMG_FILTER_CONTRAST", 1),
"5" => array("IMG_FILTER_COLORIZE", 4),
"6" => array("IMG_FILTER_EDGEDETECT", 0),
"7" => array("IMG_FILTER_EMBOSS", 0),
"8" => array("IMG_FILTER_GAUSSIAN_BLUR", 0),
"9" => array("IMG_FILTER_SELECTIVE_BLUR", 0),
"10" => array("IMG_FILTER_MEAN_REMOVAL", 0),
"11" => array("IMG_FILTER_SMOOTH", 0),
);

if($src == "" || strlen($src) <= 3)
return "no image specified";

// $orifilesize = filesize($src);
// if($orifilesize <= 1024*500)
// return;

$picinfo = pathinfo($src);
$picname = $picinfo["basename"];
// set path to cache directory (default is ./cache)
// this can be changed to a different location
$cache_dir = $picinfo['dirname'];

// last modified time (for caching)
$lastModified = filemtime($src);

// // get properties
$new_width = preg_replace("/[^0-9]+/", "", $width);
$new_height = preg_replace("/[^0-9]+/", "", $height);
$zoom_crop = preg_replace("/[^0-9]+/", "", $zoom_crop);
$quality = preg_replace("/[^0-9]+/", "", $quality);
$filters = "";

if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}



// get mime type of src
$mime_type = IMG_FILTER_mime_type($src);

// check to see if this image is in the cache already
IMG_FILTER_check_cache( $cache_dir );

// if not in cache then clear some space and generate a new file
//cleanCache();

ini_set('memory_limit', "50M");

// make sure that the src is gif/jpg/png
if(!IMG_FILTER_valid_src_mime_type($mime_type)) {
return "Invalid src mime type: " .$mime_type;
}

// check to see if GD function exist
if(!function_exists('imagecreatetruecolor')) {
return "GD Library Error: imagecreatetruecolor does not exist";
}

if(strlen($src) && file_exists($src)) {

// open the existing image
$image = IMG_FILTER_open_image($mime_type, $src);
if($image === false) {
return 'Unable to open image : ' . $src;
}

// Get original width and height
$width = imagesx($image);
$height = imagesy($image);

// don't allow new width or height to be greater than the original
if( $new_width > $width ) {
$new_width = $width;
}
if( $new_height > $height ) {
$new_height = $height;
}

// // generate new w/h if not provided
// if( $new_width && !$new_height ) {
//
// $new_height = $height * ( $new_width / $width );
//
// } elseif($new_height && !$new_width) {
//
// $new_width = $width * ( $new_height / $height );
//
// } elseif(!$new_width && !$new_height) {
//
// $new_width = $width;
// $new_height = $height;
//
// }

//assign the start position on the canvas
if( $height > $width ){
$dst_height = $new_height;
$dst_width = $dst_height*($width/$height);
$dst_x = ( $new_width - $dst_width )/2;
$dst_y = 0;
}elseif( $height < $width ){
$dst_width = $new_width;
$dst_height = $dst_width*($height/$width);
$dst_x = 0;
$dst_y = ( $new_height - $dst_height)/2;
}elseif( $height == $width ){
$dst_width = $new_width;
$dst_height = $new_height;
$dst_x = 0;
$dst_y = 0;
}
// create a new true color image
$canvas = imagecreatetruecolor( $new_width, $new_height );
imagealphablending($canvas, false);
// Create a new transparent color for image
$color = imagecolorallocatealpha($canvas, 250, 250, 250, 127);
// Completely fill the background of the new image with allocated color.
imagefill($canvas, 0, 0, $color);
// Restore transparency blending
imagesavealpha($canvas, true);

if( $zoom_crop ) {

$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;

$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;

// calculate x or y coordinate and width or height of source

if ( $cmp_x > $cmp_y ) {

$src_w = round( ( $width / $cmp_x * $cmp_y ) );
$src_x = round( ( $width - ( $width / $cmp_x * $cmp_y ) ) / 2 );

} elseif ( $cmp_y > $cmp_x ) {

$src_h = round( ( $height / $cmp_y * $cmp_x ) );
$src_y = round( ( $height - ( $height / $cmp_y * $cmp_x ) ) / 2 );

}

imagecopyresampled( $canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h );

} else {

// copy and resize part of an image with resampling
imagecopyresampled( $canvas, $image, $dst_x, $dst_y, 0, 0, $dst_width, $dst_height, $width, $height );

}

if ($filters != "") {
// apply filters to image
$filterList = explode("|", $filters);
foreach($filterList as $fl) {
$filterSettings = explode(",", $fl);
if(isset($imageFilters[$filterSettings[0]])) {

for($i = 0; $i < 4; $i ++) {
if(!isset($filterSettings[$i])) {
$filterSettings[$i] = null;
}
}

switch($imageFilters[$filterSettings[0]][1]) {

case 1:

imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
break;

case 2:

imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
break;

case 3:

imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
break;

default:

imagefilter($canvas, $imageFilters[$filterSettings[0]][0]);
break;

}
}
}
}

// output image to browser based on mime type
IMG_FILTER_show_image($mime_type, $canvas, $cache_dir, $quality, $picname);

// remove image from memory
//imagedestroy($canvas);
return "";
} else {

if(strlen($src)) {
return "image " . $src . " not found";
} else {
return "no source specified";
}

}

}
//=======================================================================================================
/**
* 以下是一些辅助处理函数
*/
function IMG_FILTER_show_image($mime_type, $image_resized, $cache_dir, $quality, $picname) {

// check to see if we can write to the cache directory
$is_writable = 0;
$cache_file_name = $cache_dir . '/' . $picname;

if(touch($cache_file_name)) {

// give 666 permissions so that the developer
// can overwrite web server user
chmod($cache_file_name, 0666);
$is_writable = 1;

} else {

$cache_file_name = NULL;
header('Content-type: ' . $mime_type);

}

//$quality = floor($quality * 0.09);

imagejpeg($image_resized, $cache_file_name, $quality);

if($is_writable) {
//IMG_FILTER_show_cache_file($cache_dir, $mime_type, $picname);
}

imagedestroy($image_resized);

}

/**
*
*/
function IMG_FILTER_open_image($mime_type, $src) {

if(stristr($mime_type, 'gif')) {

$image = imagecreatefromgif($src);

} elseif(stristr($mime_type, 'jpeg')) {

@ini_set('gd.jpeg_ignore_warning', 1);
$image = imagecreatefromjpeg($src);

} elseif( stristr($mime_type, 'png')) {

$image = imagecreatefrompng($src);

}

return $image;

}

/**
* clean out old files from the cache
* you can change the number of files to store and to delete per loop in the defines at the top of the code
*/
function IMG_FILTER_cleanCache() {

$files = glob("cache/*", GLOB_BRACE);

$yesterday = time() - (24 * 60 * 60);

if (count($files) > 0) {

usort($files, "filemtime_compare");
$i = 0;

if (count($files) > IMG_FILTER_CACHE_SIZE) {

foreach ($files as $file) {

$i ++;

if ($i >= IMG_FILTER_CACHE_CLEAR) {
return;
}

if (filemtime($file) > $yesterday) {
return;
}

unlink($file);

}

}

}

}

/**
* compare the file time of two files
*/
function IMG_FILTER_filemtime_compare($a, $b) {

return filemtime($a) - filemtime($b);

}

/**
* determine the file mime type
*/
function IMG_FILTER_mime_type($file) {

if (stristr(PHP_OS, 'WIN')) {
$os = 'WIN';
} else {
$os = PHP_OS;
}

$mime_type = '';

if (function_exists('mime_content_type')) {
$mime_type = mime_content_type($file);
}

// use PECL fileinfo to determine mime type
if (!IMG_FILTER_valid_src_mime_type($mime_type)) {
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($finfo, $file);
finfo_close($finfo);
}
}

// try to determine mime type by using unix file command
// this should not be executed on windows
if (!IMG_FILTER_valid_src_mime_type($mime_type) && $os != "WIN") {
if (preg_match("/FREEBSD|LINUX/", $os)) {
$mime_type = trim(@shell_exec('file -bi "' . $file . '"'));
}
}

// use file's extension to determine mime type
if (!IMG_FILTER_valid_src_mime_type($mime_type)) {

// set defaults
$mime_type = 'image/png';
// file details
$fileDetails = pathinfo($file);
$ext = strtolower($fileDetails["extension"]);
// mime types
$types = array(
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif'
);

if (strlen($ext) && strlen($types[$ext])) {
$mime_type = $types[$ext];
}

}

return $mime_type;

}

/**
*
*/
function IMG_FILTER_valid_src_mime_type($mime_type) {

if (preg_match("/jpg|jpeg|gif|png/i", $mime_type)) {
return true;
}

return false;

}

/**
*
*/
function IMG_FILTER_check_cache($cache_dir) {

// make sure cache dir exists
if (!file_exists($cache_dir)) {
// give 777 permissions so that developer can overwrite
// files created by web server user
mkdir($cache_dir);
chmod($cache_dir, 0777);
}
chmod($cache_dir, 0777);
//show_cache_file($cache_dir, $mime_type, $lastModified);

}

/**
*
*/
function IMG_FILTER_show_cache_file($cache_dir,$mime_type,$picname) {

$cache_file = $cache_dir . '/' . $picname;

if (file_exists($cache_file)) {

$gmdate_mod = gmdate("D, d M Y H:i:s", filemtime($cache_file));

if(! strstr($gmdate_mod, "GMT")) {
$gmdate_mod .= " GMT";
}

if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {

// check for updates
$if_modified_since = preg_replace("/;.*$/", "", $_SERVER["HTTP_IF_MODIFIED_SINCE"]);

if ($if_modified_since == $gmdate_mod) {
header("HTTP/1.1 304 Not Modified");
exit;
}

}

$fileSize = filesize($cache_file);

// send headers then display image
header("Content-Type: image/png");
header("Accept-Ranges: bytes");
header("Last-Modified: " . $gmdate_mod);
header("Content-Length: " . $fileSize);
header("Cache-Control: max-age=9999, must-revalidate");
header("Expires: " . $gmdate_mod);

readfile($cache_file);

exit;

}

}

/**
* check to if the url is valid or not
*/
function IMG_FILTER_valid_extension ($ext) {

if (preg_match("/jpg|jpeg|png|gif/i", $ext)) {
return TRUE;
} else {
return FALSE;
}

}

?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值