[0, 0], 'pct' => 100, ], $options); imagecopymerge( $resource, $addResource, $options['position'][0], $options['position'][1], 0, 0, imagesx($addResource), imagesy($addResource), $options['pct'] ); return $resource; } /** * 为图片添加文字 * @param $resource * @param string $text * @param array $options * @return mixed */ public static function text(&$resource, $text = '', $options = []) { $options = array_merge([ 'font' => __DIR__ . '/font.ttf', 'color' => [255, 255, 255], 'size' => 20, 'position' => [25, 20], ], $options); $color = call_user_func_array( 'imagecolorallocate', array_merge([$resource], $options['color']) ); $currentEncoding = mb_detect_encoding($text); if ($currentEncoding != 'UTF-8') { $text = iconv($currentEncoding, 'UTF-8', $text); } imagettftext($resource, $options['size'], 0, $options['position'][0], $options['position'][1], $color, $options['font'], $text); return $resource; } /** * 修改图片/资源大小 * @param $filename * @param $width * @param $height * @param false $crop * @return false|GdImage|resource */ public static function resize($filename, $width, $height, $crop = false) { if (is_resource($filename)) { $size = [imagesx($filename), imagesy($filename)]; $resource = $filename; } else { $size = self::getImageSize($filename); $resource = self::createResourceFromFile($filename); } // 宽高比 $resourceProp = $size[1] / $size[0]; $targetProp = $height / $width; if ($resourceProp > $targetProp) { $targetWidth = $width; $targetHeight = $width * $resourceProp; } else if ($resourceProp < $targetProp) { $targetHeight = $height; $targetWidth = $height / $resourceProp; } else { $targetWidth = $width; $targetHeight = $height; } // 创建资源 $targetResource = self::createResource($targetWidth, $targetHeight); // 缩放 imagecopyresampled($targetResource, $resource, 0, 0, 0, 0, $targetWidth, $targetHeight, $size[0], $size[1]); // 裁剪 if (true === $crop) { // 居中 $sourceX = ($targetWidth - $width) / 2; $sourceY = ($targetHeight - $height) / 2; $cropResource = self::createResource($width, $height); imagecopy($cropResource, $targetResource, 0, 0, $sourceX, $sourceY, $width, $height); return $cropResource; } return $targetResource; } /** * 保存图片 * @param $resource * @param $filename * @return bool */ public static function save($resource, $filename) { $fileNameArr = explode('.', $filename); $fileExt = strtolower(end($fileNameArr)); unset($fileNameArr); switch ($fileExt) { case 'jpg': case 'jpeg': return imagejpeg($resource, $filename); case 'png': return imagepng($resource, $filename); case 'gif': return imagegif($resource, $filename); default: } return false; } }