PDFlib Cookbook

cookbook

images/image_rounded_corners

Place an image with rounded corners.

Download PHP Code  Switch to Java Code  Show Output 

<?php
/*
 * Image with rounded corners:
 * Place an image with rounded corners
 *
 * Get the bounding box of an image and create a clipping path as a rectangle
 * with the image size and with rounded corners. Fit the image into a box
 * with the position and size of the clipping path.
 *
 * Required software: PDFlib/PDFlib+PDI/PPS 9
 * Required data: image file
 */

/* This is where the data files are. Adjust as necessary. */
$searchpath = dirname(__FILE__,3)."/input";
$outfile = "";
$title = "Image with Rounded Corners";

$imagefile = "nesrin.jpg";
$image;
$radius = 50;          // radius of the circle for the rounded corners
$x = 50; $y = 300;     // lower left position of the image

try {
    $p = new pdflib();

    $p->set_option("searchpath={" . $searchpath . "}");

    /* This means we must check return values of load_image() etc. */
    $p->set_option("errorpolicy=return");

    if ($p->begin_document($outfile, "") == 0)
        throw new Exception("Error: " . $p->get_errmsg());

    $p->set_info("Creator", "PDFlib Cookbook");
    $p->set_info("Title", $title);

    /* Load image */
    $image = $p->load_image("auto", $imagefile, "");
    if ($image == 0)
        throw new Exception("Error: " . $p->get_errmsg());

    /* Start a A4 page */
    $p->begin_page_ext(0, 0, "height=a4.height width=a4.width");

    /* Retrieve the image's bounding box as path object */
    $bbox = $p->info_image($image, "boundingbox", 
        "boxsize {495 400} position center fitmethod=meet");

    $p->save();
    /* Use the bounding box path as clipping path */
    $p->draw_path($bbox, $x, $y, "round=" . $radius . " clip close");

    /* Fit the image into a box with the size and start point (x,y) of the
        * clipping path. The image is placed in the center of the box using the
        * fit method "meet" which will scale the image proportionally so that
        * it completely covers the box.
        */
    $p->fit_image($image, $x, $y, 
        "boxsize {495 400 } position center fitmethod=meet");

    /* Restore the previous graphics state (without clipping) and close image */
    $p->restore();
    $p->close_image($image);

    $p->end_page_ext("");
    $p->end_document("");
    $buf = $p->get_buffer();
    $len = strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=image_rounded_corners.pdf");
    print $buf;

} catch (PDFlibException $e) {
    echo("PDFlib exception occurred:\n".
        "[" . $e->get_errnum() . "] " . $e->get_apiname() .
        ": " . $e->get_errmsg() . "\n");
    exit(1);
} catch (Throwable $e) {
    echo("PHP exception occurred: " . $e->getMessage() . "\n");
    exit(1);
}

$p = 0;

?>