网站首页php

封装一个PHP的图片处理类

发布时间:2019-12-31 12:00:38编辑:slayer.hover阅读(660)

    用于处理图片缩放,高斯模糊,锐化,图文识别的PHP类.


    class ImgTools
    {
        #图片高斯模糊(适用于png/jpg/gif格式)
        public function gaussian_blur(string $source, string $target,int $blurFactor = 1)
        {
            $gdImageResource = $this->image_create_from_ext($source);
            $srcImgObj       = $this->blur($gdImageResource, $blurFactor);
            $srcinfo         = getimagesize($source);
            switch ($srcinfo[2]) {
                case 1:
                    imagegif($srcImgObj, $target);
                    break;
                case 2:
                    imagejpeg($srcImgObj, $target);
                    break;
                case 3:
                    imagepng($srcImgObj, $target);
                    break;
                default:
                    return '保存失败'; //保存失败
            }
            imagedestroy($srcImgObj);
        }
        private function blur(resource $gdImageResource, int $blurFactor = 1)
        {
            $blurFactor = round($blurFactor);
            $originalWidth  = imagesx($gdImageResource);
            $originalHeight = imagesy($gdImageResource);
            $smallestWidth  = ceil($originalWidth * pow(0.5, $blurFactor));
            $smallestHeight = ceil($originalHeight * pow(0.5, $blurFactor));
            
            $prevImage  = $gdImageResource;
            $prevWidth  = $originalWidth;
            $prevHeight = $originalHeight;
            
            for ($i = 0; $i < $blurFactor; $i += 1) {
                // determine dimensions of next image
                $nextWidth  = $smallestWidth * pow(2, $i);
                $nextHeight = $smallestHeight * pow(2, $i);
                // resize previous image to next size
                $nextImage = imagecreatetruecolor($nextWidth, $nextHeight);
                imagecopyresized($nextImage, $prevImage, 0, 0, 0, 0, 
                        $nextWidth, $nextHeight, $prevWidth, $prevHeight);
                // apply blur filter
                imagefilter($nextImage, IMG_FILTER_GAUSSIAN_BLUR);
                // now the new image becomes the previous image for the next step
                $prevImage  = $nextImage;
                $prevWidth  = $nextWidth;
                $prevHeight = $nextHeight;
            }
            imagecopyresized($gdImageResource, $nextImage, 0, 0, 0, 0, 
                    $originalWidth, $originalHeight, $nextWidth, $nextHeight);
            imagefilter($gdImageResource, IMG_FILTER_GAUSSIAN_BLUR);
            imagedestroy($prevImage);
            return $gdImageResource;
        }
        private function image_create_from_ext(string $imgfile)
        {
            $info = getimagesize($imgfile);
            $im   = null;
            switch ($info[2]) {
                case 1:
                    $im = imagecreatefromgif($imgfile);
                    break;
                case 2:
                    $im = imagecreatefromjpeg($imgfile);
                    break;
                case 3:
                    $im = imagecreatefrompng($imgfile);
                    break;
            }
            return $im;
        }
        #锐化
        public function GDMakeJpegLookLikeCrap(string $source, string $target)
        {
            $image         = imagecreatefromjpeg($source);
            $sharpenMatrix = [
                [-1, -1, -1],
                [-1, -1, -1],
                [-1, -1, -1]
            ];
            $divisor       = array_sum(array_map('array_sum', $sharpenMatrix));
            $offset        = 0;
            imageconvolution($image, $sharpenMatrix, $divisor, $offset);
            imagejpeg($image, $target, 100);
            imagedestroy($image);
        }
        #按比例缩放图片
        public function thumb(string $source, string $target, int $des_w, int $des_h)
        {
            //获取图片的类型
            $srcarr = getimagesize($source);
            //处理图片创建函数和图片输出函数
            switch ($srcarr[2]) {
                case 1://gif
                    $imagecreatefrom = 'imagecreatefromgif';
                    $imageout        = 'imagegif';
                    break;
                case 2://jpg
                    $imagecreatefrom = 'imagecreatefromjpeg';
                    $imageout        = 'imagejpeg';
                    break;
                case 3://png
                    $imagecreatefrom = 'imagecreatefrompng';
                    $imageout        = 'imagepng';
                    break;
            }
            // 创建原图资源
            $src_img = $imagecreatefrom($source);
            //获取原图的宽高
            $src_w = imagesx($src_img);
            $src_h = imagesy($src_img);
            // 计算缩放比例(用原图片的宽高分别处以对应目的图片的宽高,选择比例大的作为基准进行缩放)
            $scale = ($src_w / $des_w) > ($src_h / $des_h) ? ($src_w / $des_w) : ($src_h / $des_h);
            //计算实际缩放时目的图的宽高(向下取整)
            $des_w = floor($src_w / $scale);
            $des_h = floor($src_h / $scale);
            //创建画布
            $des_img = imagecreatetruecolor($des_w, $des_h);
            //设置缩放起点
            $des_x = 0;
            $des_y = 0;
            $src_x = 0;
            $src_y = 0;
            //缩放
            imagecopyresampled($des_img, $src_img, $des_x, $des_y, $src_x, $src_y, $des_w, $des_h, $src_w, $src_h);
            //输出图片
            $imageout($des_img, $target);
        }
        #文本识别调用百度图文识别接口
        public function img2txt(string $image): string
        {
            $code         = '';
            $access_token = $this->get_ocr_access_token();
            $url          = 'https://aip.baidubce.com/rest/2.0/ocr/v1/webimage?access_token=' . $access_token;
            $headers      = ['Content-Type:application/x-www-form-urlencoded'];
            $postData     = 'image=' . urlencode(base64_encode(file_get_contents($image)));
            $data         = json_decode(curl_data($url, $postData, false, false, '', $headers), TRUE);
            if (!empty($data['words_result'])) {
                foreach ($data['words_result'] as $k => $v) {
                    $code .= $v['words'] . PHP_EOL;
                }
            }
            return $code;
        }
        private function remember($key, $ttl, callable $func)
        {
            if (class_exists('redis')) {
                $cache = new redis();
                $cache->connect('127.0.0.1', '6379');
                $cache->select(2);
                if ($cache->exists($key)) {
                    return $cache->get($key);
                }
                $rows = call_user_func($func);
                $cache->set($key, $rows, $ttl);
                return $rows;
            } else {
                return call_user_func($func);
            }
        }
        private function get_ocr_access_token()
        {
            return $this->remember('ocrToken', 2590000, function () {
                $url                        = 'https://aip.baidubce.com/oauth/2.0/token';
                $post_data['grant_type']    = 'client_credentials';
                $post_data['client_id']     = 'puD3MMcpW2DM4TInTT84mM3n';
                $post_data['client_secret'] = 'SNXEjqnOhmmMjK7XQIX8QQ5zdk4HVwNy';
                $res                        = curl_data($url, $post_data);
                $resArr                     = json_decode($res, TRUE);
                return $resArr['access_token'];
            });
        }
    }


    用法如下:


    $source = './images/captcha.jpg';   //源图
    $bigger = './images/b_captcha.jpg'; //放大
    $blur  = './images/m_captcha.jpg'; //模糊
    $crap  = './images/r_captcha.jpg'; //锐化
    $target = './images/t_captcha.jpg'; //目标图
    
    $imgTool = new ImgTools;
    #放大
    $imgTool->thumb($source, $bigger, 600, 300);
    
    #模糊
    $imgTool->gaussian_blur($bigger, $blur);
    
    #锐化
    $imgTool->GDMakeJpegLookLikeCrap($blur, $crap);
    
    #缩放
    $imgTool->thumb($crap, $target, 60, 30);
    
    #图文识别
    $code = $imgTool->img2txt($target);
    echo $code;


    具体使用场景自己意会~



评论