]> BookStack Code Mirror - bookstack/blob - app/Uploads/FaviconHandler.php
Updated favicon gen to use png-based ICO
[bookstack] / app / Uploads / FaviconHandler.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use Illuminate\Http\UploadedFile;
6 use Intervention\Image\ImageManager;
7
8 class FaviconHandler
9 {
10     public function __construct(
11         protected ImageManager $imageTool
12     ) {
13     }
14
15     /**
16      * Save the given UploadedFile instance as the application favicon.
17      */
18     public function saveForUploadedImage(UploadedFile $file): void
19     {
20         $targetPath = public_path('favicon.ico');
21         if (!is_writeable($targetPath)) {
22             return;
23         }
24
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);
30
31         file_put_contents($targetPath, $icoData);
32     }
33
34     /**
35      * Restore the original favicon image.
36      */
37     public function restoreOriginal(): void
38     {
39         $targetPath = public_path('favicon.ico');
40         $original = public_path('icon.ico');
41         if (!is_writeable($targetPath)) {
42             return;
43         }
44
45         copy($original, $targetPath);
46     }
47
48     /**
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)
52      */
53     protected function pngToIco(string $bmpData, int $width, int $height): string
54     {
55         // ICO header
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
59
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
65
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);
75
76         // Join & return the combined parts of the ICO image data
77         return $header . $entry . $bmpData;
78     }
79 }