php合成圖片 文字


代碼:

public function mergePic(){
        $ground = '/Public/merge/beijing.png';
        $img = [
            'url'=>'/Public/merge/qrcode.png',
            'x'=>100,
            'y'=>100
        ];
        $qr = [
            'url'=>'/Public/merge/qr.jpg',
            'x'=>150,
            'y'=>1400
        ];
        $text = [
            'size'=>20,
            'text'=>'123456'
        ];
        $this->merge($ground,$img,$qr,$text);
    }

    /**
     * @param $ground string 背景
     * @param $img array 圖片
     * @param $qr array 二維碼
     * @param $text array 文字
     */
    public function merge($ground,$img=[],$qr=[],$text=[]){
        $types = [
            "image/jpg" => 'imagecreatefromjpeg',
            "image/jpeg" => 'imagecreatefromjpeg',
            "image/png" => 'imagecreatefrompng',
            "image/pjpeg"  => 'imagecreatefromjpeg',
            "image/gif"  => 'imagecreatefromgif',
            "image/bmp"  => 'imagecreatefromwbmp',
            "image/x-png"  => 'imagecreatefromjpeg'
        ];
        $groundMime = getimagesize(getcwd().$ground);
        $grounds = $types[$groundMime['mime']](getcwd().$ground);//獲取圖片資源
//        $fileName = "/Public/merge/".time().".png";//保存圖片目錄
        $fileName = "/Public/merge/123.png";//保存圖片目錄
        if($img){
            $imgMime = getimagesize(getcwd().$img['url']);
            $imgs = $types[$imgMime['mime']](getcwd().$img['url']);//獲取圖片資源
            $imgsW = imagesx($imgs);//圖片寬
            $imgsH = imagesy($imgs);//圖片高
            imagecopy($grounds, $imgs, $img['x'], $img['y'], 0, 0, $imgsW, $imgsH);//核心函數:復制圖片資源到另一圖片資源中
        }

        if($qr){
            $qrMime = getimagesize(getcwd().$qr['url']);
            $qrs = $types[$qrMime['mime']](getcwd().$qr['url']);//獲取圖片資源
            $qrsW = imagesx($qrs);//圖片寬
            $qrsH = imagesy($qrs);//圖片高
            imagecopy($grounds, $qrs, $qr['x'], $qr['y'], 0, 0, $qrsW, $qrsH);//核心函數:復制圖片資源到另一圖片資源中
        }

        if($text){
            $size = $text['size'];//字體大小
            $font = "./Public/merge/yuanti.ttf";//字體
            $text = $text['text'];//顯示的文字
            $grey = imagecolorallocate($grounds,0,0,0);//設置字體顏色
            imagettftext($grounds,$size,0,100,100,$grey,$font,$text);//將ttf文字寫到圖片中
        }

        imagepng($grounds,getcwd().$fileName); //保存
        imagedestroy($grounds);
        imagedestroy($imgs);
        imagedestroy($qrs);//銷毀圖片資源
    }

 參考:

PHP 使用GD庫合成帶二維碼的海報步驟以及源碼實現

將圖片繪制到畫布上:imagecopy()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM