Skip to content

Instantly share code, notes, and snippets.

@slivero
Created July 23, 2012 15:41
Show Gist options
  • Save slivero/3164297 to your computer and use it in GitHub Desktop.
Save slivero/3164297 to your computer and use it in GitHub Desktop.
Resampling a JPEG image in PHP using GD (not imagemagick)
<?php
/**
* Class used for resampling images
*/
class Resampler
{
/**
* Resample an image
*
* The image is returned as a string ready to be saved, it is not converteed back to a resource
* as that would just be unnecessary
*
* @param resource $image Resource storing JPEG image
* @param integer $dpi The dpi the image should be resampled at
* @return string Resampled JPEG image as a string
*/
function resample($image, $height, $width, $dpi = 300)
{
if(!$image)
{
throw new \Exception('Attempting to resample an empty image');
}
if(gettype($image) !== 'resource')
{
throw new \Exception('Attempting to resample something which is not a resource');
}
//Use truecolour image to avoid any issues with colours changing
$tmp_img = imagecreatetruecolor($width, $height);
//Resample the image to be ready for print
if(!imagecopyresampled ($tmp_img , $image , 0 , 0 ,0 , 0 , $width , $height , imagesx($image) , imagesy($image)))
{
throw new \Exception("Unable to resample image");
}
//Massive hack to get the image as a jpeg string but there is no php function which converts
//a GD image resource to a JPEG string
ob_start();
imagejpeg($tmp_img, "", 100);
$image = ob_get_contents();
ob_end_clean();
//change the JPEG header to 300 pixels per inch
$image = substr_replace($image, pack("Cnn", 0x01, 300, 300), 13, 5);
return $image;
}
}
@guirip
Copy link

guirip commented Dec 15, 2014

Hello
Nice work, but the dpi param (which brought me here) is never used.

Copy link

ghost commented Jan 21, 2015

guirip said: "Hello Nice work, but the dpi param (which brought me here) is never used."

// Mistake:
$image = substr_replace($image, pack("Cnn", 0x01, 300, 300), 13, 5);

// Correction:
$image = substr_replace($image, pack("Cnn", 0x01, $dpi, $dpi), 13, 5);

@Frankobingen
Copy link

Working really good - thanks!

@I-CRE8
Copy link

I-CRE8 commented Sep 10, 2015

This was really helpful in solving an issue I was having, thanks for putting this code into the public domain

@maulikvora
Copy link

Nice work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment