-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathImageContent.php
More file actions
71 lines (62 loc) · 1.74 KB
/
ImageContent.php
File metadata and controls
71 lines (62 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
namespace fholbrook\Openrouter\DTO;
use fholbrook\Openrouter\Contracts\ContentInterface;
use fholbrook\Openrouter\Exceptions\OpenRouterException;
/**
* OpenAI Spec Image content item. Supports both URL and base64 encoded image data.
*/
final class ImageContent implements ContentInterface
{
public function __construct(
/**
* URL or base64 encoded image data
*
* @var string
*/
public string $url,
/**
* Optional, defaults to 'image_url'
*
* @var string|null
*/
public string $type = 'image_url'
) {
}
public static function fromFile(string $path): self
{
if (realpath($path) === false) {
throw new OpenRouterException('File not found: `'.$path.'`');
}
$content = file_get_contents($path);
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($path);
return new self(
sprintf('data:%s;base64,%s', $mimeType, base64_encode($content))
);
}
public static function fromContent(?string $content): self
{
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($content);
return new self(
sprintf('data:%s;base64,%s', $mimeType, base64_encode($content))
);
}
public function toArray(): array
{
return array_filter(
[
'image_url' => ['url' => $this->url],
'type' => $this->type,
]
);
}
public static function fromArray(array $data): self
{
return new self(
$data['image_url']['url'],
$data['type'] ?? 'image_url'
);
}
}