3 namespace BookStack\Uploads;
5 use Illuminate\Http\UploadedFile;
6 use Intervention\Image\ImageManager;
10 public function __construct(
11 protected ImageManager $imageTool
16 * Save the given UploadedFile instance as the application favicon.
18 public function saveForUploadedImage(UploadedFile $file): void
20 $targetPath = public_path('favicon.ico');
21 if (!is_writeable($targetPath)) {
25 $imageData = file_get_contents($file->getRealPath());
26 $image = $this->imageTool->make($imageData);
27 $image->resize(32, 32);
28 $bmpData = $image->encode('png');
29 $icoData = $this->pngToIco($bmpData, 32, 32);
31 file_put_contents($targetPath, $icoData);
35 * Restore the original favicon image.
37 public function restoreOriginal(): void
39 $targetPath = public_path('favicon.ico');
40 $original = public_path('icon.ico');
41 if (!is_writeable($targetPath)) {
45 copy($original, $targetPath);
49 * Convert PNG image data to ICO file format.
50 * Built following the file format info from Wikipedia:
51 * https://en.wikipedia.org/wiki/ICO_(file_format)
53 protected function pngToIco(string $bmpData, int $width, int $height): string
56 $header = pack('v', 0x00); // Reserved. Must always be 0
57 $header .= pack('v', 0x01); // Specifies ico image
58 $header .= pack('v', 0x01); // Specifies number of images
60 // ICO Image Directory
61 $entry = hex2bin(dechex($width)); // Image width
62 $entry .= hex2bin(dechex($height)); // Image height
63 $entry .= "\0"; // Color palette, typically 0
64 $entry .= "\0"; // Reserved
66 // Color planes, Appears to remain 1 for bmp image data
67 $entry .= pack('v', 0x01);
68 // Bits per pixel, can range from 1 to 32. From testing conversion
69 // via intervention from png typically provides this as 24.
70 $entry .= pack('v', 0x00);
71 // Size of the image data in bytes
72 $entry .= pack('V', strlen($bmpData));
73 // Offset of the bmp data from file start
74 $entry .= pack('V', strlen($header) + strlen($entry) + 4);
76 // Join & return the combined parts of the ICO image data
77 return $header . $entry . $bmpData;