图像在上传并变成缩略图时会失真

时间:2012-02-24 20:36:44

标签: php image file-upload

全部, 我正在上传一张图片,然后将其制作缩略图以供显示。我正在使用以下代码处理我的上传:

$imageW = $blogOptions['image']['width'];
$imageH = $blogOptions['image']['height'];
$themePath = ABSPATH . 'wp-content/';
$path_to_image_directory = $themePath.'uploads/';  
$path_to_thumbs_directory = $themePath.'uploads/thumbs/';
$fieldname = 'logo';

if(preg_match('/[.](jpg)|(gif)|(png)|(JPG)$/', $_FILES[$fieldname]['name'])) {
$now = time();
$filename = $now."_".$_FILES[$fieldname]['name'];
$source = $_FILES[$fieldname]['tmp_name'];  
$target = $path_to_image_directory . $filename;  
move_uploaded_file($source, $target);

$file = $path_to_image_directory . $filename;
$x = @getimagesize($file);
switch($x[2]) { 
case 1: 
    $type = "gif";  
    break; 
case 2: 
    $type = "jpeg";
    break; 
case 3: 
    $type = "png";   
    break; 
default: 
    echo "error";
}

if($type == "gif"){
$im = imagecreatefromgif($path_to_image_directory . $filename);   
}if($type == "jpeg"){ 
$im = imagecreatefromjpeg($path_to_image_directory . $filename); 
}if($type == "png"){ 
$im = imagecreatefrompng($path_to_image_directory . $filename);   
} 

$ox = imagesx($im);  
$oy = imagesy($im);  

$nx = $imageW;  
$ny = $imageH;

$nm = imagecreatetruecolor($nx, $ny);  

imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);  

if(!file_exists($path_to_thumbs_directory)) {  
    if(!mkdir($path_to_thumbs_directory)) {  
        die("There was a problem. Please try again!");  
    }   
}

if($type == "gif"){
imagegif($nm, $path_to_thumbs_directory . $filename);   
}if($type == "jpeg"){ 
imagejpeg($nm, $path_to_thumbs_directory . $filename); 
}if($type == "png"){ 
imagepng($nm, $path_to_thumbs_directory . $filename);  
}
}
}

上传工作正常,文件创建成功但是当我显示它时图像看起来非常扭曲。如果我使用Wordpress来处理文件上传并创建缩略图,它看起来根本不会失真。是否有更好的方法来上传此文件,或者我没有错误,以免丢失图片质量?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果您的源尺寸与目标尺寸不同,则图像将被缩放。

您可以使用类似(未进行实际测试)的方式调整初始裁剪:

$oy = floor($ox * $ny / $nx);

答案 1 :(得分:1)

您还没有进行任何缩放 - 如果您想要一个固定的缩略图宽度和高度,它将会失真。

要进行缩放,请执行以下操作:

$original_width = imagesx($im);
$original_height = imagesy($im);

$scaling_factor = ($original_width / $desired_width);
$new_width = $desired_width;
$new_height = ($original_height / $scaling_factor);

然后,您需要将新图像居中并将其裁剪到所需的高度(如果太高)。如果太短,则应重新缩放,但使用高度作为比例因子,然后居中并裁剪(如果太宽)。