All,
I’m uploading an image and then making it a thumbnail for display purposes. I’m using the following code to process my 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);
}
}
}
The upload works fine and the file is created successfully however when I display it is the image looks extremely distorted. If I use WordPress to handle the file upload and create the thumbnail it doesn’t look distorted at all. Is there a better method to upload this file or what am I don’t wrong to not lose the picture quality?
Thanks!
You haven’t done any scaling – if you want to have a fixed thumbnail width and height it will be distorted.
To do scaling, do the following:
You’d then need to centre the new image and crop it to the desired height (if too tall). If too short, you should re-scale but use the height for the scaling factor, and then centre and crop if too wide.