首页 文章

使用PHP,Laravel,GD上传图像并将多个大小保存到文件系统

提问于
浏览
2

我正在尝试允许用户上传图像并将图像保存为目录中的“原始副本”

public_html/data/user_images/yyyy/MM/dd/guid.ext

接下来,使用GD I创建不同大小的图像的多个副本,并保存到文件系统中的另一个动态位置 .

public_html/data/user_images/width/yyyy/MM/dd/guid.ext

我一直遇到以下错误,这让我相信文件需要存在才能使用GD库保存操作的图像 .

imagejpeg(/data/user_images/200/2013/05/21/9714624e10eed645e822babd0acccf69ac421d59.png): 

failed to open stream: No such file or directory

我得到相对和绝对路径相同的错误 . 我知道这个目录或文件不存在 . 保存上传图像的原始副本时,代码按预期工作,我无法在动态目录中创建新代码 .

下面是我的图片助手的代码 . 作为参数,它采用原始保存的图像位置,新图像的大小数组和文件名 . createDirectories函数返回一个包含绝对和相对动态创建路径的数组 .

public static function create_sizes($image, $sizes, $filename){

    $current_size = GetimageSize($image);
    $urls = array();

    switch(strtolower($current_size['mime'])){
        case 'image/png':
            $image_original = imagecreatefrompng($image);
            break;
        case 'image/jpeg':
            $image_original = imagecreatefromjpeg($image);
            break;
        case 'image/gif':
            $image_original = imagecreatefromgif($image);
            break;
        default: die();
    }



    foreach($sizes as $width){

        $directories = self::createDirectories('user_images/'.$width);

        $aspect_ratio = $current_size[0] / $current_size[1];
        $height = (int) ($width / $aspect_ratio);

        $photoX = ImagesX($image_original);
        $photoY = ImagesY($image_original);

        $image_new = ImageCreateTrueColor($width, $height);

        ImageCopyResampled($image_new, $image_original, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);

        ImageJPEG($image_new, $directories['absolute'].$filename, 100);
        array_push($urls, $directories['relative'].$filename);
    }

    ImageDestroy($image_original);
    ImageDestroy($image_new);

    return $urls;
}

1 回答

  • 3

    快速浏览一下我的ImageProcessor类 . 我认为它会对你有所帮助:http://pastebin.com/zNY02N57

    用法:当用户上传文件时,其名称位于$ _FILES ['input_name'] ['tmp_name']中 . 首先创建我的类的空实例:

    $OriginalImage = new ImageProcessor();
    //Note that it will automatically detect the file type :)
    if(!$OriginalImage->Load($_FILES['input_name']['tmp_name']))
        die('Image is invalid');
    

    现在你必须选择调整大小的方法 . 您可以强制图像具有固定的宽度或高度,或者具有您选择的精确尺寸,但如果它不适合,它将在黑色背景上 .

    Fixed width:
    $NewImage = $OriginalImage->ResizeWPreserve($NewWidth)
    Fixed height:
    $NewImage = $OriginalImage->ResizeHPreserve($NewHeight)
    Fixed size:
    $NewImage = $OriginalImage->ResizeCanvas($NewWidth, $NewHeight)
    
    Then, to save it, simply:
    $NewImage->Save('FileName.jpg');
    

    您可以在循环中重复保存和调整大小,如:

    $Sizes = array(640, 800, 1024);
    foreach($Sizes as $Width)
    {
        $OriginalImage->ResizeWPreserve($Width)->Save(sprintf('Images/%s/%d.jpg', 'SomeName', $Width));
    }
    

相关问题