Home  >  Article  >  Backend Development  >  How to process images using PHP built-in functions?

How to process images using PHP built-in functions?

WBOY
WBOYOriginal
2024-04-22 12:15:02578browse

PHP built-in functions provide convenient image processing functions, which can realize image scaling, cropping, adding watermarks and other operations. Use imagecopyresampled() to resize the image, imagecrop() to crop the image, and imagecopymerge() to add a watermark.

如何使用 PHP 内置函数处理图像?

How to use PHP built-in functions to process images

PHP provides a wealth of built-in functions for image processing, allowing you to operate images conveniently and quickly. This article will introduce how to use these functions to perform common operations on images, including scaling, cropping, adding watermarks, etc. The following content includes actual case code.

Scale the image

imagecopyresampled() The function can scale the image:

<?php
$src_image = 'image.jpg';
$dst_image = 'image-scaled.jpg';
$scaled_width = 300;
$scaled_height = 200;

$src = imagecreatefromjpeg($src_image);
$dst = imagecreatetruecolor($scaled_width, $scaled_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $scaled_width, $scaled_height, imagesx($src), imagesy($src));
imagejpeg($dst, $dst_image);
?>

Crop the image

imagecrop() Function can crop the image:

<?php
$src_image = 'image.jpg';
$dst_image = 'image-cropped.jpg';
$crop_x = 100;
$crop_y = 200;
$crop_width = 300;
$crop_height = 200;

$src = imagecreatefromjpeg($src_image);
$dst = imagecrop($src, ['x' => $crop_x, 'y' => $crop_y, 'width' => $crop_width, 'height' => $crop_height]);
imagejpeg($dst, $dst_image);
?>

Add watermark

imagecopymerge() Function Watermark can be added:

<?php
$main_image = 'image.jpg';
$watermark_image = 'watermark.png';
$output_image = 'image-with-watermark.jpg';
$margin = 50;

$main = imagecreatefromjpeg($main_image);
$watermark = imagecreatefrompng($watermark_image);

$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);

$dst_x = imagesx($main) - $margin - $watermark_width;
$dst_y = imagesy($main) - $margin - $watermark_height;

imagecopymerge($main, $watermark, $dst_x, $dst_y, 0, 0, $watermark_width, $watermark_height, 75);
imagejpeg($main, $output_image);
?>

The above is the detailed content of How to process images using PHP built-in functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn