Browse Source

added Image class

Fabian Peter Hammerle 8 years ago
parent
commit
8ab5d927f1
5 changed files with 62 additions and 0 deletions
  1. 44 0
      Image.php
  2. 17 0
      tests/ImageTest.php
  3. 1 0
      tests/autoload.php
  4. BIN
      tests/data/chainring-saved.jpg
  5. BIN
      tests/data/chainring.jpg

+ 44 - 0
Image.php

@@ -0,0 +1,44 @@
+<?php
+
+namespace fphammerle\helpers;
+
+class Image
+{
+    protected $resource = null;
+
+    private function __construct()
+    {
+    }
+
+    public function __destruct()
+    {
+        if($this->resource) {
+            imagedestroy($this->resource);
+        }
+    }
+
+    /**
+     * @param string $path
+     * @return Image
+     */
+    public static function fromFile($path)
+    {
+        switch(exif_imagetype($path)) {
+            case IMAGETYPE_JPEG:
+                $image = new self;
+                $image->resource = imagecreatefromjpeg($path);
+                return $image;
+            default:
+                throw new \InvalidArgumentException("type of '$path' is not supported");
+        }
+    }
+
+    /**
+     * @param string $path
+     * @return void
+     */
+    public function saveJpeg($path)
+    {
+        imagejpeg($this->resource, $path);
+    }
+}

+ 17 - 0
tests/ImageTest.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace fphammerle\helpers\tests;
+
+use fphammerle\helpers\Image;
+
+class ImageTest extends \PHPUnit_Framework_TestCase
+{
+    public function testSaveJpeg()
+    {
+        $img = Image::fromFile(__DIR__ . '/data/chainring.jpg');
+        $tmp_path = tempnam(sys_get_temp_dir(), 'image');
+        $img->saveJpeg($tmp_path);
+        $this->assertFileEquals(__DIR__ . '/data/chainring-saved.jpg', $tmp_path);
+        unlink($tmp_path);
+    }
+}

+ 1 - 0
tests/autoload.php

@@ -5,4 +5,5 @@ error_reporting(-1);
 
 require_once(__DIR__ . '/../ArrayHelper.php');
 require_once(__DIR__ . '/../DateTimeHelper.php');
+require_once(__DIR__ . '/../Image.php');
 require_once(__DIR__ . '/../StringHelper.php');

BIN
tests/data/chainring-saved.jpg


BIN
tests/data/chainring.jpg