发布作者: 笒鬼鬼
百度收录: 正在检测是否收录...
作品采用: 《 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 》许可协议授权
<?php
// 示例:输出圆形图片
header('Content-Type: image/png');
echo getimg("https://q.qlogo.cn/headimg_dl?dst_uin=778713968&spec=640", 300);
// 制作圆形图片
function getimg($imageUrl, $size)
{
// 创建画布
$canvasSize = 1000; // 处理时的图片尺寸
$canvas = imagecreatetruecolor($canvasSize, $canvasSize);
// 设置透明背景
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
$transparentColor = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
imagefilledrectangle($canvas, 0, 0, $canvasSize, $canvasSize, $transparentColor);
// 加载原始图片
$sourceImage = imagecreatefromjpeg($imageUrl);
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);
// 放大图片
$enlargedWidth = $sourceWidth * 1.5;
$enlargedHeight = $sourceHeight * 1.5;
$enlargedImage = imagecreatetruecolor($enlargedWidth, $enlargedHeight);
imagecopyresampled($enlargedImage, $sourceImage, 0, 0, 0, 0, $enlargedWidth, $enlargedHeight, $sourceWidth, $sourceHeight);
// 计算裁剪为圆形的半径
$radius = $canvasSize / 2;
// 裁剪为圆形
for ($x = 0; $x < $canvasSize; $x++) {
for ($y = 0; $y < $canvasSize; $y++) {
$dx = $x - $radius;
$dy = $y - $radius;
$distance = sqrt($dx * $dx + $dy * $dy);
if ($distance < $radius) {
// 在圆内部
imagesetpixel($canvas, $x, $y, imagecolorat($enlargedImage, $enlargedWidth / $canvasSize * $x, $enlargedHeight / $canvasSize * $y));
}
}
}
// 输出的图片尺寸
$end = imagecreatetruecolor($size, $size);
imagesavealpha($end, true);
$transparency = imagecolorallocatealpha($end, 0, 0, 0, 127);
imagefill($end, 0, 0, $transparency);
imagealphablending($end, false);
imagesavealpha($end, true);
imagecopyresampled($end, $canvas, 0, 0, 0, 0, $size, $size, $canvasSize, $canvasSize);
imagepng($end);
// 释放资源
imagedestroy($canvas);
imagedestroy($sourceImage);
imagedestroy($enlargedImage);
imagedestroy($end);
}
—— 评论区 ——