PHP图片拼接组合为大图
效果
代码
<?php
class img{
// 原图宽
public $width = 900;
// 原图高
public $height = 1280;
// 缩小后宽
public $new_width = 360;
// 缩小后高
public $new_height = 512;
// 多少列
public $wNum = 10;
// 多少行
public $hNum = 10;
// 图片源文件夹
public $dir ='E:/work/pyhton/nft-create-master/Generate-NFT/output/edition EPX/images/';
// 合成后图片保存路径
public $saveName = './2.jpg';
public function __construct($wNum,$hNum)
{
ini_set('memory_limit', '-1');
$this->wNum = $wNum;
$this->hNum = $hNum;
}
public function start()
{
$this->img();
}
// 图片名称组合
private function bw($num)
{
$step = 5;
$n = strlen($num.'');
for($i=1;$i<=($step-$n);$i++)
{
$num = '0'.$num;
}
return $num;
}
private function img()
{
$width = $this->width;
$height = $this->height;
$new_width = $this->new_width;
$new_height = $this->new_height;
$wNum = $this->wNum;
$hNum = $this->hNum;
// 创建大图
$iOut = imagecreatetruecolor($new_width*$wNum, $new_height*$hNum);
$setp = 0;
// 合成图片总数
$imgCount = $wNum*$hNum;
$xsetp = 0;
$isArray = [];
while(true)
{
$i = mt_rand(0,100000);
$img_name = $this->bw($i);
$dir = $this->dir.$img_name.'.png';
// 文件存在
// 且图片不存在于数组,去重 保证每张图片只出现一次
if(is_file($dir) && !in_array($i,$isArray))
{
$isArray[] = $i;
if($xsetp == $wNum) $xsetp = 0;
// 行
$hang = ($setp+1) >= $wNum ?(floor($setp/$wNum)+1):1;
$oX = $new_width*$xsetp;
$oY = ($hang-1)*$new_height;
$img = imagecreatefrompng($dir);
// 缩小图片尺寸
$image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// 将合成图片拷贝到大图
imagecopy($iOut, $image_p, $oX, $oY, 0, 0, $new_width, $new_height);
$setp++;
$xsetp++;
echo '第'.$hang.'行,第'.$xsetp.'列'.PHP_EOL;
}
if($setp > ($imgCount-1)){
echo $setp.PHP_EOL;
break;
}
}
// 保存大图
imagejpeg($iOut,$this->saveName);
}
}
// 40列 12行
$img = new img(40,12);
// // 原图宽
// $img->width = 900;
// // 原图高
// $img->height = 1280;
// // 缩小后宽
// $img->new_width = 360;
// // 缩小后高
// $img->new_height = 512;
// // 图片源文件夹
// $img->dir ='E:/work/pyhton/nft-create-master/Generate-NFT/output/edition EPX/images/';
// $img->saveName = './img/'.microtime().mt_rand(1000,99999).'.jpg';
$img->start();
?>