PHP: if more than ..px resize to

a 夏天 提交于 2019-12-13 03:33:04

问题


I want to do so if the image are over the dimensions 604x453, then resize it to 604x453.

Ive made it this far:

    $org_name = stripslashes($_FILES[$upload_name]['name']);
    $file_size = $_FILES[$upload_name]['size'];
    $file_temp = $_FILES[$upload_name]['tmp_name'];
    $file_type = $_FILES[$upload_name]["type"];
    $file_err  = $_FILES[$upload_name]['error'];
list($width, $height, $type, $attr) = $imageSizeInfo;
    $move_me = "images/users/status/".$org_name;
if(move_uploaded_file($file_temp, $move_me)) {
    echo "{";
    echo        "msg: '".$org_name."'";
    echo "}";
}
if($width > 604 && $height > 453) {
$jpeg_quality = 90;
$src = "images/users/status/".$org_name;
$ext= pathinfo($src, PATHINFO_EXTENSION);
$targ_h = 453;
$targ_w = 604;
$path_thumbs = "images/users/status/";
$thumb_path = $path_thumbs . '/' . $newfilename;

if($ext == "jpg" OR $ext == "jpeg" OR $ext == "JPG"){
    $img_r = imagecreatefromjpeg($src);
}elseif($ext == "png" OR $ext == "PNG"){
    $img_r = imagecreatefrompng($src);
}elseif($ext == "gif" OR $ext == "GIF"){ 
    $img_r = imagecreatefromgif($src);
}
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

imagejpeg($dst_r,$thumb_path,$jpeg_quality);

unlink($move_me);
}

So first it uploads the file with the original dimensions and everything, and then after it checks for dimensions and then resizes it, and unlinks(remove) the original one..

Now I dont know what, but somehow at the resize procedure it goes wrong and i only get a black square in the dimensions 604x453 as output..

What did i miss, how can i solve this?


回答1:


Between your ImageCreateTrueColor and imagejpeg lines, you need something like this:

imagecopyresampled($dst_r, $img_r, 0, 0, 0, 0, $targ_w, $targ_h, $width, $height);

See the PHP manual for imagecopyresampled().

Your old code was essentially creating a blank canvas of the correct size, then creating your "black square" from it.

You should also use getimagesize() to determine what type of image has been uploaded, instead of using the file extension.

Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

The reason for this is that it is perfectly plausible that an image is uploaded which is called file.jpg, but it is actually a .png file - getimagesize() examines the bytes inside the image to determine what format it is.



来源:https://stackoverflow.com/questions/4639961/php-if-more-than-px-resize-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!