在上传到服务器之前使用GD编辑图像

时间:2016-04-05 14:35:41

标签: php image upload gd

我尝试在上传到服务器之前向带边框的图像添加一些文本。然而,看起来我编写代码的方式并没有上传图像。我已经单独检查过上传工作和图像处理工作但是它们一起工作不起作用:

$name = "some text";
$target_dir = "uploads/";
//strip filename of clear spaces 
$cleaned = str_replace(' ', '', basename($_FILES["fileToUpload"]["name"]));
$target_file = $target_dir . $cleaned;
$image = $_FILES["fileToUpload"]["name"];


$im = imagecreatefromjpeg($image);
$white = imagecolorallocate($im, 255, 255, 255);
$font_path = 'uploads/SCRIPTIN.ttf';
$text = "In Memory of " . $name;
imagesetthickness($im, 200);
$black = imagecolorallocate($im, 0, 0, 0);
$x = 0;
$y = 0;
$w = imagesx($im) - 1;
$z = imagesy($im) - 1;
imageline($im, $x, $y, $x, $y+$z, $black);
imageline($im, $x, $y, $x+$w, $y, $black);
imageline($im, $x+$w, $y, $x+$w, $y+$z, $black);
imageline($im, $x, $y+$z, $x+$w ,$y+$z, $black);
imagettftext($im, 200, 0, 20, 300, $white, $font_path, $text);

我认为这可能与我如何将文件写入服务器有关:

move_uploaded_file(imagejpeg($im), $target_file);

1 个答案:

答案 0 :(得分:1)

这是一份快速草案,但它应该有效:

创建一个文件ImageProcessor.php,复制代码,并通过require_once包含它:

class ImageProcessor
{
    /** @var string actual file, in our tmp folder on the server */
    private $file;

    /** @var string filename that we are going to save it with */
    private $filename;

    /** @var string the name we are going to write on the image */
    private $name_to_write;

    /** @var resource file resource */
    private $resource = false;

    /** @var string where we are going to save the result */
    public static $save_path = 'images/';

    /** @var array the list of file extensions we're going to allow */
    private $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');

    public function __construct($file, $name_to_write)
    {
        if (!is_array($file) || !isset($file['tmp_name'])) {
            throw new Exception('We are expecting something else');
        }

        $this->file = $file['tmp_name'];
        $this->filename = $file['name'];
        $this->name_to_write = $name_to_write;

        if (!$this->checkFileValidity()) {
            throw new Exception('Invalid file');
        }
    }

    /*
     * Get the file extension in lowercase for further checks
     *
     * @return string
     */
    private function getExtension()
    {
        return strtolower(pathinfo($this->filename, PATHINFO_EXTENSION));
    }

    /*
     * Check whether the file has a valid extension.
     *
     * @return bool
     */
    private function checkFileValidity()
    {
        return in_array($this->getExtension(), $this->allowed_extensions);
    }

    /*
     * Create a resource, depending on file's extension
     *
     * @return void
     */
    private function setFileResource()
    {
        switch ($this->getExtension()) {
            case 'jpeg':
            case 'jpg':
                $this->resource = imagecreatefromjpeg($this->file);
            break;

            case 'png':
                $this->resource = imagecreatefrompng($this->file);
            break;

            case 'gif':
                $this->resource = imagecreatefromgif($this->file);
            break;
        }
    }

    /*
     * Process the file - add borders, and writings, and so on.
     * In the last step we're also saving it.
     *
     * @return void
     */
    public function processFile()
    {
        $this->setFileResource();

        if (!$this->resource) {
            throw new Exception('Invalid file');
        }

        $white = imagecolorallocate($this->resource, 255, 255, 255);
        $font_path = 'uploads/SCRIPTIN.ttf';
        $text = "In Memory of ".$this->name_to_write;

        imagesetthickness($this->resource, 200);
        $black = imagecolorallocate($this->resource, 0, 0, 0);
        $x = 0;
        $y = 0;
        $w = imagesx($im) - 1;
        $z = imagesy($im) - 1;
        imageline($this->resource, $x, $y, $x, $y+$z, $black);
        imageline($this->resource, $x, $y, $x+$w, $y, $black);
        imageline($this->resource, $x+$w, $y, $x+$w, $y+$z, $black);
        imageline($this->resource, $x, $y+$z, $x+$w ,$y+$z, $black);
        imagettftext($this->resource, 200, 0, 20, 300, $white, $font_path, $text);

        return $this->save();
    }

    /*
     * Save the file in $save_path and return the path to the file
     *
     * @return mixed string|bool
     */
    private function save()
    {
        imagejpeg($this->resource, self::$save_path.$this->filename);

        return file_exists(self::$save_path.$this->filename) ? self::$save_path.$this->filename : false;
    }
}

然后在检测到文件已上传时调用它:

if (isset($_FILES['fileToUpload']) && is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
    $processor = new ImageProcessor($_FILES['fileToUpload'], 'John Doe');

    if ($image_path = $processor->processFile()) {
        var_dump($image_path); // this is your new image
    }
}

更新(忘记在图片上添加要写的名称)