使用GD库裁剪/调整图像功能 [英] Crop/Resize Image Function using GD Library

查看:83
本文介绍了使用GD库裁剪/调整图像功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本可以运行,但是我希望调用它

My script works however I wish to call upon this

// Example
resize_crop_image(max_width, max_height, source_file, dst_dir);
// Should-be Calling???
resize_crop_image(120, 120, $name, UPLOAD_DIR);

下面是我的完整脚本,没有调用此函数进行裁剪然后重新调整大小.我已经尝试了几种方法,但我相信这只是我只是想念的东西或者还没有理解...

Below is my fully working script without calling upon this function to crop then resize. I have tried several ways and I believe it is something simply I just am missing or do notyet understand...

define("UPLOAD_DIR", "../Desktop/IMG/BananzaNews/Thumbs/");

if (!empty($_FILES["file"])) {
    $myFile = $_FILES["file"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }

    // verify the file is a GIF, JPEG, or PNG
    $fileType = exif_imagetype($_FILES["file"]["tmp_name"]);
    $allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
    if (!in_array($fileType, $allowed)) {
        // file type is not permitted
    } else {

        // ensure a safe filename
        $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

        // don't overwrite an existing file
        $i = 0;
        $parts = pathinfo($name);
        while (file_exists(UPLOAD_DIR . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }

        //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);
        }

        // preserve file from temporary directory
        $success = move_uploaded_file($myFile["tmp_name"],
            UPLOAD_DIR . $name);
            $img = "http://www.rafflebananza.com/Desktop/IMG/BananzaNews/Thumbs/" . $_FILES["file"]["name"];
        if (!$success) { 
            echo "<p>Unable to save file.</p>";
            exit;
        }

        // set proper permissions on the new file
        chmod(UPLOAD_DIR . $name, 0644);
    }
} else {
    die("An error occurred uploading ".$_FILES["file"]["error"].": ".$sql);
}

推荐答案

这里是一个使用您所拥有内容的类.它将保存您的文件到您想要的任何大小尺寸.我已将其标记为您的理解:

Here is a class that uses what you have plus a bit more. It will save your file to whatever size dimensions you want. I have notated it for your understanding:

class ImageFactory
    {
        protected   $original;
        public      $destination;

        public  function FetchOriginal($file)
            {
                $size                       =   getimagesize($file);
                $this->original['width']    =   $size[0];
                $this->original['height']   =   $size[1];
                $this->original['type']     =   $size['mime'];
                return $this;
            }

        public  function Thumbnailer($thumb_target = '', $width = 60,$height = 60,$SetFileName = false, $quality = 80)
            {
                // Set original file settings
                $this->FetchOriginal($thumb_target);
                // Determine kind to extract from
                if($this->original['type'] == 'image/gif')
                    $thumb_img  =   imagecreatefromgif($thumb_target);
                elseif($this->original['type'] == 'image/png') {
                        $thumb_img  =   imagecreatefrompng($thumb_target);
                        $quality    =   7;
                    }
                elseif($this->original['type'] == 'image/jpeg')
                        $thumb_img  =   imagecreatefromjpeg($thumb_target);
                else
                    return false;
                // Assign variables for calculations
                $w  =   $this->original['width'];
                $h  =   $this->original['height'];
                // Calculate proportional height/width
                if($w > $h) {
                        $new_height =   $height;
                        $new_width  =   floor($w * ($new_height / $h));
                        $crop_x     =   ceil(($w - $h) / 2);
                        $crop_y     =   0;
                    }
                else {
                        $new_width  =   $width;
                        $new_height =   floor( $h * ( $new_width / $w ));
                        $crop_x     =   0;
                        $crop_y     =   ceil(($h - $w) / 2);
                    }
                // New image
                $tmp_img = imagecreatetruecolor($width,$height);
                // Copy/crop action
                imagecopyresampled($tmp_img, $thumb_img, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $w, $h);
                // If false, send browser header for output to browser window
                if($SetFileName == false)
                    header('Content-Type: '.$this->original['type']);
                // Output proper image type
                if($this->original['type'] == 'image/gif')
                    imagegif($tmp_img);
                elseif($this->original['type'] == 'image/png')
                    ($SetFileName !== false)? imagepng($tmp_img, $SetFileName, $quality) : imagepng($tmp_img);
                elseif($this->original['type'] == 'image/jpeg')
                    ($SetFileName !== false)? imagejpeg($tmp_img, $SetFileName, $quality) : imagejpeg($tmp_img);
                // Destroy set images
                if(isset($thumb_img))
                    imagedestroy($thumb_img); 
                // Destroy image
                if(isset($tmp_img))
                    imagedestroy($tmp_img);
            }
    }

用法示例:

// Initiate class
$ImageMaker =   new ImageFactory();

// Here is just a test landscape sized image
$thumb_target   =   'http://media1.santabanta.com/full6/Outdoors/Landscapes/landscapes-246a.jpg';

// This will save the file to disk. $destination is where the file will save and with what name
$destination    =   'image60px.jpg';
$ImageMaker->Thumbnailer($thumb_target,120,120,$destination);

// This example will just display to browser, not save to disk
// $ImageMaker->Thumbnailer($thumb_target,120,120);

这篇关于使用GD库裁剪/调整图像功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆