当前位置:首页 > PHP > 正文内容

php为图片添加背景图,设置位于背景图的位置

高老师2年前 (2024-07-07)PHP412

之前用ceomax的wordpress主题发现它的缩略图很好看,于是其他项目也是参考它的来生成图片。

背景图如下:

ceo_img_1.png

原图如下:

944b687112.png

生成效果图:

new_image.jpg

参考代码:

// 使用示例
$originalImagePath = './944b687112.png';
$backgroundImagePath = './ceo_img_1.png';
$thumbnailWidth = 200;
$thumbnailHeight = 200;
$thumbnailQuality = 75;

// 加载图像
$background = imagecreatefrompng($backgroundImagePath);
$foreground = imagecreatefrompng($originalImagePath);

// 获取图像尺寸
$backgroundWidth = imagesx($background);
$backgroundHeight = imagesy($background);
$foregroundOriginalWidth = imagesx($foreground);
$foregroundOriginalHeight = imagesy($foreground);

// 计算缩放比例
$scaleX = $backgroundWidth / $foregroundOriginalWidth;
$scaleY = $backgroundHeight / $foregroundOriginalHeight;
$scale = min($scaleX, $scaleY); // 选择较小的比例以保证图像完全适应背景

// 计算缩放后的尺寸
$foregroundWidth = 282;
$foregroundHeight = 166;

// 创建一个新图像,大小与背景图像相同
$newImage = imagecreatetruecolor($backgroundWidth, $backgroundHeight);

// 复制背景图像到新图像
imagecopy($newImage, $background, 0, 0, 0, 0, $backgroundWidth, $backgroundHeight);

// 计算前景图像在新图像中的位置(这里居中)
$x = 59;
$y = 56;

// 使用imagecopyresampled缩放并复制前景图像到新图像
imagecopyresampled($newImage, $foreground, $x, $y, 0, 0, $foregroundWidth, $foregroundHeight, $foregroundOriginalWidth, $foregroundOriginalHeight);

// 保存新图像
imagejpeg($newImage, 'new_image.jpg', 100); // 90是质量参数,范围从0到100

// 释放资源
imagedestroy($background);
imagedestroy($foreground);
imagedestroy($newImage);



扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/791.html

分享给朋友:

“php为图片添加背景图,设置位于背景图的位置” 的相关文章

php 经纬度获取城市,php 经纬度转城市

php 经纬度获取城市,php 经纬度转城市

通过经纬度转换为城市名称,并获得城市的编号,通常在全国类型的商城中比较通用。//经纬度转城市名称(返回城市id,城市名称) //$ak开发密钥,$lat纬度,$lng经度,$type返回数据类型 public function getCityName($ak,$lat,$lng)...

xmlrpc  php,php通过xml-rpc进行通信

xmlrpc php,php通过xml-rpc进行通信

xmlrpc协议是通过http请求xml数据进行通信。webservice中和它相同的是soap。soap调用的确很简单,但是创建wsdl太繁琐,效率低下。xmlrpc很好的解决这个问题。(1).创建xmlrpc服务端(求和函数api)function getSum($method,$ar...

PHP异常处理,PHP自定义错误,PHP记录错误日志

PHP异常处理,PHP自定义错误,PHP记录错误日志

面试中PHP面试官会问调用一个不存在的方法,如何知道是哪个文件哪行调用的?假设方法是getWorkLoad()回答1:开启PHP错误输出,PHP会输出Fatal error: Call to undefined function getWorkLoad() in D:\wwwroot\thinkpa...

php守护进程

php守护进程

<?php /**  * daemonize让当前脚本为守护进程执行  * @param string $callback 匿名函数  */ function daemonize($callback) {...

PHP Warning:  ftok(): Project identifier is invalid

PHP Warning: ftok(): Project identifier is invalid

在使用ftok生成ipc进程通信key尝试将第二个参数项目标识符传入字符串报错:PHP Warning:  ftok(): Project identifier is invalid,查阅资料发现第二个字符串只能是1个字符串,长度为1....

PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl.dll找不到指定的模块

PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl.dll找不到指定的模块

最近在编写windows php多线程的东西,从官网下载了PHP的线程安全版,尝试开启curl扩展extension=php_curl.dllphp -m 却提示 PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl...