bitandblack / image-blur
Extracts color values from images and creates blurred CSS backgrounds.
Fund package maintenance!
Buymeacoffee
Requires
- php: >=8.2
- ext-imagick: *
- bitandblack/colors: ^2.11
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^11.0
- rector/rector: ^1.0
- symplify/easy-coding-standard: ^12.0
This package is auto-updated.
Last update: 2024-12-20 11:50:34 UTC
README
Bit&Black Image Blur
Extracts the most important color values from an image and creates a blurred CSS background out of them.
This can be used to display a simple preview of the image while it still loads.
Original image | Blurred version as CSS gradient |
---|---|
Usage
The AutoCSSImageBackground
class takes an image and returns the color values as CSS custom properties. To get the CSS gradient working, you need to add the CSS class background-blur
to the HTML. All together it may look like that:
<?php
use BitAndBlack\ImageBlur\AutoCSSImageBackground;
echo '<img src="my-image.jpg" class="background-blur" style="' . new AutoCSSImageBackground('my-image.jpg') . '">';
And the output will be similar to:
<img src="my-image.jpg" class="background-blur" style="--color-top-left: rgb(181, 126, 116); --color-top-right: rgb(202, 181, 115); --color-bottom-left: rgb(183, 206, 213); --color-bottom-right: rgb(181, 203, 206); --color-center: rgb(149, 159, 143);">
The CSS class can be found in the src
folder. There is a scss
file with a mixin too.
The manual way
Initialize the ColorExtract
class with your image at first:
<?php
use BitAndBlack\ImageBlur\ColorExtract;
$colorExtract = new ColorExtract('my-image.jpg');
Get the color values by calling the getColors
method then:
<?php
$colors = $colorExtract->getColors();
Options
The method setDownscalePercent
can be used to specify the percentage to which the image should be reduced. This enables faster color extraction. At the same time, the image must not be scaled too small so that characteristic color values are retained. For example:
<?php
$colorExtract->setDownscalePercent(10);
The method setPaddingPercent
can be used to specify the distance from the image border in percent where the colors get extracted from. This can improve extracting the color values, because the colors with a little distance from the outer image border are more recognizable. For example:me
<?php
$colorExtract->setPaddingPercent(25);
Formatting
If you want to format the colors into CSS custom properties, you can use the CssCustomPropertiesFormatter
class:
<?php
use BitAndBlack\ImageBlur\CssCustomPropertiesFormatter;
$formattedColors = CssCustomPropertiesFormatter($colorExtract);
But for sure you can use your own custom formatter too.
Help
If you have any questions, feel free to contact us under hello@bitandblack.com
.
Further information about Bit&Black can be found under www.bitandblack.com.