Created
November 22, 2014 08:52
-
-
Save dljoseph/9d535d9a2ae6e849904a to your computer and use it in GitHub Desktop.
SilverStripe 3.1.x Auto-rotate mobile images on upload according to EXIF Orientation data
This file contains 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 | |
/** | |
* Image Extension | |
*/ | |
class ImageExtension extends DataExtension { | |
// Rotated Image - | |
// Some mobile image when uploaded will appear correctly oriented on mobile devices, but when | |
// viewed on a desktop will appear oriented the wrong way up. | |
public function RotatedImage($angle) { | |
return $this->owner->getFormattedImage('RotatedImage', $angle); | |
} | |
public function generateRotatedImage(GD $gd, $angle) { | |
return $gd->rotate($angle); | |
} | |
/** | |
* Mobile image correction | |
*/ | |
public function onAfterUpload() { | |
$self = $this->owner; | |
if ($file = $self->getField('Filename')) { | |
// image path & exif metadata | |
$imagePath = $self->getFullPath(); | |
$type = strtolower(File::get_file_extension($imagePath)); | |
if ($type == "jpeg" || $type == "jpg") { | |
$exif = exif_read_data($imagePath); | |
// resource optimisation | |
if (file_exists($imagePath) && !empty($exif['Orientation'])) { | |
// only JPEG has metadata, so no PNG or GIF parsers necessary | |
$source = imagecreatefromjpeg($imagePath); | |
// modify according to orientation | |
// replace jpeg at source, thus no other complexities regarding renaming, etc. | |
// image write placed inline for further resource optimisation | |
switch ($exif['Orientation']) { | |
case 3 : | |
$image = imagerotate($source, 180, 0); | |
imagejpeg($image, $imagePath, 100); | |
break; | |
case 6 : | |
$image = imagerotate($source, -90, 0); | |
imagejpeg($image, $imagePath, 100); | |
break; | |
case 8 : | |
$image = imagerotate($source, 90, 0); | |
imagejpeg($image, $imagePath, 100); | |
break; | |
} | |
} | |
} | |
} | |
// inherited from "owner" | |
$self->deleteFormattedImages(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires appropriate entry in the _config/config.yml file. For example, if the above snippet is saved in a file called ImageExtension.php, the following must be added to the yaml file: