thumbFileFullUrlArrPHP图像上传-复制文件,制作缩略图并保存两个图像

时间:2019-12-16 03:43:03

标签: php ajax file-upload

我让用户使用PHP上传图像。现在,我想为我的应用创建相同图像的缩略图。问题在于,一旦我执行move_uploaded_file(),临时文件就会被移动(显然),并且不会被复制。一旦我想调整相同图像的大小然后再次执行相同的操作,但是将文件名添加了“ -thumb”,我将收到一条错误消息,指出该文件不存在。

解决这个问题的最佳方法是什么?谢谢!

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newFileFullUrl)) { //Successfully stored image
    $retArr['imgUrl'] = $_POST['fileTarget']['dir'] . $_POST['fileTarget']['name'];

    //Needs to also create a thumb
    if ($_POST['dimensionSettings']->thumb->create) {
        $needsResize = true;

        $resizeOptions = (object) [
            'width' => $_POST['dimensionSettings']->thumb->width,
            'height' => $_POST['dimensionSettings']->thumb->height,
            'mode' => 'maxwidth',
            'imageQuality' => 100
        ];

        include_once($_SERVER['DOCUMENT_ROOT'] . '/lib/classes/ResizeImage.php');

        $resize = new ResizeImage($_FILES['fileToUpload']['tmp_name']);
        $resize->resizeTo($resizeOptions->width, $resizeOptions->height, $resizeOptions->mode);
        $resize->saveImage($_FILES['fileToUpload']['tmp_name'], $resizeOptions->imageQuality);

        //Add -thumb to end of filename
        $thumbFileFullUrlArr = explode('.', $newFileFullUrl);
        $thumbFileFullUrlArr[sizeof($thumbFileFullUrlArr) - 2] .= '-thumb';
        $thumbFileFullUrl = implode('.', $thumbFileFullUrlArr);

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $thumbFileFullUrl)) { //Successfully stored image
            $retArr['success'] = true;
        }
    }
}

编辑,这是ResizeImage类:

<?php
/**
 * Resize image class will allow you to resize an image
 *
 * Can resize to exact size
 * Max width size while keep aspect ratio
 * Max height size while keep aspect ratio
 * Automatic while keep aspect ratio
 */
class ResizeImage
{
    private $ext;
    private $image;
    private $newImage;
    private $origWidth;
    private $origHeight;
    private $resizeWidth;
    private $resizeHeight;
    /**
     * Class constructor requires to send through the image filename
     *
     * @param string $filename - Filename of the image you want to resize
     */
    public function __construct( $filename )
    {
        if(file_exists($filename))
        {
            $this->setImage( $filename );
        } else {
            throw new Exception('Image ' . $filename . ' can not be found, try another image.');
        }
    }
    /**
     * Set the image variable by using image create
     *
     * @param string $filename - The image filename
     */
    private function setImage( $filename )
    {
        $size = getimagesize($filename);
        $this->ext = $size['mime'];
        switch($this->ext)
        {
            // Image is a JPG
            case 'image/jpg':
            case 'image/jpeg':
                // create a jpeg extension
                $this->image = imagecreatefromjpeg($filename);
                break;
            // Image is a GIF
            case 'image/gif':
                $this->image = @imagecreatefromgif($filename);
                break;
            // Image is a PNG
            case 'image/png':
                $this->image = @imagecreatefrompng($filename);
                break;
            // Mime type not found
            default:
                throw new Exception("File is not an image, please use another file type.", 1);
        }
        $this->origWidth = imagesx($this->image);
        $this->origHeight = imagesy($this->image);
    }
    /**
     * Save the image as the image type the original image was
     *
     * @param  String[type] $savePath     - The path to store the new image
     * @param  string $imageQuality       - The qulaity level of image to create
     *
     * @return Saves the image
     */
    public function saveImage($savePath, $imageQuality = 100, $download = false)
    {
        switch($this->ext)
        {
            case 'image/jpg':
            case 'image/jpeg':
                // Check PHP supports this file type
                if (imagetypes() & IMG_JPG) {
                    imagejpeg($this->newImage, $savePath, $imageQuality);
                }
                break;
            case 'image/gif':
                // Check PHP supports this file type
                if (imagetypes() & IMG_GIF) {
                    imagegif($this->newImage, $savePath);
                }
                break;
            case 'image/png':
                $invertScaleQuality = 9 - round(($imageQuality/100) * 9);
                // Check PHP supports this file type
                if (imagetypes() & IMG_PNG) {
                    imagepng($this->newImage, $savePath, $invertScaleQuality);
                }
                break;
        }

        if ($download)
        {
            header('Content-Description: File Transfer');
            header("Content-type: application/octet-stream");
            header("Content-disposition: attachment; filename= ".$savePath."");
            readfile($savePath);
        }
        imagedestroy($this->newImage);
    }
    /**
     * Resize the image to these set dimensions
     *
     * @param  int $width           - Max width of the image
     * @param  int $height          - Max height of the image
     * @param  string $resizeOption - Scale option for the image
     *
     * @return Save new image
     */
    public function resizeTo( $width, $height, $resizeOption = 'default' )
    {
        switch(strtolower($resizeOption))
        {
            case 'exact':
                $this->resizeWidth = $width;
                $this->resizeHeight = $height;
            break;
            case 'maxwidth':
                $this->resizeWidth  = $width;
                $this->resizeHeight = $this->resizeHeightByWidth($width);
            break;
            case 'maxheight':
                $this->resizeWidth  = $this->resizeWidthByHeight($height);
                $this->resizeHeight = $height;
            break;
            default:
                if($this->origWidth > $width || $this->origHeight > $height)
                {
                    if ( $this->origWidth > $this->origHeight ) {
                         $this->resizeHeight = $this->resizeHeightByWidth($width);
                         $this->resizeWidth  = $width;
                    } else if( $this->origWidth < $this->origHeight ) {
                        $this->resizeWidth  = $this->resizeWidthByHeight($height);
                        $this->resizeHeight = $height;
                    }
                } else {
                    $this->resizeWidth = $width;
                    $this->resizeHeight = $height;
                }
            break;
        }

        $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);

        //Image is of a type that may have transparent background
        if ($this->ext == 'image/png' || $this->ext == 'image/gif') {
            // integer representation of the color black (rgb: 0,0,0)
            $background = imagecolorallocate($this->newImage , 0, 0, 0);
            // removing the black from the placeholder
            imagecolortransparent($this->newImage, $background);

            // turning off alpha blending (to ensure alpha channel information
            // is preserved, rather than removed (blending with the rest of the
            // image in the form of black))
            imagealphablending($this->newImage, false);

            // turning on alpha channel information saving (to ensure the full range
            // of transparency is preserved)
            imagesavealpha($this->newImage, true);
        }

        imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
    }
    /**
     * Get the resized height from the width keeping the aspect ratio
     *
     * @param  int $width - Max image width
     *
     * @return Height keeping aspect ratio
     */
    private function resizeHeightByWidth($width)
    {
        return floor(($this->origHeight/$this->origWidth)*$width);
    }
    /**
     * Get the resized width from the height keeping the aspect ratio
     *
     * @param  int $height - Max image height
     *
     * @return Width keeping aspect ratio
     */
    private function resizeWidthByHeight($height)
    {
        return floor(($this->origWidth/$this->origHeight)*$height);
    }
}
?>

0 个答案:

没有答案