Search code examples
phpimagemagickimagick

Can't get ImagickDraw setStrokeOpactiy to work


I'm not sure if this is a bug, or my method. I believe that the example below should show a red square with a barely visible (if at all) X across it. What's actually happening is the X (made of two lines) is fully opaque.

<?php
$draw = new ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(0.1);
$draw->setStrokeColor("black");
$draw->line(0, 0, 500, 500);
$draw->line(500, 0, 0, 500);

$drawing = new Imagick();
$drawing->newImage(500, 500, "red");
$drawing->setImageFormat("png");
$drawing->drawImage($draw);

header("Content-Disposition: attachment; filename=test.png");
echo $drawing->getImageBlob();
?>

Solution

  • There's two issues.

    i) You also need to set the fill color for a line stroke, not just the stroke color. Lines are drawn with a fill width of 1 pixel.

    ii) Setting the color overwrites the opacity, as the color 'black' has it's opacity set to fully opaque. Switching the order of the commands, stops the opacity being changed by the set color command.

    i.e. the setStrokeOpacity modifies the strokes colour. It does not get batched up and modify the draw command.

    <?php
    
    $draw = new ImagickDraw();
    $draw->setStrokeWidth(1);
    
    $draw->setStrokeColor("black");
    $draw->setStrokeOpacity(0.1);
    
    $draw->setFillColor('black');
    $draw->setfillopacity(0.1);
    
    $draw->line(0, 0, 500, 500);
    $draw->line(500, 0, 0, 500);
    
    $drawing = new Imagick();
    $drawing->newImage(500, 500, "red");
    $drawing->setImageFormat("png");
    $drawing->drawImage($draw);
    
    header("Content-Disposition: attachment; filename=test.png");
    //header("Content-Type: image/png");
    echo $drawing->getImageBlob();