图片处理 - PHP 工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片处理 - PHP 工具类相关的知识,希望对你有一定的参考价值。

图片处理 - php 工具类

<?php
/**
 * Created by PhpStorm.
 * User: peeke
 * Date: 2020/4/22
 * Time: 08:53
 */

namespace App\\common\\Helpers\\tools;


class ImageHelper


    /**
     * 增加图片样式,防止图片在手机端显示溢出
     *
     * @param $content
     * @return string
     */
    public static function mobileShow($content)
    
        return "<style>imgwidth:100%</style>" . self::removeWidthAndHeight($content);
    


    /**
     * 移除图片宽高
     *
     * @param $content
     * @return string
     */
    public static function removeWidthAndHeight($content)
    
        $content = strtolower($content);
        $content = preg_replace("/(<img.*?)?width[ ]*=[ ]*[|\\"]?\\S+[|\\"]?(.*?\\/>)/", $1$2, $content);
        $content = preg_replace("/(<img.*?)?height[ ]*=[ ]*[|\\"]?\\S+[|\\"]?(.*?\\/>)/", $1$2, $content);
        $content = preg_replace("/(<img.*)+.*?width[ ]*:[ ]*\\S*?([;| |\\"|\\]+.*?\\/>)+/", $1$2, $content);
        $content = preg_replace("/(<img.*)+.*?height[ ]*:[ ]*\\S*?([;| |\\"|\\]+.*?\\/>)+/", $1$2, $content);
        return $content;
    

    /**
     * 获取图片地址
     *
     * @param $path
     * @return string
     */
    public static function getImageUrl($path)
    
        //dd(env("OSS_BINDING_DOMAIN",env("IMAGES_DOMAIN")).$path);
        return env("OSS_BINDING_DOMAIN", env("IMAGES_DOMAIN")) . $path;
    

    /**
     * 获取缩略图地址
     *
     * @param $path
     * @return string
     */
    public static function getImageUrlThumbnail($path)
    
        if (empty($path)) 
            return ;
        
        return env("OSS_BINDING_DOMAIN", env("IMAGES_DOMAIN")) . $path . env("oss_img_style", "?x-oss-process=style/percent-50");
    

    /**
     * 获取图片OSS地址
     *
     * @param $path
     * @return string
     */
    public static function getOssImageUrl($path)
    
        return env("OSS_BINDING_DOMAIN") . $path;
    

    /**
     * 获取图片的真实路径
     *
     * @param $path
     * @return string
     */
    public static function getImagePath($path)
    
        $dir = env("PUBLIC_PATH", public_path() . DIRECTORY_SEPARATOR);

        return $dir . $path;
    


    /**
     * 将图片转换成所需的图片格式
     *
     * @param $srcFile  图片来源路径
     * @param $dstExt   转成后的图片路径
     * @param $quality  质量值
     * @return bool|false|string
     */
    public static function convertPic($srcFile, $dstExt = jpg, $percent = 1, $quality = 100, $isremote = true)
    
        if (!in_array($dstExt, [jpg, png, webp])) 
            return false;
        
        if ($isremote) 
            $reaFile = UrlHelper::imagesUrl($srcFile);
         else 
            $reaFile = $srcFile;
        
        //$reaFile = "http://static.yiquantong.vip/upload/users/2021/06/01/2021060115580885910423290.jpg";
        // 2021060115580885910423290
        if (!is_file($reaFile)) 
            //return false;
        
        $srcType = getimagesize($reaFile);

        $fileInfo = pathinfo($reaFile);
        //dd($fileInfo);
        $dirname = rtrim($fileInfo[dirname], /) . /;
        //dd($dirname);
        $filename = $fileInfo[filename];
        list($width, $height, $imgType) = $srcType;

        $im = null;
        // 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP
        switch ($imgType) 
            case 1:
                $im = imagecreatefromgif($reaFile);
                break;
            case 2:
                $im = imagecreatefromjpeg($reaFile);
                break;
            case 3:
                $im = imagecreatefrompng($reaFile);
                break;
            case 18:
                //$im = imagecreatetruecolor(120, 20);
                $im = imagecreatefromwebp($reaFile);
                break;

        


        // 重新取样P
        $newWidth  = $width * $percent;
        $newHeight = $height * $percent;

        $imageP = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($imageP, $im, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);


        $imageFunction = imagejpeg;
        if ($dstExt != jpg) 
            $imageFunction = image . $dstExt;
        

        $savePath = null;


        if ($savePath) 
            $imgInfo = $imageFunction($im, $savePath, $quality);
            //return $savePath;
         else 
            $savePath = public_path(upload/users/ . convert_ . $filename . . . $dstExt);
            $imgInfo  = $imageFunction($imageP, $savePath, $quality);
            //return $savePath;
            //$newFilecontent = file_get_contents($newDir);


        

        imagedestroy($im);
        return $savePath;

    

    /**
     * 将图片转换成所需的图片格式
     *
     * @param        $srcFile 图片来源路径
     * @param string $dstExt  转成后的图片路径
     * @param int    $percent
     * @param int    $quality 质量值
     * @return bool|false|string
     */
    public static function convertLocalPic($srcFile, $dstExt = jpg, $percent = 1, $quality = 100)
    
        if (!in_array($dstExt, [jpg, png])) 
            return false;
        
        $reaFile = $srcFile;

        $srcType = getimagesize($reaFile);

        $fileInfo = pathinfo($reaFile);
        //dd($fileInfo);
        $dirname = rtrim($fileInfo[dirname], /) . /;
        //dd($dirname);
        $filename = $fileInfo[filename];
        list($width, $height, $imgType) = $srcType;

        $im = null;
        // 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP
        switch ($imgType) 
            case 1:
                $im = imagecreatefromgif($reaFile);
                break;
            case 2:
                $im = imagecreatefromjpeg($reaFile);
                break;
            case 3:
                $im = imagecreatefrompng($reaFile);
                break;
        

        // 重新取样P
        $newWidth  = $width * $percent;
        $newHeight = $height * $percent;

        $imageP = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($imageP, $im, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);


        $imageFunction = imagejpeg;
        if ($dstExt != jpg) 
            $imageFunction = image . $dstExt;
        

        $savePath = null;


        if ($savePath) 
            $imgInfo = $imageFunction($im, $savePath, $quality);
            //return $savePath;
         else 
            $savePath = public_path(upload/users/ . convert_ . $filename . . . $dstExt);
            $imgInfo  = $imageFunction($imageP, $savePath, $quality);
            //return $savePath;
            //$newFilecontent = file_get_contents($newDir);


        

        imagedestroy($im);
        return $savePath;

    

    /**
     * 同时支持本地及远程图片BASE64
     *
     * @param $file
     * @return string|string[]
     */
    public static function imageBase64($file)
    
        if (empty($file) || !FileHelper::file_exists($file)) 
            return ;
        
        $fileName = FileHelper::get_file_name($file);
        $newFile  = $file;
        if (FileHelper::isRemoteFile($file) && FileHelper::downloadUrlFile($file, FileHelper::getUploadFile(upload/tmp/ . $fileName))) 
            $newFile = FileHelper::getUploadFile(upload/tmp/ . $fileName);
        
        $content       = file_get_contents($newFile);
        $contentBase64 = base64_encode($content);
        //$contentBase64 = str_replace("+", "%2B", $contentBase64);
        return $contentBase64;
    

    /**
     * 将图片远程文件转成base64编码
     *
     * @param $file 远程图片
     * @return string
     */
    public static function fileToBase64($file)
    
        // 取得图片的大小,类型等
        $type    = getimagesize($file);
        $content = file_get_contents($file);
        //base64编码
        //$fileContent = base64_encode($content);
        $fileContent = self::imageBase64($file);
        $imgType     = jeg;
        switch ($type[2]) //判读图片类型
            case 1:
                $imgType = "gif";
                break;
            case 2:
                $imgType = "jpg";
                break;
            case 3:
                $imgType = "png";
                break;
        
        //合成图片的base64编码
        $img = data:image/ . $imgType . ;base64, . $fileContent;
        //$img = str_replace("+", "%2B", $img);
        return $img;

    


    /**
     * 根据消息类型获取对应的消息类型图标
     *
     * @param int $type
     * @return string
     */
    public static function getPhoneMessageIcon(int $type)
    
        switch ($type) 
            case 1:
                return ImageHelper::getImageUrl("/phone/ic_system_m@3x.png");
            case 2:
                return ImageHelper::getImageUrl("/phone/ic_shouru@3x.png");
            case 3:
                return ImageHelper::getImageUrl("/phone/ic_serve@3x.png");
            case 4:
                return ImageHelper::getImageUrl("/phone/ic_message_certificate@3x.png");
            case 5:
                return ImageHelper::getImageUrl("/phone/ic_message_certificate@3x.png");
            case 6:
                return ImageHelper::getImageUrl("/phone/ic_message_zb@3x.png");
            case 7:
                return ImageHelper::getImageUrl("/phone/ic_message_xy@3x.png");
            case 8:
                return ImageHelper::getImageUrl("/phone/ic_message_cwjs@3x.png");
            case 9:
                return ImageHelper::getImageUrl("/phone/ic_Smartphone@3x.png");
            case 10:
                return ImageHelper::getImageUrl("/phone/ic_message_signet@3x.png");
            case 11:
                return ImageHelper::getImageUrl("/phone/ic_message_zb@3x.png");
        
        return ImageHelper::getImageUrl("/phone/ic_system_m@3x.png");
    


    /**
     * 判断远程图片是否存在
     *
     * @param $url
     * @return bool
     */
    public static function remote_image_exists($url)
    
        $curl = curl_init($url);
        // 不取回数据
        curl_setopt($curl, CURLOPT_NOBODY, true);
        // 发送请求
        $result = curl_exec($curl);
        $found  = false;
        // 如果请求没有发送失败
        if ($result !== false) 
            $info = curl_getinfo($curl);
            if ($info["http_code"] == 200) 
                $found = true;
            
        
        return $found;
    


    /**
     * 简单的文件转存
     *
     * @param $url
     * @param $locatPath
     * @return bool
     */
    public static function remoteToLocal($url, $locatPath)
    
        if (self::remote_image_exists($url)) 
            if (!file_exists(dirname($locatPath))) 
                mkdir(dirname($locatPath), 0777, true);
            
            file_put_contents($locatPath, file_get_contents($url));
        
        return true;
    

    /**
     * 将历史大写改为小写存入库内
     *
     * @param string $str
     * @return mixed
     */
    public static function thumbnailUpperTolower(string $str)
    
        return str_replace([
            "image_url_Thumbnail",
            "image_path_Thumbnail",
        ], [
            "image_url_thumbnail",
            "image_path_thumbnail",
        ], $str);
    

    /**
     * 获取缩略图
     *
     * @param array $json
     * @return mixed
     */
    public static function getImageThumbnail(array $json)
    
        return $json["image_path_thumbnail"] ?? ($json["image_path_Thumbnail"] ?? ($json["image_path"] ?? ""));
    


    /**
     * 根据宽度生成压缩图片
     *
     * @param $sFile           压缩文件地址
     * @param $width        指定图片格式化后的宽度
     * @return bool|string
     */
    public static function resizeImage($srcImage, $width, $newFileName)
    
        $srcSize = getimagesize($srcImage);
        $ename   = explode(/, $srcSize[mime]);
        if (count($ename) < 2) 
            return $srcImage;
        
        $ext = $ename[1];
        if ($srcSize[0] <= $width) 
            return $srcImage;
        
        $height   = ($width / $srcSize[0]) * $srcSize[1];
        $tmpImage = imagecreatetruecolor($width, $height);
        $type     = substr(strrchr($srcImage, "."), 1);
        $type     = strtolower($type);

        //初始化图象
        if ($ext == "jpg" || $ext == "jpeg") 
            $srcImageSource = imagecreatefromjpeg($srcImage);
        
        if ($ext == "gif") 
            $srcImageSource = imagecreatefromgif($srcImage);
        
        if ($ext == "png") 
            $srcImageSource = imagecreatefrompng($srcImage);
        
        imagecopyresampled($tmpImage, $srcImageSource, 0, 0, 0, 0, $width, $height, $srcSize[0], $srcSize[1]);
        if (imagejpeg($tmpImage, $newFileName)) 
            return $newFileName;
        
        return $srcImage;
    


以上是关于图片处理 - PHP 工具类的主要内容,如果未能解决你的问题,请参考以下文章

图片处理 - PHP 工具类

PHP 图片处理工具类(添加水印与生成缩略图)

php获取图片完整Exif信息类 获取图片详细完整信息类

防止GD图像库内存不足的故障安全方法? (PHP)

遥感数字图象处理的问题,求GIS牛人解答

怎么提高png图象的质量?