2014-10-09 135 views
2

我正在創建各種格式(jpg, png)myImage的縮略圖。這裏是我的代碼imagepng不起作用,它創建一個空白圖像和圖像不壓縮

<?php 
error_reporting(E_ALL); 
//$file = 'H:/xampp/htdocs/myfolder/new.jpg'; 
$file = 'H:/xampp/htdocs/myfolder/phool.png'; 
$pathToSave = 'H:/xampp/myfolder/New/'; 
$sourceWidth =60; 
$sourceHeight = 60; 
$what = getimagesize($file); 
$file_name = basename($file); 
//print "MIME ".$what['mime']; 
switch(strtolower($what['mime'])) 
{ 
    case 'image/png': 
      $img = imagecreatefrompng($file); 
      $img = imagecreatefromstring($img); 
      $new = imagecreatetruecolor($what[0],$what[1]); 
      imagecopy($new,$img,0,0,0,0,$what[0],$what[1]); 
      header('Content-Type: image/png'); 
      imagepng($new,$pathToSave.$file_name); 
      imagedestroy($new); 
     break; 
    case 'image/jpeg': 
      $img = imagecreatefromjpeg($file); 
      $new = imagecreatetruecolor($what[0],$what[1]); 
      imagecopy($new,$img,0,0,0,0,$what[0],$what[1]); 
      header('Content-Type: image/jpeg'); 
      imagejpeg($new,$pathToSave.$file_name); 
      imagedestroy($new); 
     break; 
    case 'image/gif': 
     $img = imagecreatefromgif($file); 
     break; 
    default: die(); 
} 

但是,它不工作PNG images.It保存在我的目的地$pathToSave = 'H:/xampp/htdocs/myfolder/New/'空白圖像。

如果我刪除$img = imagecreatefromstring($img);然後imagepng保存圖像,但不會像imagejpg那樣壓縮圖像。

+0

只是儘量不使用'$ IMG = imagecreatefromstring($ IMG);' – 2014-10-09 14:00:31

+0

善於觀察,但如果我刪除,它只是保存原始圖像,它不會在這裏進行壓縮 – Hitesh 2014-10-09 14:05:10

+0

你的意思原始圖像?你的文件'phool.png'所以它可能是相同的圖像 – 2014-10-09 14:12:37

回答

1
$img = imagecreatefrompng($file); //Creates an image from a png file 
$img = imagecreatefromstring($img); //Creates an image from a string 

Basicly您使用imagecreatefrompng($文件)在內存中創建的圖像,但然後您覆蓋使用imagecreatefromstring相同的變量($ img),它不會將GDImage變量作爲參數,所以它返回一個空白圖像(或null?)。

只需刪除imagecreatefromstring($ img);它會工作。

$newImage = imagecreatetruecolor($newwidth, $newheight); 
$source = imagecreatefrompng($fileurl); 
imagecopyresized($newImage, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
imagepng($newImage,$fileurl); 
imagedestroy($newImage); 
imagedestroy($source); 
+0

感謝您的回答 – Hitesh 2014-10-09 17:50:36

+0

你能否請嘗試下載一些更高分辨率的PNG圖像,並在我的本地複製我的代碼...並嘗試做你在給我解釋的東西這裏。我正在嘗試這個,但它保存了相同的原始圖像,並沒有使它變小圖像....因爲它適用於'image/jpeg' – Hitesh 2014-10-09 17:57:30

+0

試試這張圖片http://upload.wikimedia.org/wikipedia/commons /e/e6/Bosje_bloemen.png – Hitesh 2014-10-09 17:59:44

0

試試這個,它正在向我

$img = imagecreatefrompng($file); 
$new = imagecreatetruecolor($what[0],$what[1]); 
imagecopyresampled($new, $img, 0,0,0,0,$what[0],$what[1]); 

reference for imagecopyresampled

+0

它給我一個空白圖片 – Hitesh 2014-10-09 14:11:04