2016-01-21 102 views
1

編輯:請忘掉這個問題!我在原始代碼中犯了一個愚蠢的錯誤。 示例代碼按預期工作!旋轉和裁剪圖像批處理

我想旋轉和裁剪圖像。 我有這個至今:

$w = 100; 
$h = 400; 
$img1 = imagecreatefromjpeg('image1.jpg'); 
$img2 = imagecreatefromjpeg('image2.jpg'); 
for ($i = 0; $i < 2; $i++) { 
    ${'img'.$i + 3} = imagecreatetruecolor($h, $h); 
    imagecopy(${'img'.$i + 3}, ${'img'.$i + 1}, 0, 0, 0, 0, $w, $h); 
    ${'img'.$i + 3} = imagerotate(${'img'.$i + 3}, 90, 0); 
    ${'img'.$i + 3} = imagecrop(${'img'.$i + 3}, array(0, 0, $h, $w)); 
    imagejpeg(${'img'.$i + 3}); 
    imagedestroy(${'img'.$i + 3}); 
    imagedestroy(${'img'.$i + 1}); 
} 

所以我基本上做的是開放的一些JPG格式,創造新的圖像,JPG文件複製到新的圖像,然後裁剪圖像。

唉這導致空圖片...

我在做什麼錯?

+0

和你得到的日誌中的錯誤? – RamRaider

+0

不,沒有... – Dick

回答

0

不知道這是否會對缺乏輸出產生影響 - 但是$img1 & $img2是做什麼的 - 它們沒有被使用,據我所知,

@error_reporting(E_ALL); 
$w = 100; 
$h = 400; 

$img1 = imagecreatefromjpeg('image1.jpg'); 
$img2 = imagecreatefromjpeg('image2.jpg'); 

for ($i = 0; $i < 3; $i++) { 

     $new=${'img'.$i + 3}; 
     $src=${'img'.$i + 1}; 


    $new = imagecreatetruecolor($h, $h); 
    imagecopy($new, $src, 0, 0, 0, 0, $w, $h); 

    $new = imagerotate($new, 90, 0); 
    $new = imagecrop($new, array(0, 0, $h, $w)); 

    imagejpeg($new); 

    imagedestroy($new); 
    imagedestroy($src); 

    break;/* just to see if it gets this far*/ 
} 
+0

謝謝,但它是我在我寫的原始代碼中犯的一個錯誤...順便說一句:就像你對'$ img1'和'$ img2'的問題的評論,這些被引用'$ src = $ {'img'。$ i + 1};'。 – Dick

0

首先,您應該考慮使用image copy resampled以獲得更高質量的結果。

然後,您需要正確使用imagejpeg函數,目前您只需簡單地加載JPG並直接輸出它們,這可能是您想要的,但您處於循環狀態,並且無法直接循環加載多個圖像到同一個文件。這也意味着你看到的圖像(或不是)是該集合中的最終圖像。

你的問題是你的for循環運行了三次,但你只有與前兩個實例相關的數據,但第三個實例是空的,因爲這是最近的這是唯一的實例輸出到瀏覽器。

所以:

1)除非你有imagejpeg($data,$filename);生成的圖像。您可以將文件名定義爲$filename = $img+3.".jpg";或類似文件。

2)如果您使用數組而不是數字增加的變量,那麼調試和讀取代碼也會容易得多,這是編寫代碼的非常混亂的方式!

3)如果你直接要輸出的圖像瀏覽器,你需要PHP之前如header('Content-Type: image/jpeg');提供一個頭輸出的imagejpeg內容。


代碼的老調重彈:

$w = 100; 
$h = 400; 
$img[1] = imagecreatefromjpeg('image1.jpg'); 
$img[2] = imagecreatefromjpeg('image2.jpg'); 
for ($i = 3; $i < 5; $i++) { 
    $img[$i] = imagecreatetruecolor($h, $h); 
    $j = $i -2; 
    imagecopyresampled($img[$i], $img[$j], 0, 0, 0, 0, $h, $h, $w, $h,); 
    // this function also contains destination width and destination 
    // height, which are equal to the size of the destination image so 
    // are set as $h, $h in the function above. 
    $img[$i] = imagerotate($img[$i], 90, 0); 
    $img[$i] = imagecrop($img[$i], array(0, 0, $h, $w)); 
    $filename = "image-".$i.".jpg"; 
    imagejpeg($img[$i], $filename); 
    imagedestroy($img[$i]); 
    imagedestroy($img[$j]); 
} 
+0

我真的很慚愧,我在原始代碼中犯了一個錯誤:(我粘貼的代碼在這個例子中被簡化了,所以當我試着運行它時,無論如何,感謝使用這個數組的提示,這真的很整潔。 – Dick