2014-10-09 56 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