How to move compressed image file PHP

2019-09-21 14:22发布

Here is the function that compress image file.

function compress_image($source_url, $destination_url, $quality) { 
$info = getimagesize($source_url); 
if ($info['mime'] == 'image/jpeg'){
    $image = imagecreatefromjpeg($source_url); 
}elseif ($info['mime'] == 'image/gif') {
    $image = imagecreatefromgif($source_url); 
}elseif ($info['mime'] == 'image/png') {
    $image = imagecreatefrompng($source_url); 
}imagejpeg($image, $destination_url, $quality); 
return $destination_url; 
} 

$filename = compress_image($_FILES["home_image"]["tmp_name"], $_FILES["home_image"]["name"], 80); 
$buffer = file_get_contents($_FILES["home_image"]["name"]);

Here is my code that want to move the compressed image to my specific folder

move_uploaded_file($_FILES["home_image"]["tmp_name"][$i],"../../../Test/image/home_banner/" .$filename);

But the image that move to the folder is still remain the original size without compress.

Am I doing the mistake..?

1条回答
Animai°情兽
2楼-- · 2019-09-21 15:08

I think move_uplodaded_file() is not appropriate here, because you change the uploaded file contents:

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

Use rename() instead.

I'm also not 100% if you can edit the uploaded file directly..

查看更多
登录 后发表回答