Skip to content

Commit

Permalink
Update Image helper :
Browse files Browse the repository at this point in the history
- improve base64Encode() to support http(s) resources
  • Loading branch information
webeweb committed Apr 25, 2022
1 parent 8d0b114 commit f9e3c64
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
15 changes: 8 additions & 7 deletions src/image/Helper/ImageHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
namespace WBW\Library\Image\Helper;

use RuntimeException;
use SplFileObject;
use WBW\Library\Image\Factory\ImageFactory;
use WBW\Library\Image\Model\Image;
use WBW\Library\Image\Model\ImageInterface;
Expand All @@ -37,14 +36,16 @@ public static function base64Encode(?string $uri): ?string {
return null;
}

$data = "";
$data = file_get_contents($uri);

$splFileObject = new SplFileObject($uri);
while (false === $splFileObject->eof()) {
$data .= $splFileObject->fgets();
}
$stream = fopen("php://memory", "w+b");
fwrite($stream, $data);

$mime = mime_content_type($stream);

fclose($stream);

return sprintf("data:%s;base64,%s", mime_content_type($uri), base64_encode($data));
return sprintf("data:%s;base64,%s", $mime, base64_encode($data));
}

/**
Expand Down
6 changes: 4 additions & 2 deletions tests/image/Helper/ImageHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,12 @@ protected function setUp(): void {
public function testBase64Encode(): void {

// Set the mocks.
$src = realpath($this->images[0]);
$uri = realpath($this->images[0]);
$url = "https://raw.githubusercontent.com/webeweb/core-library/master/tests/image/Fixtures/TestImage_1920x1037.jpg";

$res = file_get_contents(__DIR__ . "/ImageHelperTest.testBase64Encode.txt");
$this->assertEquals($res, ImageHelper::base64Encode($src));
$this->assertEquals($res, ImageHelper::base64Encode($uri));
$this->assertEquals($res, ImageHelper::base64Encode($url));

$this->assertNull(ImageHelper::base64Encode(null));
}
Expand Down

0 comments on commit f9e3c64

Please sign in to comment.