Completed
Push — master ( 9e9310...e9812b )
by Leo
02:16
created

ImageOrientationFixer::updateCMSFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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