David
David

Reputation: 755

TCPDF Image aspect ratio issue

I have an issue with TCPDF Image inserting.

enter image description here

Here's the code i'm using :

$this->Image($this->data['logo'], PDF_MARGIN_LEFT, 5, 60, 20, '', '', 'M', true);

I've set the resize at true, but the TCPDF library do not respect image ratio.

How can I force preserving image ratio ?

For information I'm using TCPDF 6.2.8 (2015-04-29).

Thanks for your support, David.

Upvotes: 2

Views: 6043

Answers (3)

TRiG
TRiG

Reputation: 10643

I built on David’s answer to create a function. Pass it the width, the height, and the path to the image. It reads the image size and then sets either $w or $h to zero, as appropriate. It’s exactly the same idea as David’s code, but his hardcodes the specific image ratio for his purposes, while this version is more generic.

function imageBox($file, $w, $h)
{
    if (!$w or !$h) {
        // If the input has set one of these to zero, it should be calling TCPDF
        // image directly.
        throw new Exception('You must provide a value for both width and height');
    }
    // First, we grab the width and height of the image.
    list($image_w, $image_h) = getimagesize($file);

    // Constrain the image to be within a certain boundary by doing maths.
    if (($w / $h) > ($image_w / $image_h)) {
        $w = 0;
    } else {
        $h = 0;
    }

    return array($w, $h);
}

Upvotes: 0

David
David

Reputation: 755

Here's the solution I found :

    if ('' != $this->data['logo'] && is_file($this->data['logo'])) {
        // select only one constraint : height or width. 60x20 image emplacement => ratio = 3 (60/20)
        list($image_w, $image_h) = getimagesize($this->data['logo']);
        if (3 > $image_w / $image_h) list($w, $h) = array(0, 20);
        else list($w, $h) = array(60, 0);

        $this->Image($this->data['logo'], PDF_MARGIN_LEFT, 5, $w, $h, '', '', 'M');
    }

I've found the image emplacement ratio (60/20=3), I compared it to the image ratio and I choose between set the width or the heigh.

Thanks to JamesG to help me to find my solution.

David.

Upvotes: 6

JamesG
JamesG

Reputation: 4309

If you want to preserve the image's aspect ratio, just set either the width parameter or the height parameter to zero.

In your example I can see that you've set the width to 60 and the height to 20. Try setting the width to 0 and leaving the height at 20 - I think you will get a good result. And you can probably leave off the resize parameter too.

Upvotes: 1

Related Questions