2015-11-17 34 views
0

我使用Imagemagick的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(); 


} 
+0

删除$ J = 0;并且在for循环之前做$ j = 0的$ j =''的instad。然后在$ base-> readImage行之后添加$ j ++; – sinaza

回答

1

在您的代码中,从第二次迭代开始,对于所有后续迭代,行$j = 0;已运行,因此$ j将保持为0。

我建议你初始化$ J = 0或者循环之前或if($i==0){}子句中和在其他{}子句结尾加一:

[...] 
$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(); 


} 
0

前初始化变量j的循环将其设置为0。

$j = 0 
for ($i = 0; $i < $count; $i++) { 

    if (==> put your condition here) { 
     $j++; 
    } 
.... 
} 

在for循环中,那么你可以制定什么都调理你想J可提高(例如每秒迭代,而不是在第一次迭代期间,仅在前10次迭代中,...)