3 namespace BookStack\Uploads;
5 use Illuminate\Http\UploadedFile;
6 use Intervention\Image\ImageManager;
10 protected string $path;
12 public function __construct(
13 protected ImageManager $imageTool
15 $this->path = public_path('favicon.ico');
19 * Save the given UploadedFile instance as the application favicon.
21 public function saveForUploadedImage(UploadedFile $file): void
23 if (!is_writeable($this->path)) {
27 $imageData = file_get_contents($file->getRealPath());
28 $image = $this->imageTool->make($imageData);
29 $image->resize(32, 32);
30 $bmpData = $image->encode('png');
31 $icoData = $this->pngToIco($bmpData, 32, 32);
33 file_put_contents($this->path, $icoData);
37 * Restore the original favicon image.
38 * Returned boolean indicates if the copy occurred.
40 public function restoreOriginal(): bool
42 $permissionItem = file_exists($this->path) ? $this->path : dirname($this->path);
43 if (!is_writeable($permissionItem)) {
47 return copy($this->getOriginalPath(), $this->path);
51 * Restore the original favicon image if no favicon image is already in use.
52 * Returns a boolean to indicate if the file exists.
54 public function restoreOriginalIfNotExists(): bool
56 if (file_exists($this->path)) {
60 return $this->restoreOriginal();
64 * Get the path to the favicon file.
66 public function getPath(): string
72 * Get the path of the original favicon copy.
74 public function getOriginalPath(): string
76 return public_path('icon.ico');
80 * Convert PNG image data to ICO file format.
81 * Built following the file format info from Wikipedia:
82 * https://en.wikipedia.org/wiki/ICO_(file_format)
84 protected function pngToIco(string $bmpData, int $width, int $height): string
87 $header = pack('v', 0x00); // Reserved. Must always be 0
88 $header .= pack('v', 0x01); // Specifies ico image
89 $header .= pack('v', 0x01); // Specifies number of images
91 // ICO Image Directory
92 $entry = hex2bin(dechex($width)); // Image width
93 $entry .= hex2bin(dechex($height)); // Image height
94 $entry .= "\0"; // Color palette, typically 0
95 $entry .= "\0"; // Reserved
97 // Color planes, Appears to remain 1 for bmp image data
98 $entry .= pack('v', 0x01);
99 // Bits per pixel, can range from 1 to 32. From testing conversion
100 // via intervention from png typically provides this as 24.
101 $entry .= pack('v', 0x00);
102 // Size of the image data in bytes
103 $entry .= pack('V', strlen($bmpData));
104 // Offset of the bmp data from file start
105 $entry .= pack('V', strlen($header) + strlen($entry) + 4);
107 // Join & return the combined parts of the ICO image data
108 return $header . $entry . $bmpData;