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

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

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

之前用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 /**  * 订单任务  */ class Order {    &n...

【一】PHP多进程学习-简单创建父子进程.理解父子进程运行流程

【一】PHP多进程学习-简单创建父子进程.理解父子进程运行流程

(1).学习的目标:学会创建父子进程,并且能够区分当前进程是父还是子;了解父进程执行过程,子进程执行过程;能够用多进程执行任务(2).相关函数学习:    (2.1)pcntl_fork()执行时:       &nbs...

php json_encode 使用注意

php json_encode 使用注意

参数中包含gb2312的字符串,返回结果是false或者null(不同PHP版本具有差异性)代码:<?php $dbms = 'mysql'; $host = '192.168.8.8'; $dbName =&n...

php  while  true  cpu占用100%

php while true cpu占用100%

在编写多进程的实例中我在每个进程中使用如下代码://调用等待信号的处理器 while (true) {     pcntl_signal_dispatch(); }开启5个进程,cpu直接100%修正之后的代码://调用等待信号的处理器 while&...

php redis事务

php redis事务

概念请参考w3school文章: redis watch ,redis exec (看完基本秒懂)(1)基本事务://连接本地的 Redis 服务 $redis = new Redis(); $redis->con...

php端口复用,php socket端口复用

php端口复用,php socket端口复用

第一次听说端口复用是在mixphp最新版本中发现的,mixphp启动监听9501端口,现在作者说可以多开几个进程来执行mixphp,我心里想了下再启动不是会端口冲突嘛,但是却没有问题,于是下载mixphp的源码解读,原来是启动http服务器使用new Co\Http\Server('0.0....