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('bmp');
29 $icoData = $this->bmpToIco($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 BMP 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 bmpToIco(string $bmpData, int $width, int $height): string
55 // Trim off the header of the bitmap file
56 $rawBmpData = substr($bmpData, 14);
59 $header = pack('v', 0x00); // Reserved. Must always be 0
60 $header .= pack('v', 0x01); // Specifies ico image
61 $header .= pack('v', 0x01); // Specifies number of images
63 // ICO Image Directory
64 $entry = hex2bin(dechex($width)); // Image width
65 $entry .= hex2bin(dechex($height)); // Image height
66 $entry .= "\0"; // Color palette, typically 0
67 $entry .= "\0"; // Reserved
69 // Color planes, Appears to remain 1 for bmp image data
70 $entry .= pack('v', 0x01);
71 // Bits per pixel, can range from 1 to 32. From testing conversion
72 // via intervention from png typically provides this as 32.
73 $entry .= pack('v', 0x20);
74 // Size of the image data in bytes
75 $entry .= pack('V', strlen($rawBmpData));
76 // Offset of the bmp data from file start
77 $entry .= pack('V', strlen($header) + strlen($entry) + 4);
79 // Join & return the combined parts of the ICO image data
80 return $header . $entry . $rawBmpData;