Skip to content

Instantly share code, notes, and snippets.

@dljoseph
Created November 22, 2014 08:52
Show Gist options
  • Save dljoseph/9d535d9a2ae6e849904a to your computer and use it in GitHub Desktop.
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
<?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();
}
}
@dljoseph
Copy link
Author

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:

Image:
  extensions:
    - 'ImageExtension'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment