2012-02-26 54 views
10
$image_p = imagecreatetruecolor($new_width, $new_height); 
$image = imagecreatefromjpeg($filename); 
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

如何保存調整後的圖像文件夾/? 如何檢測圖像類型是jpg/png/gif?PHP保存圖像imagecopyresampled

回答

12

將圖像保存到一個文件,你可以使用任何的這些:imagejpeg()imagepng()imagegif(),具體取決於您所需的輸出格式。

要檢測圖像類型,你可以檢查文件的擴展名,並根據自己的情況。但是,有時人們會手動更改圖像文件的擴展名,認爲實際上會更改圖像類型,因此檢查imagecreatefrom是否返回圖像資源而非false是個好主意。

對於一個快速的方法來恢復文件的只是擴展:您應用imagecopyresampled()

$ext = pathinfo($path_to_file, PATHINFO_EXTENSION); 

Manual entry on pathinfo()

4

實例添加以下代碼

imagepng($iOut,'pic/mypic.png',3); 

&此代碼從外部來源取得你的照片格式

$link='http://example.com/example.png'; 
echo (substr ($link,strrpos ($link,".")+1)); 
1
$filename = 'path/to/original/file.xxx'; // where xxx is file type (jpg, gif, or png) 
$newfilename = 'path/to/resized/file.xxx'; // where xxx is file type (jpg, gif, or png) 
$path_parts = pathinfo($filename); 
if ($path_parts['extension'] == 'jpg') { 
    $image_p = imagecreatetruecolor($new_width, $new_height); 
    $image = imagecreatefromjpeg($filename); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    imagejpeg($image_p, $newfilename); 
} elseif ($path_parts['extension'] == 'gif') { 
    $image_p = imagecreatetruecolor($new_width, $new_height); 
    $image = imagecreatefromgif($filename); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    imagegif($image_p, $newfilename); 
} elseif ($path_parts['extension'] == 'png') { 
    $image_p = imagecreatetruecolor($new_width, $new_height); 
    $image = imagecreatefrompng($filename); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    imagepng($image_p, $newfilename); 
} else { 
     echo "Source file is not a supported image file type."; 
} 
+0

其工作的罰款只是創造與發行PNG文件作爲再生文件必須是透明的。如何做到這一點。 – 2018-02-03 05:31:41

3

後,$dst_image將是你的圖像資源標識符。

僅應用imagecopyresampled()函數不會自動將其保存到文件系統。

所以,你需要保存它,使用的功能imagejpeg()之一,imagepng()

// Output 
imagejpeg($dst_image, 'new-image.jpg', 100);