How to rotate images and keep padding using PHP and OpenCV libraries
Abstract:
In image processing, image rotation is a common operation. This article will introduce how to use PHP and OpenCV libraries to achieve image rotation and keep padding. We will use PHP's image processing extension library GD and OpenCV's PHP extension library to implement this function. The article will provide detailed code examples to help readers understand and practice.
Preparation
Before we begin, we need to ensure that we have installed the PHP image processing extension library GD and the OpenCV PHP extension library. If not installed, you can install them according to the following command:
sudo apt-get install php7.4-gd sudo apt-get install php7.4-opencv
<?php // 加载OpenCV库 if (!extension_loaded('opencv')) { dl('opencv.' . PHP_SHLIB_SUFFIX); } // 加载源图像 $srcImage = imagecreatefromjpeg('input.jpg'); // 源图像的宽度和高度 $srcWidth = imagesx($srcImage); $srcHeight = imagesy($srcImage); // 创建一个新的图像对象,大小为旋转后的图像大小 $newWidth = $srcHeight; // 宽度等于高度 $newHeight = $srcWidth; // 高度等于宽度 $dstImage = imagecreatetruecolor($newWidth, $newHeight); // 旋转图像 $angle = 90; // 旋转角度 $bgColor = imagecolorallocate($dstImage, 255, 255, 255); // 填补颜色为白色 $dstImage = imagerotate($srcImage, $angle, $bgColor); // 保存旋转后的图像 imagejpeg($dstImage, 'output.jpg'); ?>
The above code will load an image from a source image named input.jpg
and create a new image object with the size of the rotated image. The algorithm rotates the image 90 degrees and fills it with white. Finally, save the rotated image as output.jpg
.
Through the study and practice of this article, readers will be able to better understand and apply PHP and OpenCV libraries to rotate images and maintain filling methods. I hope this article will be helpful to readers in their study and application in the field of image processing.
The above is the detailed content of How to rotate images and keep padding using PHP and OpenCV libraries. For more information, please follow other related articles on the PHP Chinese website!