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

标签 php image image-processing png

如何在 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;

这是原图:

enter image description here

这是添加边框后的:

enter image description here

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

最佳答案

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

Result Image

那就这样吧。如果需要,您甚至可以在边框和图像之间添加填充!

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

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

以下是将 $borderPadding 设置为 10 的结果:

Alternative Result Image

就是这样!希望它有帮助:)

关于php - 使用 imagick PHP 在 png 图像周围添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24450999/

相关文章:

php - HTML、PHP 和 MYSQL 图片彼此相邻

c++ - 分水岭分割opencv xcode

php - 无法插入到我的 sql 表中

html - 为什么图片不放在html页面的最左上角?

php - MySQL 或 PHP 将行转换为列

ios - 崩溃 CGDataProviderCreateWithCopyOfData : vm_copy failed: status 1

c++ - 过滤时进行操作

python - 从OpenCV中的图像定位和提取(未知)书籍

PHP: "Value Expected To Be A Reference"与 Call_User_Func 和绑定(bind)参数

php - 自动设置外键值