1212class PngRenderer
1313{
1414 protected array $ foregroundColor = [0 , 0 , 0 ];
15+ protected ?array $ backgroundColor = null ;
16+
1517 protected bool $ useImagick ;
1618
1719 /**
@@ -52,6 +54,7 @@ public function render(Barcode $barcode, int $widthFactor = 2, int $height = 30)
5254 $ width = (int )round ($ barcode ->getWidth () * $ widthFactor );
5355
5456 if ($ this ->useImagick ) {
57+ $ image = $ this ->createImagickImageObject ($ width , $ height );
5558 $ imagickBarsShape = new ImagickDraw ();
5659 $ imagickBarsShape ->setFillColor (new ImagickPixel ('rgb( ' . implode (', ' , $ this ->foregroundColor ) .') ' ));
5760 } else {
@@ -80,7 +83,6 @@ public function render(Barcode $barcode, int $widthFactor = 2, int $height = 30)
8083 }
8184
8285 if ($ this ->useImagick ) {
83- $ image = $ this ->createImagickImageObject ($ width , $ height );
8486 $ image ->drawImage ($ imagickBarsShape );
8587 return $ image ->getImageBlob ();
8688 } else {
@@ -90,26 +92,49 @@ public function render(Barcode $barcode, int $widthFactor = 2, int $height = 30)
9092 }
9193 }
9294
95+ // Use RGB color definitions, like [0, 0, 0] or [255, 255, 255]
9396 public function setForegroundColor (array $ color ): self
9497 {
9598 $ this ->foregroundColor = $ color ;
96-
99+ return $ this ;
100+ }
101+
102+ // Use RGB color definitions, like [0, 0, 0] or [255, 255, 255]
103+ // If no color is set, the background will be transparent
104+ public function setBackgroundColor (?array $ color ): self
105+ {
106+ $ this ->backgroundColor = $ color ;
97107 return $ this ;
98108 }
99109
100110 protected function createGdImageObject (int $ width , int $ height )
101111 {
102112 $ image = \imagecreate ($ width , $ height );
103- $ colorBackground = \imagecolorallocate ($ image , 255 , 255 , 255 );
104- \imagecolortransparent ($ image , $ colorBackground );
113+
114+ if ($ this ->backgroundColor !== null ) {
115+ // Colored background
116+ $ backgroundColor = \imagecolorallocate ($ image , $ this ->backgroundColor [0 ], $ this ->backgroundColor [1 ], $ this ->backgroundColor [2 ]);
117+ \imagefill ($ image , 0 , 0 , $ backgroundColor );
118+ } else {
119+ // Use transparent background
120+ $ backgroundColor = \imagecolorallocate ($ image , 255 , 255 , 255 );
121+ \imagecolortransparent ($ image , $ backgroundColor );
122+ }
105123
106124 return $ image ;
107125 }
108126
109127 protected function createImagickImageObject (int $ width , int $ height ): Imagick
110128 {
111129 $ image = new Imagick ();
112- $ image ->newImage ($ width , $ height , 'none ' , 'PNG ' );
130+ if ($ this ->backgroundColor !== null ) {
131+ // Colored background
132+ $ backgroundColor = new ImagickPixel ('rgb( ' . implode (', ' , $ this ->backgroundColor ) . ') ' );
133+ } else {
134+ // Use transparent background
135+ $ backgroundColor = new ImagickPixel ('none ' );
136+ }
137+ $ image ->newImage ($ width , $ height , $ backgroundColor , 'PNG ' );
113138
114139 return $ image ;
115140 }
0 commit comments