SoFunction
Updated on 2025-03-04

Detailed explanation of the method of PHP to implement picture rotation

Recently, there is a requirement to rotate the image uploaded from the front end by 90° counterclockwise. This mainly requires the imagerotate method of php to rotate the image. The specific implementation method is as follows:

<?php
 
namespace common\traits;
 
use Yii;
use yii\helpers\FileHelper;
 
/**
  * Image rotation processing trait
  *
  * @author wangjian
  * @since 1.0
  */
class ImageRotate
{
 
    /**
      * base64 picture rotation
      * @param $image Base64 image that needs to be rotated
      * @param string $rotate Counterclockwise rotation angle
      * @param false $savePath The saved image path, false returns base64 format
      */
    public static function base64Rotate($image, $rotate = '90', $savePath = false)
    {
        if (empty($image)) {
            return false;
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {
            $type = $result[2];
            //Set temporary directory            $temporaryPath = '/tmp/';
            $temporaryPath = dirname(Yii::getAlias('@common')) . '/web' . $temporaryPath;
            FileHelper::createDirectory($temporaryPath);
 
            //Save the original image to the snack directory            $temporaryImage = date('YmdHis') . rand(1000, 9999) . '.' . $type;
            if (file_put_contents($temporaryPath . $temporaryImage, base64_decode(str_replace($result[1], '', $image)))) {
                $newImage = self::rotateImage($temporaryPath . $temporaryImage, $rotate); //Rotate the picture                //Delete temporary files                @unlink($temporaryPath . $temporaryImage);
 
                ob_start();
                if ($savePath === false) { //Return to base                    imagepng($newImage);
                    $imageString = $result[1] . base64_encode(ob_get_contents());
                    @unlink($newImage);
                } else {
                    $imageString = imagepng($newImage, $savePath);
                }
                ob_end_clean();
 
                return $imageString;
            }
        }
 
        return false;
    }
 
    /**
      * Local image rotation
      * @param $image Local image that needs to be rotated
      * @param string $rotate Counterclockwise rotation angle
      * @param false $savePath The saved image path, false returns to replace the original image
      */
    public static function imageRotate($image, $rotate = '90', $savePath = false)
    {
        if (empty($image)) {
            return false;
        }
        //Rotate the picture        $newImage = self::rotateImage($image, $rotate);
        ob_start();
        if ($savePath === false) {
            //Replace the original image            $url = $image;
        } else {
            $url = $savePath;
        }
        $imageString = imagepng($newImage, $url);
        ob_end_clean();
        return $imageString;
    }
 
    /**
      * @param $file Image that needs to be rotated
      * @param $rotate Counterclockwise rotation angle
      */
    private static function rotateImage($file, $rotate)
    {
        $imageSize = getimagesize($file);
        $imageSize = explode('/', $imageSize['mime']);
        $type = $imageSize[1];
 
        switch ($type) {
            case "png":
                $image = imagecreatefrompng($file);
                break;
            case "jpeg":
                $image = imagecreatefromjpeg($file);
                break;
            case "jpg":
                $image = imagecreatefromjpeg($file);
                break;
            case "gif":
                $image = imagecreatefromgif($file);
                break;
        }
        $rotateImage = imagerotate($image, $rotate, 0); //Rotate counterclockwise        //Get the width and height after rotation        $srcWidth = imagesx($rotateImage);
        $srcHeight = imagesy($rotateImage);
        //Create a new picture        $newImage = imagecreatetruecolor($srcWidth, $srcHeight);
        //Assign color + alpha, fill the color onto the new picture        $alpha = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
        imagefill($newImage, 0, 0, $alpha);
        //Copy the source image to the new image and set the complete alpha channel information to save the PNG image        imagecopyresampled($newImage, $rotateImage, 0, 0, 0, 0, $srcWidth, $srcHeight, $srcWidth, $srcHeight);
        imagesavealpha($newImage, true);
 
        return $newImage;
    }
 
}

Specific use:

1: base64 picture rotates and outputs base64

ImageRotate::base64Rotate('base64 pictures', 'Rotation angle');

2: base64 image rotate and save

ImageRotate::base64Rotate('base64 pictures', 'Rotation angle', 'Save Address');

3: Local image rotation

ImageRotate::imageRotate('Local image address', 'Rotation angle', 'Save Address');

According to the above method, we can realize the rotation function of the picture

This is the end of this article about the detailed explanation of the method of PHP to achieve image rotation. For more related PHP image rotation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!