imagejpeg()函数是PHP中的内置函数,用于向浏览器或文件显示图像。此功能的主要用途是在浏览器中查看图像,将任何其他图像类型转换为JPEG并更改图像质量。
用法:
bool imagejpeg( resource $image, int $to, int $quality )
参数:此函数接受上述和以下所述的三个参数:
$image:它指定要处理的图像资源。
$to (Optional):它指定将文件保存到的路径。
$quality (Optional):它指定图像的质量。
返回值:如果成功,此函数将返回TRUE,否则将返回FALSE。
以下示例说明了PHP中的imagejpeg()函数:
范例1:在此示例中,我们将在浏览器中查看图像。
// Load an image from jpeg URL
$im = imagecreatefromjpeg(
'https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg');
// View the loaded image in browser using imagejpeg() function
header('Content-type:image/jpg');
imagejpeg($im);
imagedestroy($im);
?>
输出:
范例2:在此示例中,我们将PNG转换为JPEG。
// Load an image from PNG URL
$im = imagecreatefrompng(
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png');
// Convert the image into JPEG using imagejpeg() function
imagejpeg($im, 'converted.jpg');
imagedestroy($im);
?>
输出:
This will save the JPEG version of image
in the same folder where your PHP script is.
范例3:在此示例中,我们将更改图像的质量。
// Load an image from jpeg URL
$im = imagecreatefromjpeg(
'https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg');
// View the loaded image in browser using imagejpeg() function
header('Content-type:image/jpg');
// Decrease the quality of image to 2
imagejpeg($im, null, 2);
imagedestroy($im);
?>
输出: