diff --git a/examples/huggingface/text-to-image.php b/examples/huggingface/text-to-image.php index 74f36bdc8..1dc487f35 100644 --- a/examples/huggingface/text-to-image.php +++ b/examples/huggingface/text-to-image.php @@ -20,4 +20,4 @@ 'task' => Task::TEXT_TO_IMAGE, ]); -echo $result->asBase64().\PHP_EOL; +echo $result->asDataUri().\PHP_EOL; diff --git a/src/platform/src/Result/BinaryResult.php b/src/platform/src/Result/BinaryResult.php index f85e08c00..4f810f1b2 100644 --- a/src/platform/src/Result/BinaryResult.php +++ b/src/platform/src/Result/BinaryResult.php @@ -39,12 +39,12 @@ public function toBase64(): string return base64_encode($this->data); } - public function toDataUri(): string + public function toDataUri(?string $mimeType = null): string { - if (null === $this->mimeType) { + if (null === ($mimeType ?? $this->mimeType)) { throw new RuntimeException('Mime type is not set.'); } - return 'data:'.$this->mimeType.';base64,'.$this->toBase64(); + return 'data:'.($mimeType ?? $this->mimeType).';base64,'.$this->toBase64(); } } diff --git a/src/platform/src/Result/DeferredResult.php b/src/platform/src/Result/DeferredResult.php index 2448446a8..05767a528 100644 --- a/src/platform/src/Result/DeferredResult.php +++ b/src/platform/src/Result/DeferredResult.php @@ -90,13 +90,13 @@ public function asBinary(): string /** * @throws ExceptionInterface */ - public function asBase64(): string + public function asDataUri(?string $mimeType = null): string { $result = $this->as(BinaryResult::class); \assert($result instanceof BinaryResult); - return $result->toDataUri(); + return $result->toDataUri($mimeType); } /** diff --git a/src/platform/tests/Result/BinaryResultTest.php b/src/platform/tests/Result/BinaryResultTest.php index 8bed637c1..90389f946 100644 --- a/src/platform/tests/Result/BinaryResultTest.php +++ b/src/platform/tests/Result/BinaryResultTest.php @@ -58,4 +58,13 @@ public function testToDataUriThrowsExceptionWhenMimeTypeNotSet() $result->toDataUri(); } + + public function testToDataUriWithMimeTypeExplicitlySet() + { + $result = new BinaryResult('binary data'); + $actual = $result->toDataUri('image/jpeg'); + $expected = 'data:image/jpeg;base64,'.base64_encode('binary data'); + + $this->assertSame($expected, $actual); + } }