How to process images using PHP built-in functions?

WBOY
Release: 2024-04-22 12:15:02
Original
625 people have browsed it

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);
?>
Copy after login

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);
?>
Copy after login

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);
?>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template