在上传到服务器之前裁剪图像

时间:2015-01-16 20:34:51

标签: php

所以我已经将这个PHP脚本扩展并从中心裁剪成一个正方形;

<?PHP
//resize and crop image by center
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
    $imgsize = getimagesize($source_file);
    $width = $imgsize[0];
    $height = $imgsize[1];
    $mime = $imgsize['mime'];

    switch($mime){
        case 'image/gif':
            $image_create = "imagecreatefromgif";
            $image = "imagegif";
            break;

        case 'image/png':
            $image_create = "imagecreatefrompng";
            $image = "imagepng";
            $quality = 7;
            break;

        case 'image/jpeg':
            $image_create = "imagecreatefromjpeg";
            $image = "imagejpeg";
            $quality = 80;
            break;

        default:
            return false;
            break;
    }

    $dst_img = imagecreatetruecolor($max_width, $max_height);
    $src_img = $image_create($source_file);

    $width_new = $height * $max_width / $max_height;
    $height_new = $width * $max_height / $max_width;
    //if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
    if($width_new > $width){
        //cut point by height
        $h_point = (($height - $height_new) / 2);
        //copy image
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
    }else{
        //cut point by width
        $w_point = (($width - $width_new) / 2);
        imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
    }

    $image($dst_img, $dst_dir, $quality);

    if($dst_img)imagedestroy($dst_img);
    if($src_img)imagedestroy($src_img);
}
//usage example
resize_crop_image(100, 100, "test.jpg", "test.jpg");p_image(100, 100, "test.jpg", "test.jpg");
?>

您只需调用以下函数:

resize_crop_image(100, 100, "test.jpg", "test.jpg");p_image(100, 100, "test.jpg", "test.jpg");

在上传到服务器之前,我的HTML5 / JQuery预览文件已添加到JSFiddle

1)。在运行此脚本之前,是否需要将图像上传到服务器?

2)。如果需要事先上传,我如何使用我的表单上传到临时位置,完成工作并移动到特定目录并删除临时目录?

2 个答案:

答案 0 :(得分:2)

1)是的,在您编辑/裁剪之前,需要在服务器上提供图像副本。 2)上传的文件自动存储在临时目录中(通常将它们复制出来以使用图像,但不一定要这样)。它们可以通过代码从temp目录中读取为图像,PHP也会自动清理脚本末尾的文件。

当文件上传时,$_FILES数组中有一个带有tmp名称的密钥。您可以将它作为源文件传递给您的函数,它应该与imagecopyresampled一起使用而没有任何问题。临时名称类似于$_FILES['nameFromFileFieldOnForm']['tmp_name']

答案 1 :(得分:0)

如果您的源文件或目标文件是

$source_file = www.example.com/storage/packages/image.jpg

将其更改为

$source_file = ./storage/packages/image.jpg

在laravel 5中它对我有用