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

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

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

之前用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可变变量的作用

<!doctype html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <bod...

PHP session和cookie的关联

PHP session和cookie的关联

先看看下面的代码:<?php session_start(); $_SESSION['username']='lucy'; ?>当我们请求访问上面的脚本,默认会在我们的客户端生成一个名为PHPSESSID的cookie,我这里的值是PHPSESSID=...

php 数组转换xml,php 数组转成xml,php数组转xml 函数

php 数组转换xml,php 数组转成xml,php数组转xml 函数

源码:特别适用于微信支付中通知微信支付网关function array2xml($arr, $level = 1) { $s = $level == 1 ? "<xml&g...

php上传大文件,php大文件上传

php上传大文件,php大文件上传

(1).前端文件:<form action="upload.php" method="post" enctype="multipart/form-data">    &...

全方位认识PHP的SESSION

全方位认识PHP的SESSION

【一】.介绍session由于HTTP是无状态的请求,创建一个会话需要保持必须需要身份标识。当用户第一次访问,PHP会为用户创建一个唯一的sessionid,并将sessionid通过cookie发送给浏览器,并在服务器的临时文件创建一个以sessionid为名的文件用来保存这个sessionid保...

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