php将多张图片拼成一张图,首张大图
文章标签:
php
$dir = __DIR__ . '/'; //图片文件夹位置
$percent = 0.75; //各个小图的比例 4:3
$files = array();
$width = 1000; //新图的宽度
$height = 0;
$colCount = 3; //每行多少个图
$space = 4; //图间隙
foreach (scandir($dir) as $value) {
if (preg_match('/\.jpg$/', $value)){
$file = $dir . $value;
$files[] = array(
'path' => $file,
'size' => getimagesize($file)
);
$index = count($files);
if ($index == 1){
$height = $width * $percent;
$height += $space;
}
}
}
//额外在最后加一张图
$lastImg = dirname(__DIR__) . '/10.jpg';
$files[] = array(
'path' => $lastImg,
'size' => getimagesize($lastImg)
);
$count = count($files);
$rowCount = (int)(($count - 1) / $colCount);
$rowChildWidth = ($width - (($colCount - 1) * $space)) / $colCount;
$rowHeight = $rowChildWidth * $percent;
$height += $rowHeight * $rowCount + $space * $rowCount - 1;
$newImage = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $white);
$y = 0;
foreach ($files as $key => $value) {
$imgSrc = imagecreatefromjpeg($value['path']);
if ($key == 0){
$x = 0;
$w = $width;
$h = $width * $percent;
}else{
$w = $rowChildWidth;
$h = $rowHeight;
$row1 = $key - 1 == 0 || ($key - 1) % 3 == 0;
$row2 = $key == 2 || ($key + 1) % 3 == 0;
$row3 = $key % 3 == 0;
if ($row1) {
$x = 0;
}elseif ($row2) {
$x = $rowChildWidth + $space;
}elseif ($row3) {
$x = $rowChildWidth * 2 + $space * 2;
}
}
imagecopyresampled($newImage, $imgSrc, $x, $y, 0, 0, $w, $h, $value['size'][0], $value['size'][1]);
if ($key == 0 || $row3){
$y += $h + $space;
}
}
header("Content-type: image/png");
// imagejpeg($newImage, '0.jpg'); //保存新图到文件
imagepng($newImage);
imagedestroy($newImage);

登录后可发表评论
点击登录