使用imagick PHP在png图像周围添加边框

use*_*732 12 php png image image-processing

如何在png图像周围添加边框?每当我尝试添加边框采用borderImage可用功能imagick它失去了它的透明度,如果它是一个PNG图像.

<?php

$image = new Imagick();
$image->readImage('tux.png');

$image->BorderImage(new ImagickPixel("red") , 5,5);

// send the result to the browser
header("Content-Type: image/" . $image->getImageFormat());
echo $image;
Run Code Online (Sandbox Code Playgroud)

这是原始图片:

在此输入图像描述

这是在添加边框之后:

在此输入图像描述

边框颜色也应用于背景.我想用imagick做到这一点如何在不失透明度的情况下将边框应用于透明图像?

小智 15

如果你想达到这样的结果:

结果图片

那就是这个.如果需要,您甚至可以在边框和图像之间进行填充!

/** 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;
Run Code Online (Sandbox Code Playgroud)

我从这里得到了这个方法.基本上我们只使用透明填充和格式化边框制作一个矩形ImagickDraw::rectangle,然后我们将图像放在矩形内Imagick::compositeImage.

如果您设置$borderPadding为以下结果10:

替代结果图像

而已!希望能帮助到你 :)