Lucas
Lucas

Reputation: 1680

How can I set DPI/PPI through an GD resize?

I found solutions here and here using Imagick but I really do not want go though Imagick extension due security issues.

Currently, I'm doing the resize as follow:

list($width, $height) = getimagesize($file_path);

$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($newwidth, $newheight);

//prepare the transparency
imagealphablending($dst, false);
imagesavealpha( $dst , true );
$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);

imagefilledrectangle($dst, 0, 0, $newwidth, $newheight, $transparent);

imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

But it are setting always 72 DPI (overriding even the original file DPI).

There have some way to set DPI using GD?

Upvotes: 0

Views: 1560

Answers (1)

Matey
Matey

Reputation: 1210

It seems PHP GD extension has no way of specifying the DPI directly when writing an image file. You have two options though:

  • Change the #define GD_RESOLUTION 72 in GD source code to your desired value and recompile the GD extension on your own. Be careful, this will have effect on all images saved by GD on your system.
  • Manipulate the binary file (JPEG or PNG?) to change the DPI value in the file header. DPI is only a meta-value, it has no connection to the pixel data.

Which brings me to the question why are you resizing the image if you only need to change the DPI value? Or the other way round - why do you need to change the DPI when you're resizing the image anyway? Is the image used for print?

Upvotes: 1

Related Questions