【问题标题】:Add border around png image using imagick PHP使用imagick PHP在png图像周围添加边框
【发布时间】:2014-08-18 12:21:43
【问题描述】:

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

这是原图:

这是在添加边框之后:

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

【问题讨论】:

  • 您的意思是在图像外应用边框线,这样它就不会给出背景?

标签: php image image-processing png


【解决方案1】:

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

那么就是这样。如果需要,您甚至可以在边框和图像之间设置填充!

/** 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,结果如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2018-10-04
    • 2015-05-15
    相关资源
    最近更新 更多