當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP imagepng()用法及代碼示例

imagepng()函數是PHP中的內置函數,用於向瀏覽器或文件顯示圖像。此函數的主要用途是在瀏覽器中查看圖像,將任何其他圖像類型轉換為PNG並將過濾器應用於圖像。

用法:

bool imagepng( resource $image, int $to, int $quality, int $filters)

參數:此函數接受上述和以下所述的三個參數:


  • $image:它指定要處理的圖像資源。
  • $to (Optional):它指定將文件保存到的路徑。
  • $quality (Optional):它指定圖像的質量。
  • $filters (Optional):它指定要應用於圖像的過濾器,有助於減小圖像尺寸。

返回值:如果成功,此函數將返回TRUE,否則將返回FALSE。

以下示例說明了PHP中的imagepng()函數:

範例1:在此示例中,我們將在瀏覽器中查看圖像。

<?php 
  
// Load an image from PNG URL 
$im = imagecreatefrompng( 
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); 
  
// View the loaded image in browser using imagepng() function 
header('Content-type:image/png');   
imagepng($im); 
imagedestroy($im); 
?>

輸出:

範例2:在此示例中,我們將JPEG轉換為PNG。

<?php 
  
// Load an image from JPEG URL 
$im = imagecreatefromjpeg( 
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); 
  
// Convert the image into PNG using imagepng() function 
imagepng($im, 'converted.png'); 
imagedestroy($im); 
?>

輸出:

This will save the PNG version of image in the same folder where your PHP script is.

程序3:在此示例中,我們將使用過濾器。

<?php 
  
// Create an image instance 
$im = imagecreatefrompng( 
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png'); 
  
// Save the image as image1.png 
imagepng($im, 'image1.png'); 
  
// Save the image as image2.png with all filters to disable size compression 
imagepng($im, 'image2.png', null, PNG_ALL_FILTERS); 
  
imagedestroy($im); 
?>

輸出:

This will save the image1.png as compressed and image2.png as uncompressed image

參考: https://www.php.net/manual/en/function.imagepng.php



相關用法


注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | imagepng() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。