我想在用户使用PHP和ImageManipulator库上传时调整配置文件图像的大小

时间:2018-03-28 12:28:18

标签: php mysql

我编写了个人资料图像系统,让用户上传自己的个人资料图片,我想将上传的图片调整到一定的宽度和高度 这是代码使用

function user_prof_img($image_temp,$image_extn,$conn){
  include_once 'ImageManipulator.php';
  ob_start();
  $username_id = $_SESSION['id'];
  $manipulator = new ImageManipulator($_FILES['profile_imge']['tmp_name']);
  $newImage = $manipulator->resample(200, 200);
  $newNamePrefix = time() . '_';
   $manipulator->save('../profile_image/'
    . $newNamePrefix . $_FILES['profile_imge']['name'] . '.' . $image_extn);
$image_path = '../profile_image/' . substr(md5(time()), 0 , 10) . '.' . $image_extn;
move_uploaded_file($image_temp,$image_path);
$update_img = "UPDATE users SET profile_img = '$image_path' WHERE users.id='$username_id'";
$updated_img = mysqli_query($conn,$update_img);
if (!$updated_img) {
echo "sorry an error happens while we processes your image please try again later";
}else {
  header("Location: ../browser-games/index");
}
}

if (isset($_POST['submit_img'])) {
  if (empty($_FILES['profile_imge']['name']) === true) {
    echo "<script>alert('please choose an image to upload')</script>";
  }else {
  $allowed = array('jpg','jpeg','png');
  $image_name = $_FILES['profile_imge']['name'];
  $image_extn = strtolower(end(explode('.', $image_name)));
  $image_size = $_FILES['profile_imge']['size'];
  $image_temp = $_FILES['profile_imge']['tmp_name'];
if (in_array($image_extn,$allowed) === true) {
user_prof_img($image_temp,$image_extn,$conn);
}else {
echo "<script>alert('incorrect image type. allowed: ".implode(', ', $allowed)."')</script>";
}


  }

}

个人资料图片显示在

中的页面
    <?php
                             if(isset($_SESSION['id'])){
                                 $username_id = $_SESSION['id'];
$select_img = "SELECT * FROM users WHERE users.id=$username_id";
$get_img = mysqli_query($conn,$select_img);
if (!$get_img) {
    echo "sorry we are unable to pull in data from our database at this moment please try again later";
}else {
 if ($img_row = mysqli_fetch_assoc($get_img)){
        if (empty($img_row['profile_img']) === false) {
             echo '<div class="prof_img_con">
             <img src="'.$img_row['profile_img'].'" alt="'.$img_row['username'].'" class="prof_img">

             </div>';
        }else {
            echo '
            <form action="" method="POST" enctype="multipart/form-data">
            <label for="file"class="file_label">
            <div class="prof_img_con"><img src="../profile_image/avatar.png" class="prof_img"
            title="Upload Profile Image"></div>
            </label>
    <input type="file" name="profile_imge" id="file" value="update image">
    <div class="submit_con">
    <label for="sub_img" class="sub_img" id="img_label">Submit Image</label>
    <input type="submit" id="sub_img" name="submit_img">
    </div>
            ';
            include "../include/profile_img.php";
        }
 }else {
     echo "<script><alert(sorry an error just happens please refresh the page or try again later)</script>";
 }
}

这个ImageManipulator代码在这里

<?php
class ImageManipulator
{
    /**
     * @var int
     */
    protected $width;

    /**
     * @var int
     */
    protected $height;

    /**
     * @var resource
     */
    protected $image;

    /**
     * Image manipulator constructor
     * 
     * @param string $file OPTIONAL Path to image file or image data as string
     * @return void
     */
    public function __construct($file = null)
    {
        if (null !== $file) {
            if (is_file($file)) {
                $this->setImageFile($file);
            } else {
                $this->setImageString($file);
            }
        }
    }

    /**
     * Set image resource from file
     * 
     * @param string $file Path to image file
     * @return ImageManipulator for a fluent interface
     * @throws InvalidArgumentException
     */
    public function setImageFile($file)
    {
        if (!(is_readable($file) && is_file($file))) {
            throw new InvalidArgumentException("Image file $file is not readable");
        }

        if (is_resource($this->image)) {
            imagedestroy($this->image);
        }

        list ($this->width, $this->height, $type) = getimagesize($file);

        switch ($type) {
            case IMAGETYPE_GIF  :
                $this->image = imagecreatefromgif($file);
                break;
            case IMAGETYPE_JPEG :
                $this->image = imagecreatefromjpeg($file);
                break;
            case IMAGETYPE_PNG  :
                $this->image = imagecreatefrompng($file);
                break;
            default             :
                throw new InvalidArgumentException("Image type $type not supported");
        }

        return $this;
    }

    /**
     * Set image resource from string data
     * 
     * @param string $data
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function setImageString($data)
    {
        if (is_resource($this->image)) {
            imagedestroy($this->image);
        }

        if (!$this->image = imagecreatefromstring($data)) {
            throw new RuntimeException('Cannot create image from data string');
        }
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
        return $this;
    }

    /**
     * Resamples the current image
     *
     * @param int  $width                New width
     * @param int  $height               New height
     * @param bool $constrainProportions Constrain current image proportions when resizing
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function resample($width, $height, $constrainProportions = true)
    {
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }
        if ($constrainProportions) {
            if ($this->height >= $this->width) {
                $width  = round($height / $this->height * $this->width);
            } else {
                $height = round($width / $this->width * $this->height);
            }
        }
        $temp = imagecreatetruecolor($width, $height);
        imagecopyresampled($temp, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
        return $this->_replace($temp);
    }

    /**
     * Enlarge canvas
     * 
     * @param int   $width  Canvas width
     * @param int   $height Canvas height
     * @param array $rgb    RGB colour values
     * @param int   $xpos   X-Position of image in new canvas, null for centre
     * @param int   $ypos   Y-Position of image in new canvas, null for centre
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function enlargeCanvas($width, $height, array $rgb = array(), $xpos = null, $ypos = null)
    {
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }

        $width = max($width, $this->width);
        $height = max($height, $this->height);

        $temp = imagecreatetruecolor($width, $height);
        if (count($rgb) == 3) {
            $bg = imagecolorallocate($temp, $rgb[0], $rgb[1], $rgb[2]);
            imagefill($temp, 0, 0, $bg);
        }

        if (null === $xpos) {
            $xpos = round(($width - $this->width) / 2);
        }
        if (null === $ypos) {
            $ypos = round(($height - $this->height) / 2);
        }

        imagecopy($temp, $this->image, (int) $xpos, (int) $ypos, 0, 0, $this->width, $this->height);
        return $this->_replace($temp);
    }

    /**
     * Crop image
     * 
     * @param int|array $x1 Top left x-coordinate of crop box or array of coordinates
     * @param int       $y1 Top left y-coordinate of crop box
     * @param int       $x2 Bottom right x-coordinate of crop box
     * @param int       $y2 Bottom right y-coordinate of crop box
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function crop($x1, $y1 = 0, $x2 = 0, $y2 = 0)
    {
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }
        if (is_array($x1) && 4 == count($x1)) {
            list($x1, $y1, $x2, $y2) = $x1;
        }

        $x1 = max($x1, 0);
        $y1 = max($y1, 0);

        $x2 = min($x2, $this->width);
        $y2 = min($y2, $this->height);

        $width = $x2 - $x1;
        $height = $y2 - $y1;

        $temp = imagecreatetruecolor($width, $height);
        imagecopy($temp, $this->image, 0, 0, $x1, $y1, $width, $height);

        return $this->_replace($temp);
    }

    /**
     * Replace current image resource with a new one
     * 
     * @param resource $res New image resource
     * @return ImageManipulator for a fluent interface
     * @throws UnexpectedValueException
     */
    protected function _replace($res)
    {
        if (!is_resource($res)) {
            throw new UnexpectedValueException('Invalid resource');
        }
        if (is_resource($this->image)) {
            imagedestroy($this->image);
        }
        $this->image = $res;
        $this->width = imagesx($res);
        $this->height = imagesy($res);
        return $this;
    }

    /**
     * Save current image to file
     * 
     * @param string $fileName
     * @return void
     * @throws RuntimeException
     */
    public function save($fileName, $type = IMAGETYPE_JPEG)
    {
        $dir = dirname($fileName);
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true)) {
                throw new RuntimeException('Error creating directory ' . $dir);
            }
        }

        try {
            switch ($type) {
                case IMAGETYPE_GIF  :
                    if (!imagegif($this->image, $fileName)) {
                        throw new RuntimeException;
                    }
                    break;
                case IMAGETYPE_PNG  :
                    if (!imagepng($this->image, $fileName)) {
                        throw new RuntimeException;
                    }
                    break;
                case IMAGETYPE_JPEG :
                default             :
                    if (!imagejpeg($this->image, $fileName, 95)) {
                        throw new RuntimeException;
                    }
            }
        } catch (Exception $ex) {
            throw new RuntimeException('Error saving image file to ' . $fileName);
        }
    }

    /**
     * Returns the GD image resource
     *
     * @return resource
     */
    public function getResource()
    {
        return $this->image;
    }

    /**
     * Get current image resource width
     *
     * @return int
     */
    public function getWidth()
    {
        return $this->width;
    }

    /**
     * Get current image height
     *
     * @return int
     */
    public function getHeight()
    {
        return $this->height;
    }
}

使用此代码获取已调整大小的图像和原始图像,但原始图像显示在我的页面上而不是调整大小的图像。 如何显示已调整大小的图像并自动删除原始图像? 并感谢您的帮助

1 个答案:

答案 0 :(得分:1)

简而言之,您应该在保存调整大小后的图片路径时将原始文件($image_path)保存到用户的个人资料中。

我创建了2个新变量,然后在下面使用。这使代码更清晰,更易于阅读:$smallPath$originalPath分别由ImageManipulator和DB使用。

您也可以使用tempnam()(http://php.net/manual/en/function.tempnam.php),而不是自己编写唯一的名称逻辑。

我还应该指出,您的数据库查询对SQL注入攻击是开放的。我没有为你修改这个。

include_once 'ImageManipulator.php';
ob_start();
$username_id = $_SESSION['id'];
$manipulator = new ImageManipulator($_FILES['profile_imge']['tmp_name']);
$newImage = $manipulator->resample(200, 200);
$newNamePrefix = time() . '_';

// You can use tempnam() to do the unique logic for you. 
$smallPath = '../profile_image/' . $newNamePrefix . $_FILES['profile_imge']['name'] . '.' . $image_extn;
$originalPath = '../profile_image/' . substr(md5(time()), 0 , 10) . '.' . $image_extn;

$manipulator->save($smallPath);
move_uploaded_file($image_temp, $originalPath);

// This is very dangerous. You **need to be using prepared statements.
// Lookup PDO - https://phpdelusions.net/pdo
$update_img = "UPDATE users SET profile_img = '$smallPath' WHERE users.id='$username_id'";
$updated_img = mysqli_query($conn,$update_img);
...