开发者

Transparent rounded corners in PHP

Is it possible to create transparent corners for an image on fly with PHP? I think that it would be possible, but I am missing a function that would preserve alpha values when you copy your image.

My idea was to create an image of same width and height, then apply transparent corners, but then I need to pre开发者_JAVA百科serve the alpha channel and just copy image on that mask, leaving transparent still transparent, but colors changed to copied image (or vice versa, put mask on image).

Is it possible to do that and what are commands for that if there are any?

Update: Thanks for helping with this. It was some time ago, and I forgot but if anybody cross this question to find a solution just visit this one: http://www.pc-siete.g6.cz/galery.html . I made functions for gradient, radial gradient and also those rounded corners so feel free to use :) . I'm not really using it on my webstie, but it's good to have them prepared.

For some reason the downloaded file had just ad in it. Now it's stored inside zip and downloads properly.


As far as I know there is no built-in function to do this. However you can create one yourself along these lines:

function imageapplyroundedcorners(&$img,$radius) {
    // for each corner
        // loop through pixels between corner and (corner +- radius)
            // if distance between pixel and radius > radius, make transparent
            // elseif distance > radius-1 make partially transparent (for antialiasing)
}


I just created this function using ImageMagick in PHP which does exactly what I wanted. You need to set the TEMP_DIR constant and have the convert executable on your execution path.

function png_corners($image, $r = 12)
{
    //Dump out the image as a PNG file.
    $tmp_file = tempnam(TEMP_DIR, "image") . ".png";
    imagepng($image, $tmp_file);

    //Final image file.
    $tmp_out_file = tempnam(TEMP_DIR, "out") . ".png";

    $x = imagesx($image);
    $y = imagesy($image);

    $cmd = "convert -size {$x}x{$y} xc:none -fill white -draw 'roundRectangle 0,0, {$x} ,{$y}, {$r}, {$r}' {$tmp_file} -compose SrcIn -composite {$tmp_out_file}";
    exec($cmd);

    header("Content-Type: image/png");
    $contents = file_get_contents($tmp_out_file);
    echo $contents;
    exit;
}


Instead of trying to reinvent the wheel use the PHP thumbnailer which will make everything for you:

require 'Thumbnailer.php';

$th=new Thumbnailer("photo.jpg");
$th->thumbFixed(120,90)->round()->save("thumb.jpg");


See the ImageMagick reference. Yes, everything you describe is possible, all the tools are there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜