Last active
September 16, 2024 21:36
-
-
Save aklump/b7bd92ede958ff6120df48d5a3b5844d to your computer and use it in GitHub Desktop.
Invokable class to rotate an image data URI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use InvalidArgumentException; | |
/** | |
* Rotate an image DataURI string. | |
* | |
* Because I'm working with a string, not a file, the Drupal image API | |
* (image.factory) didn't seem to be an appropriate solution, therefor I'm using | |
* the native PHP GD library. | |
*/ | |
class RotateImageDataURI { | |
/** | |
* @param string $data_uri A data:image/*;base64... image string. | |
* @param float $degrees Note that -90 turns clockwise. | |
* | |
* @return void | |
*/ | |
public function __invoke(string &$data_uri, float $degrees): void { | |
if (!$degrees) { | |
return; | |
} | |
$uri_parts = explode(',', $data_uri); | |
$imageData = base64_decode($uri_parts[1]); | |
$sourceImage = imagecreatefromstring($imageData); | |
$image_resource = imagerotate($sourceImage, $degrees, 0); | |
ob_start(); | |
$mime = $this->getMimeType($data_uri); | |
$this->echoImage($mime, $image_resource); | |
$raw_image_stream = ob_get_clean(); | |
$data_uri = 'data:image/png;base64,' . base64_encode($raw_image_stream); | |
} | |
private function echoImage(string $mime, $image_resource): void { | |
switch ($mime) { | |
case 'image/jpeg': | |
imagejpeg($image_resource); | |
break; | |
case 'image/png': | |
imagepng($image_resource); | |
break; | |
case 'image/gif': | |
imagegif($image_resource); | |
break; | |
default: | |
throw new InvalidArgumentException('Unsupported image type.'); | |
} | |
} | |
private function getMimeType(string $data_uri): string { | |
preg_match('#data:(.+?);#', $data_uri, $matches); | |
return $matches[1] ?? ''; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment