我正在使用Imagemagik的PHP扩展来处理一些图像。在我的代码中,我试图将变量$j的值增加1;请注意$j在第二个循环迭代中起作用。我不知道把$j++放在哪里;在我的代码范围内;它似乎并没有像我最后所说的那样增加,默认为其初始的"0"零值。
first iteration we do not need $j;
second iteration $j is assigned 0;
third iteration $j needs to be increased by 1 or $j = 1
... loop continues
$dst = "tem891";
$over = new Imagick();
$over->readImage(DOCROOT . '/' . $dst . '/middle.png');
$images = glob(DOCROOT . '/' . $dst . "/line-*.png");
sort($images, SORT_NATURAL | SORT_FLAG_CASE);
$count = count($images);
$height = (720 - $over->getImageHeight()) / 2;
$width = (640 - $over->getImageWidth()) / 2;
$j = '';
for ($i = 0; $i < $count; $i++) {
if ($i == 0) {
$base = new Imagick();
$base->newImage(640, 720, new ImagickPixel('transparent'));
} else {
$j = 0;
$base = new Imagick();
$base->readImage(DOCROOT . '/composite-' . $j . '.png');
}
$top = new Imagick();
$top->readImage($images[$i]);
$base->compositeImage($top, Imagick::COMPOSITE_DEFAULT, $width, $height);
$base->writeImage(DOCROOT . '/composite-' . $i . '.png');
$height += $top->getImageHeight();
}
在代码中,从第二次迭代开始,对于所有后续迭代,都会运行行$j = 0;
,因此$j将保持在0。
我建议您在循环之前或在if($i==0){}
子句中初始化$j=0,并在else{}子句末尾递增:
[...]
$width = (640 - $over->getImageWidth()) / 2;
$j = 0;
for ($i = 0; $i < $count; $i++) {
if ($i == 0) {
$base = new Imagick();
$base->newImage(640, 720, new ImagickPixel('transparent'));
} else {
$base = new Imagick();
$base->readImage(DOCROOT . '/composite-' . $j . '.png');
$j++;
}
$top = new Imagick();
$top->readImage($images[$i]);
$base->compositeImage($top, Imagick::COMPOSITE_DEFAULT, $width, $height);
$base->writeImage(DOCROOT . '/composite-' . $i . '.png');
$height += $top->getImageHeight();
}
在for循环之前初始化变量j,将其设置为0。
$j = 0
for ($i = 0; $i < $count; $i++) {
if (==> put your condition here) {
$j++;
}
....
}
在for循环中,您可以公式化您希望j增加的条件(例如,在每二次迭代中,而不是在第一次迭代期间,仅在前10次迭代中…)