更改代码以在上传时调整图片大小

时间:2016-09-28 11:49:47

标签: php

我需要更改此代码,以便在存储它们之前调整超过500 kB的图像。

if(isset($_FILES['photo']))
    if(file_exists($_FILES['photo']['tmp_name']) || !is_uploaded_file($_FILES['photo']['tmp_name'])){
        $file_name = basename($_FILES['photo']['name']);

        $temp = explode(".", $_FILES["photo"]["name"]);
        $newfilename = round(microtime(true)) . '.' . end($temp);
        $target_path = plugin_dir_path(__FILE__) . "uploads/$newfilename";

        if(move_uploaded_file($_FILES['photo']['tmp_name'], $target_path)) {
            $handle = fopen($target_path, "rb");
            $fsize = filesize($target_path);
            $img_contents = fread($handle, $fsize);
            fclose($handle);
        }
    }

1 个答案:

答案 0 :(得分:1)

这是您可能用于调整图像大小的功能之一:imagecopyresampled。我选择了这个,因为它有一个很好的图表,说明维度属性如何在用户贡献的笔记中起作用。

这是该页面的代码,略有修改,实际将其保存为'simpleimage.jpg'......

// The file
$filename = 'test.jpg';
$percent = 0.5;

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, 'simpleimage.jpg', 100);