Completed
Push — master ( e1a42c...4477de )
by Leo
02:04
created

ImageOrientationFixer::onBeforeWrite()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 15
rs 8.8571
cc 6
eloc 10
nc 5
nop 0
1
<?php
2
class ImageOrientationFixer extends DataExtension {
3
	
4
	public function onBeforeWrite() {
5
		$ext = $this->owner->getExtension();
6
		if (strtolower($ext) == 'jpg' || strtolower($ext) == 'jpeg') {
7
			$path = $this->owner->getFullPath();
8
			if ($orientation = $this->get_orientation($path)) {
9
				if (extension_loaded('imagick')) {
10
					$this->rotate_imagick($path, $orientation);
11
				} elseif (extension_loaded('gd')) {
12
					$this->rotate_gd($path, $orientation);
13
				}
14
			}
15
		}
16
		
17
		parent::onBeforeWrite();
18
	}
19
	
20
	private function get_orientation($path) {
21
		$exif_data = exif_read_data($path);
22
		$orientation = !empty($exif_data['Orientation']) ? $exif_data['Orientation'] : null;
23
		/**
24
		 * this image will help you understand the orientation and the difference between encoded and printed
25
		 * http://www.kendawson.ca/wp-content/uploads/orient_flag2.gif
26
		 */
27
		return $orientation == 1 ? false : $orientation;
28
	}
29
	
30
	private function rotate_imagick($imagePath, $orientation) {
31
		$imagick = new Imagick($imagePath);
32
		$imagick->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
33
		$deg = 0;
34
		switch ($orientation) {
35
			case 3:
36
				$deg = -180;
37
				break;
38
			case 6:
39
				$deg = 90;
40
				break;
41
			case 8:
42
				$deg = -90;
43
				break;
44
		}
45
		$imagick->rotateImage(new ImagickPixel('#00000000'), $deg);
46
		$imagick->writeImage($imagePath);
47
		$imagick->clear(); 
48
		$imagick->destroy(); 
49
	}
50
	
51
	private function rotate_gd($path, $orientation) {
52
		$image = imagecreatefromjpeg($path);
53
			
54
		switch ($orientation) {
55
			case 3:
56
				$image = imagerotate($image, 180, 0);
57
				break;
58
			case 6:
59
				$image = imagerotate($image, -90, 0);
60
				break;
61
			case 8:
62
				$image = imagerotate($image, 90, 0);
63
				break;
64
		}
65
		
66
		imagejpeg($image, $path, 100);
67
		imagedestroy($image);
68
		return true;
69
	}
70
}