<p>Interesting problem! I took a stab at this, see if this works for your use case.</p>
<p>It relies on ImageMagick to check for the top left pixel color (0,0) after the image is uploaded (but will also work if you hit resave). (If you want to check the other 3 corners, you'll need more code but this should get you started.)</p>
<p>To use it, you'll need a lightswitch field called <code>hasWhiteBackground</code> on your asset volume (or change the name in the script).</p>
<p>The light switch gets switched to true if the top right corner of the image is white or transparent.</p>
<p>The &quot;magic&quot; is in the <code>getImagePixelColor</code> function.</p>
<pre class="lang-php prettyprint-override"><code>Event::on(
    \craft\elements\Asset::class,
    \craft\elements\Asset::EVENT_BEFORE_SAVE,
    function(\craft\events\ModelEvent $event) {
            $asset = $event-&gt;sender;
            
            
    if ($asset-&gt;kind == 'image' ) {
        
        if  ($event-&gt;isNew) {
            
            $assetFilePath = $asset-&gt;tempFilePath;
        
        } else {
            
            $volumePath = $asset-&gt;getVolume()-&gt;settings['path'];
            $folderPath = '/' . $asset-&gt;getFolder()-&gt;path;
            $assetFilePath = Craft::getAlias($volumePath) . $folderPath . $asset-&gt;filename;
        
        }
        
    
        $img = new \Imagick($assetFilePath);
        $pixel = $img-&gt;getImagePixelColor(1, 1);
        $p = $pixel-&gt;getColor();
        
        
        if (($p['r'] == 255 &amp;&amp; $p['g'] == 255 &amp;&amp; $p['b'] == 255) || ($p['r'] == 0  &amp;&amp; $p['g'] == 0 &amp;&amp; $p['b'] == 0 &amp;&amp; $p['a'] == 0)) {
            $asset-&gt;setFieldValue('hasWhiteBackground','1');
        
        }
    }


                
});


</code></pre>

CC BY-SA 4.0
2020-11-13T21:18:51.470Z
Great solution. Thanks for showing me how to attach to the save event. I'll update my original question with some additional info that might help the next seeker of white background detection.
nitech
CC BY-SA 4.0
2020-11-22T18:46:00.150Z
very nice solution!
Matthias Redl-Mann
CC BY-SA 4.0
2020-11-10T04:29:35.643Z
2020-11-21T13:51:20.113Z
2020-11-21T13:51:20.113Z
RitterKnight
<p>In my product catalog, some product images need to have the css attribute <code>object-fit: cover</code> while some need the <code>object-fit: contain</code>:</p>
<p><a href="https://i.sstatic.net/g8s1U.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/g8s1U.png" alt="different ways to fit images" /></a></p>
<p>I'd like to detect the white background, possibly on upload (to ease processing when live). I am currently using <a href="https://plugins.craftcms.com/imager" rel="nofollow noreferrer">Imager</a> for transforms, and I would guess that plugin could have some detection feature, but I can't seem to find it.</p>
<p>Reading around a little suggests reading all four corners of the image and determine white bg if all four pixels are white -- but how can I do this? (and how can I do it on file upload?)</p>
<h3>Comments for provided solution</h3>
<p>Craft CMS has a powerful event system that lets you attach to events and then perform further actions on the entities involved.</p>
<p>I created a site module based on <a href="https://github.com/nystudio107/site-module" rel="nofollow noreferrer">nystudio107's template</a>, and inserted the provided code.</p>
<p>Then I created the field <code>hasWhiteBackground</code> as a lightswitch field, and ran a console command <code>./craft assets/resave</code> as <a href="https://craftcms.com/docs/3.x/console-commands.html#resave" rel="nofollow noreferrer">documented in the Craft CMS 3 docs</a>, to update the lightswitch for existing assets.</p>
<p>I am using <code>imager</code> to transform the images and to create <code>srcset</code>. I use the <code>hasWhiteBackground</code> to do either a <code>fit</code> or <code>crop</code> mode to the resize operation:</p>
<pre class="lang-php prettyprint-override"><code>{% set image = p.productImage.one()|default(null) %}
{% set transformedImages = craft.imager.transformImage(image, [
    { width: 269 }, 
    { width: 246 },
    { width: 209 }
    ], { 
        ratio: 1/1, 
        position: image.getFocalPoint()|default(&quot;50% 50%&quot;),
        mode: image.hasWhiteBackground|default(false) ? 'fit' : 'crop'
    }) 
%} 
</code></pre>
<p>I then added the class <code>contain</code> to each image outputted:</p>
<pre class="lang-html prettyprint-override"><code> class=&quot;{{ image.hasWhiteBackground ? 'contain'}}&quot;&gt;
</code></pre>
<p>The class simply adds the following css to the image:</p>
<pre class="lang-css prettyprint-override"><code>.contain {
    object-fit:contain;
}
</code></pre>
<p>Here is what the result looks like:</p>
<p><a href="https://i.sstatic.net/JOxNM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JOxNM.png" alt="6 products lined up with some using object-fit contain and some cover." /></a></p>

<assets><image-transforms>
How to detect white background
# How to detect white background

(Asked by: username_0 on 2020-11-06)

In my product catalog, some product images need to have the css attribute object-fit: cover while some need the object-fit: contain:

I'd like to detect the white background, possibly on upload (to ease processing when live). I am currently using Imager for transforms, and I would guess that plugin could have some detection feature, but I can't seem to find it.
Reading around a little suggests reading all four corners of the image and determine white bg if all four pixels are white -- but how can I do this? (and how can I do it on file upload?)
Comments for provided solution
Craft CMS has a powerful event system that lets you attach to events and then perform further actions on the entities involved.
I created a site module based on nystudio107's template, and inserted the provided code.
Then I created the field hasWhiteBackground as a lightswitch field, and ran a console command ./craft assets/resave as documented in the Craft CMS 3 docs, to update the lightswitch for existing assets.
I am using imager to transform the images and to create srcset. I use the hasWhiteBackground to do either a fit or crop mode to the resize operation:
{% set image = p.productImage.one()|default(null) %}
{% set transformedImages = craft.imager.transformImage(image, [
    { width: 269 }, 
    { width: 246 },
    { width: 209 }
    ], { 
        ratio: 1/1, 
        position: image.getFocalPoint()|default("50% 50%"),
        mode: image.hasWhiteBackground|default(false) ? 'fit' : 'crop'
    }) 
%} 

I then added the class contain to each image outputted:
 class="{{ image.hasWhiteBackground ? 'contain'}}">

The class simply adds the following css to the image:
.contain {
    object-fit:contain;
}

Here is what the result looks like:

**Tags:** assets, image-transforms

---

## 1 answers

### Answer by username_1 on 2020-11-10. Score: 2 | Accepted answer

Interesting problem! I took a stab at this, see if this works for your use case.
It relies on ImageMagick to check for the top left pixel color (0,0) after the image is uploaded (but will also work if you hit resave). (If you want to check the other 3 corners, you'll need more code but this should get you started.)
To use it, you'll need a lightswitch field called hasWhiteBackground on your asset volume (or change the name in the script).
The light switch gets switched to true if the top right corner of the image is white or transparent.
The "magic" is in the getImagePixelColor function.
Event::on(
    \craft\elements\Asset::class,
    \craft\elements\Asset::EVENT_BEFORE_SAVE,
    function(\craft\events\ModelEvent $event) {
            $asset = $event->sender;
            
            
    if ($asset->kind == 'image' ) {
        
        if  ($event->isNew) {
            
            $assetFilePath = $asset->tempFilePath;
        
        } else {
            
            $volumePath = $asset->getVolume()->settings['path'];
            $folderPath = '/' . $asset->getFolder()->path;
            $assetFilePath = Craft::getAlias($volumePath) . $folderPath . $asset->filename;
        
        }
        
    
        $img = new \Imagick($assetFilePath);
        $pixel = $img->getImagePixelColor(1, 1);
        $p = $pixel->getColor();
        
        
        if (($p['r'] == 255 && $p['g'] == 255 && $p['b'] == 255) || ($p['r'] == 0  && $p['g'] == 0 && $p['b'] == 0 && $p['a'] == 0)) {
            $asset->setFieldValue('hasWhiteBackground','1');
        
        }
    }


                
});

> **Comments:**
> **username_0**: Great solution. Thanks for showing me how to attach to the save event. I'll update my original question with some additional info that might help the next seeker of white background detection.  
> **username_2**: very nice solution!  

---

