From dfbe53c01dae8467468ef2b817c09b786a7839d2 Mon Sep 17 00:00:00 2001 From: thisispiers <1831251+thisispiers@users.noreply.github.com> Date: Mon, 15 Apr 2024 17:07:16 +0100 Subject: [PATCH] Add reset and hasImage methods and make generate public (#339) * Add reset and hasImage methods * Make generate method public * Update README --- README.md | 21 +++++++++++++++++++++ src/claviska/SimpleImage.php | 26 ++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d2adf6a..791cdfd 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,15 @@ Generates an image string. Returns a SimpleImage object. +#### `generate($mimeType, $options)` + +Generates an image. + +- `$mimeType` (string) - The image format to output as a mime type (defaults to the original mime type). +- `$options` (array|int) - Array of options or Image quality as a percentage (default 100). + +Returns an array: [mimeType, data] + #### Options array Instead of providing the quality as an integer as the last function parameter you can also set various options depending on the targeted Mime type using an associative array. @@ -296,6 +305,18 @@ Gets the image's current width. Returns the width as an integer. +#### `hasImage()` + +Checks if the SimpleImage object has loaded an image. + +Returns a boolean. + +#### `reset()` + +Destroys the image resource. + +Returns a SimpleImage object. + ### Manipulation #### `autoOrient()` diff --git a/src/claviska/SimpleImage.php b/src/claviska/SimpleImage.php index 75a1826..c9c0c7b 100644 --- a/src/claviska/SimpleImage.php +++ b/src/claviska/SimpleImage.php @@ -116,15 +116,33 @@ public function __construct(string $image = '', array $flags = []) */ public function __destruct() { - if ($this->image instanceof GdImage) { - imagedestroy($this->image); - } + $this->reset(); } ////////////////////////////////////////////////////////////////////////////////////////////////// // Helper functions ////////////////////////////////////////////////////////////////////////////////////////////////// + /** + * Checks if the SimpleImage object has loaded an image. + */ + public function hasImage(): bool + { + return $this->image instanceof GdImage; + } + + /** + * Destroys the image resource. + */ + public function reset(): static + { + if ($this->hasImage()) { + imagedestroy($this->image); + } + + return $this; + } + /** * Set flag value. * @@ -313,7 +331,7 @@ public function fromString(string $string): SimpleImage|static * * @throws Exception Thrown when WEBP support is not enabled or unsupported format. */ - protected function generate(string $mimeType = null, array|int $options = []): array + public function generate(string $mimeType = null, array|int $options = 100): array { // Format defaults to the original mime type $mimeType = $mimeType ?: $this->mimeType;