使用Imagick PHP为PNG图像添加边框

14

我该如何在png图像周围添加边框?每当我尝试使用imagick中可用的borderImage函数添加边框时,如果是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;

这是原始图像:

enter image description here

添加边框后的图像如下:

enter image description here

边框颜色也应用于背景。我想使用imagick实现这一点,如何在不丢失透明度的情况下为透明图像添加边框?


你的意思是只在图像外应用边框线,这样就不会给背景带来影响了? - Ian Mustafa
1个回答

16

如果您想要实现这样的效果:

结果图片

那么这就是方法。如果你想要,在边框和图片之间还可以添加填充。

/** 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;

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

如果您将$borderPadding设置为10,则结果如下:

Alternative Result Image

就是这样!希望对您有所帮助 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接