imagepng不工作,它会创建一个空白图像,图像不会压缩

时间:2014-10-09 13:53:07

标签: php image thumbnails imagecreatefrompng

我正在制作各种格式myImage (jpg, png)的缩略图。这是我的代码

<?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图像。它会在我的目的地$pathToSave = 'H:/xampp/htdocs/myfolder/New/'中保存一张空白图片。

如果我删除了$img = imagecreatefromstring($img);,那么imagepng会按原样保存图片,但不会像imagejpg那样压缩图片。

2 个答案:

答案 0 :(得分:1)

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

基本上你是使用imagecreatefrompng($ file)在内存中创建一个图像,但是你使用imagecreatefromstring($ img)覆盖相同的变量,它不会将GDImage变量作为参数,所以它返回一个空白图像(或者为空? )。

只需删除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);

答案 1 :(得分:0)

试试这个,它对我有用

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

reference for imagecopyresampled