【PHP教程】php上传、裁剪、调整图片大小的案例代码

在现代web应用里最常用的操作是上传、裁剪、调整图片大小,用来缩略图、相册、头像等用途。 此教程将覆盖你需要的一切基本技术,完成简单基本的功能。

在现代web应用里最常用的操作是上传、裁剪、调整图片大小,用来缩略图、相册、头像等用途。

此教程将覆盖你需要的一切基本技术,完成简单基本的功能。

用php上传图片

我们将开始这个教程,通过这个经典图片上传案例,你将能明白php上传文件的工作原理。

在第一个例子,我们将建设一个上传文件和保存文件到服务器的表单,但是文件类型只允许图片文件。

要上传文件,你需要一个包含特殊input输入区域文件类型,所以,打开你常用的编辑器,粘贴下面代码,并保存命名为form.php:

<!DOCTYPE html>
<html>
<head>
    <title>Upload Files using normal form and PHP</title>
</head>
<body>
  <form enctype="multipart/form-data" method="post" action="upload.php">
    <div class="row">      <label for="fileToUpload">Select a File to Upload</label><br />
      <input type="file" name="fileToUpload" id="fileToUpload" />
    </div>
    <div class="row">
      <input type="submit" value="Upload" />
    </div>
  </form>
</body>
</html>

你可能已经注意到我们表单的enctype。它表示像文件上传类的将进行二进制数据上传。

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

默认地,表单数据会编码为 “application/x-www-form-urlencoded”。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 “+” 加号,特殊符号转换为 ASCII HEX 值)。

<form enctype="value">

属性值

描述
application/x-www-form-urlencoded 在发送前编码所有字符(默认)
multipart/form-data 不对字符编码。

在使用包含文件上传控件的表单时,必须使用该值。

text/plain 空格转换为 “+” 加号,但不对特殊字符编码。

下一步是来创建上传的图片文件,创建.upload.php文件,并把以下代码粘贴进去:

<?php
// fileToUpload is the name of our file input field
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " $_FILES['fileToUpload']['error'] . "<br />";
else {
    echo "File name: " $_FILES['fileToUpload']['name'] . "<br />";
    echo "File type: " $_FILES['fileToUpload']['type'] . "<br />";
    echo "File size: " . ($_FILES['fileToUpload']['size'] / 1024) . " Kb<br />";
    echo "Temp path: " $_FILES['fileToUpload']['tmp_name'];
}

现在,打开form.php在浏览器,选择并上传一个文件。如果一切顺利,你应该看到你提交上传文件的一些信息。

现在开始,用户能上传任何文件到你的服务器,所以,我们需要改进upload.php代码,爱检查上传的文件是否是一个图片类型。

<?php
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " $_FILES['fileToUpload']['error'] . "<br />";
else {
    // array of valid extensions
    $validExtensions array('.jpg''.jpeg''.gif''.png');
    // get extension of the uploaded file
    $fileExtension strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension$validExtensions)) {
        echo 'Uploaded file is allowed!';
    else {
        echo 'You must upload an image...';
    }
}

如果我们检查到文件是图片,我们将编写代码来将图片移动到服务器指定的目录或文件夹,现在修改代码:

<?php
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " $_FILES['fileToUpload']['error'] . "<br />";
else {
    // array of valid extensions
    $validExtensions array('.jpg''.jpeg''.gif''.png');
    // get extension of the uploaded file
    $fileExtension strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension$validExtensions)) {
        // we are renaming the file so we can upload files with the same name
        // we simply put current timestamp in fron of the file name
        $newName = time() . '_' $_FILES['fileToUpload']['name'];
        $destination 'uploads/' $newName;
        if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $destination)) {
            echo 'File ' .$newName' succesfully copied';
        }
    else {
        echo 'You must upload an image...';
    }
}

在执行以前,创建一个叫uploads的目录。

这样我们就能成功上传和保存文件在服务器了。

裁剪和调整图片大小

现在有趣的部分开始。我们来调整上传图片的大小,并保存被调整大小后的版本在uploads文件夹,一会儿来试试。我们可以这样白手起家,但是也有很多有用的库来帮忙做的更棒。

接下来,我们用一个不错的开放类 ImageManipulator class by Phil Brown,下载并添加到我们的项目文件里。

现在更新文件upload.php:

<?php
// include ImageManipulator class
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " $_FILES['fileToUpload']['error'] . "<br />";
else {
    // array of valid extensions
    $validExtensions array('.jpg''.jpeg''.gif''.png');
    // get extension of the uploaded file
    $fileExtension strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension$validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        // resizing to 200x200
        $newImage $manipulator->resample(200, 200);
        // saving file to uploads folder
        $manipulator->save('uploads/' $newNamePrefix $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    else {
        echo 'You must upload an image...';
    }
}

同样类也可以用来裁剪图像,所以,让我们修改代码来裁剪图片到200x300px。我们想裁剪图片的中心,所以,我们需要计算裁剪的坐标。

<?php
// include ImageManipulator class
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " $_FILES['fileToUpload']['error'] . "<br />";
else {
    // array of valid extensions
    $validExtensions array('.jpg''.jpeg''.gif''.png');
    // get extension of the uploaded file
    $fileExtension strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension$validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        $width  $manipulator->getWidth();
        $height $manipulator->getHeight();
        $centreX round($width / 2);
        $centreY round($height / 2);
        // our dimensions will be 200x130
        $x1 $centreX - 100; // 200 / 2
        $y1 $centreY - 65; // 130 / 2
        $x2 $centreX + 100; // 200 / 2
        $y2 $centreY + 65; // 130 / 2
        // center cropping to 200x130
        $newImage $manipulator->crop($x1$y1$x2$y2);
        // saving file to uploads folder
        $manipulator->save('uploads/' $newNamePrefix $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    else {
        echo 'You must upload an image...';
    }
}

现在,你学到怎样用纯php代码上传、调整大小、剪裁图片了,接下来可以用更现在的方式在主题上了,比如可以用jquery和html5

 

订阅评论
提醒
guest的头像

0 评论
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x