Search code examples
transparencypixelphotoshop-script

Get colour sample from transparent pixel


I'm trying detect if a pixel is complete transparent or not. More specifically, if an image is on a transparent background or not. I thought that

  // Add a Color Sampler at a given x and y coordinate in the image.
  var pointSample = app.activeDocument.colorSamplers.add([(x),(y)]);

  // Obtain array of RGB values.
  var rgb = [
  pointSample.color.rgb.red,
  pointSample.color.rgb.green,
  pointSample.color.rgb.blue
 ];

would work - and it does...

Unless the pixel has 0% opacity (ie 100% transparent) in which case Photoshop throws a General 8800 error. I would use the above with a try catch but that probably isn't the way to go about it.

Any ideas?


Solution

  • Well I found a way to determine if an image has transparency or not:

    delete_all_colour_samples();
    var isImageTransparent = has_transparency();
    var x = 0;
    var y = 0;
    
    alert(isImageTransparent ? "Image has transparency." : "Image is opaque.");
    
    if (isImageTransparent)
    {
    
        // do stuff
    }
    else
    {
        // get colour sample
    
        // Add a Color Sampler at a given x and y coordinate in the image.
        var pointSample = app.activeDocument.colorSamplers.add([(x),(y)]);
    
        // Obtain array of RGB values.
        var rgb = [
        pointSample.color.rgb.red,
        pointSample.color.rgb.green,
        pointSample.color.rgb.blue
     ];
    }
    
    
    
    // function to see if image has transparency
    function has_transparency() 
    {
        var desc52 = new ActionDescriptor();
        var ref47 = new ActionReference();
        ref47.putProperty( charIDToTypeID('Chnl'), charIDToTypeID('fsel') );
        desc52.putReference( charIDToTypeID('null'), ref47 );
        var ref48 = new ActionReference();
        ref48.putEnumerated( charIDToTypeID('Chnl'), charIDToTypeID('Chnl'), charIDToTypeID('Trsp') );
        desc52.putReference( charIDToTypeID('T   '), ref48 );
        desc52.putBoolean( charIDToTypeID('Invr'), true );
        try
        {
            executeAction( charIDToTypeID('setd'), desc52, DialogModes.NO );
        }
        catch(eek)
        {
            return false;
    
        }
        activeDocument.selection.deselect();
        return true;
    }
    
    
    function delete_all_colour_samples()
    {
       // Kill all colour samples
       app.activeDocument.colorSamplers.removeAll();
    }