@@ -40,6 +40,7 @@ class InitialAvatar
4040 protected $ fontName = 'OpenSans, sans-serif ' ;
4141 protected $ generated_initials = 'JD ' ;
4242 protected $ preferBold = false ;
43+ protected $ randomBgColor = false ;
4344
4445 /**
4546 * Language eg.en zh-CN.
@@ -202,9 +203,31 @@ public function preferRegular()
202203 public function background ($ background )
203204 {
204205 $ this ->bgColor = (string ) $ background ;
206+ $ this ->randomBgColor = false ;
205207
206208 return $ this ;
207209 }
210+
211+ /**
212+ * Set background color to be randomly generated for each avatar.
213+ *
214+ * @param bool $random
215+ * @param int $saturation Saturation value (0-100)
216+ * @param int $luminance Luminance value (0-100)
217+ *
218+ * @return $this
219+ */
220+ public function randomBackground ($ random = true , int $ saturation = 85 , int $ luminance = 60 )
221+ {
222+ $ this ->randomBgColor = (bool ) $ random ;
223+
224+ if ($ random ) {
225+ // Generate an initial random color
226+ $ this ->generateRandomColor ($ saturation , $ luminance );
227+ }
228+
229+ return $ this ;
230+ }
208231
209232 /**
210233 * Set the font color.
@@ -437,13 +460,29 @@ public function getInitials()
437460
438461 /**
439462 * Will return the background color parameter.
463+ * If randomBgColor is enabled, generates a new random color each time.
440464 *
441465 * @return string
442466 */
443467 public function getBackgroundColor ()
444468 {
469+ if ($ this ->randomBgColor ) {
470+ // Generate a new random color each time this method is called
471+ $ this ->generateRandomColor ();
472+ }
473+
445474 return $ this ->bgColor ;
446475 }
476+
477+ /**
478+ * Will return whether random background color is enabled.
479+ *
480+ * @return bool
481+ */
482+ public function getRandomBackgroundColor ()
483+ {
484+ return $ this ->randomBgColor ;
485+ }
447486
448487 /**
449488 * Will return the set driver.
@@ -921,4 +960,26 @@ protected function getContrastColor($hexColor)
921960 return '#FFFFFF ' ;
922961 }
923962 }
963+
964+ /**
965+ * Generate a random background color.
966+ *
967+ * @param int $saturation Saturation value (0-100)
968+ * @param int $luminance Luminance value (0-100)
969+ *
970+ * @return string The generated hex color
971+ */
972+ protected function generateRandomColor (int $ saturation = 85 , int $ luminance = 60 )
973+ {
974+ // Generate a random hue (0-1)
975+ $ hue = mt_rand (0 , 359 ) / 360 ;
976+ $ saturation /= 100 ;
977+ $ luminance /= 100 ;
978+
979+ $ hexColor = $ this ->convertHSLtoRGB ($ hue , $ saturation , $ luminance );
980+ $ this ->bgColor = $ hexColor ;
981+ $ this ->fontColor = $ this ->getContrastColor ($ hexColor );
982+
983+ return $ hexColor ;
984+ }
924985}
0 commit comments