Add border around png image using imagick PHP

后端 未结 1 845
逝去的感伤
逝去的感伤 2021-01-01 21:18

How can I add a border around a png image? Whenever I try to add a border using borderImage function available in imagick it loses its transparency if it is a png image.

1条回答
  •  佛祖请我去吃肉
    2021-01-01 21:29

    If you want to achieve result like this:

    Result Image

    then this is it. You can even give padding between border and image if you want!

    /** Set source image location. You can use URL here **/
    $imageLocation = 'tux.png';
    
    /** Set border format **/
    $borderWidth = 10;
    
    // You can use color name, hex code, rgb() or rgba()
    $borderColor = 'rgba(255, 0, 0, 1)';
    
    // Padding between image and border. Set to 0 to give none
    $borderPadding = 0;
    
    
    /** Core program **/
    
    // Create Imagick object for source image
    $imageSource = new Imagick( $imageLocation );
    
    // Get image width and height, and automatically set it wider than
    // source image dimension to give space for border (and padding if set)
    $imageWidth = $imageSource->getImageWidth() + ( 2 * ( $borderWidth + $borderPadding ) );
    $imageHeight = $imageSource->getImageHeight() + ( 2 * ( $borderWidth + $borderPadding ) );
    
    // Create Imagick object for final image with border
    $image = new Imagick();
    
    // Set image canvas
    $image->newImage( $imageWidth, $imageHeight, new ImagickPixel( 'none' )
    );
    
    // Create ImagickDraw object to draw border
    $border = new ImagickDraw();
    
    // Set fill color to transparent
    $border->setFillColor( 'none' );
    
    // Set border format
    $border->setStrokeColor( new ImagickPixel( $borderColor ) );
    $border->setStrokeWidth( $borderWidth );
    $border->setStrokeAntialias( false );
    
    // Draw border
    $border->rectangle(
        $borderWidth / 2 - 1,
        $borderWidth / 2 - 1,
        $imageWidth - ( ($borderWidth / 2) ),
        $imageHeight - ( ($borderWidth / 2) )
    );
    
    // Apply drawed border to final image
    $image->drawImage( $border );
    
    $image->setImageFormat('png');
    
    // Put source image to final image
    $image->compositeImage(
        $imageSource, Imagick::COMPOSITE_DEFAULT,
        $borderWidth + $borderPadding,
        $borderWidth + $borderPadding
    );
    
    // Prepare image and publish!
    header("Content-type: image/png");
    echo $image;
    

    I got this method from here. Basically we just make a rectangle with transparent fill and formatted border using ImagickDraw::rectangle, then we put the image inside the rectangle using Imagick::compositeImage.

    Here is the result if you set $borderPadding to 10:

    Alternative Result Image

    That's it! Hope it helps :)

    0 讨论(0)
提交回复
热议问题