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

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

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

之前用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使用post发送Json数据

PHP使用post发送Json数据

前公司吃饭是需要在钉钉报餐的,对于不挑剔的我每天都在公司吃饭,有时忘记报餐导致吃不了饭还是很麻烦的。看了下报餐系统需要的是json数据包含我的工号即可。于是编写如下代码,放在360网址监控,1小时执行1次<?php /*自动报餐类*/ class  AutoBaocan{...

cookie跨域,cookie p3p跨域

cookie跨域,cookie p3p跨域

最近在公司开发一个新的项目假设项目域名是a.com,需要接入b.com的单点登陆系统。(1).首先我们会在a.com的登陆页面用iframe引入b.com来显示登陆界面,实际上登陆验证操作都是在b.com上面(2).当b.com验证通过,会在前端ajax请求a.com的回调地址,这个回调地址目的就是...

php异步信号处理

php异步信号处理

php7.1引入了PHP异步信号处理函数pcntl_async_signals() 来处理阻塞问题。在php7之前信号处理方式有2种,第一种是基于ticks来每执行一行代码来触发执行信号监听,第二种是直接while(true){  //监听信号 }第一种方式如果某行的代码阻塞时间较长会影响...

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....

在MyISAM引擎中使用事务会怎样

在MyISAM引擎中使用事务会怎样

众所周知MyISAM引擎不支持事务,但是我只是知道不支持事务,并未测试具体的表现是什么,测试代码如下:try {     //开启事务     Db::startTrans();    &...

php通过event扩展创建定时器,php毫秒级定时器

php通过event扩展创建定时器,php毫秒级定时器

PHP简单定时器可以通过pcntl_signal创建闹钟信号来实现。但是缺点很明显,性能一般,要自己实现守护进程,不支持毫秒级定时器,单进程不支持多个闹钟信号,不能跨平台运行event扩展支持的事件多,性能高。<?php //创建event配置.[空配置] $eventConfig ...