2

我正在创建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

4

2 回答 2

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 变量作为参数,因此它返回空白图像(或 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);
于 2014-10-09T14:17:35.620 回答
0

试试这个,它对我有用

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

imagecopyresampled 的参考

于 2014-10-09T14:07:15.377 回答