Question

A few months ago i wrote the following script to convert an uploaded image with PHP to Retina and non retina images. The iphone app that was working with this script only used PNG images, so i wrote the script to work with PNG's.

$filename = dirname(__FILE__)."/uploads/" . $_FILES['myFile']['name'];
$filename = str_replace('.png', '_retina.png', $filename);
file_put_contents($filename, file_get_contents($_FILES['myFile']['tmp_name']));

$image_info = getimagesize($filename);
$image = imagecreatefrompng($filename);

$width = imagesx($image);
$height = imagesy($image);

$new_width = $width/2.0;
$new_height = $height/2.0;

$new_image = imagecreatetruecolor($new_width, $new_height);

imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$color = imagecolortransparent($new_image, imagecolorallocatealpha($new_image, 0, 0, 0, 127));
imagefill($new_image, 0, 0, $color);

imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

$new_filename = str_replace('_retina.png', '.png', $filename);

imagepng($new_image, $new_filename);

Now i need the same script but then to be used with Jpeg images. Because the iphone app will load images with a higher resolution we chose Jpeg. But i can't figure out how to make that work.

What i've tried so far:

  • Replacing imagecreatefrompng with the jpeg version
  • Replacing imagepng with the jpeg version

Does anybody have a working example or useful link that can set me to the right direction?

Was it helpful?

Solution

I figured out what the problem was about. I assumed jpg php functions could not handle the transparency, so i removed those lines and forgot about them. Apparently it just creates a white background and it does not fail. So the script is as follows:

$filename = dirname(__FILE__)."/uploads/" . $_FILES['myFile']['name'];
$filename = str_replace('.jpg', '_retina.jpg', $filename);
file_put_contents($filename, file_get_contents($_FILES['myFile']['tmp_name']));

$image_info = getimagesize($filename);
$image = imagecreatefromjpeg($filename);

$width = imagesx($image);
$height = imagesy($image);

$new_width = $width/2.0;
$new_height = $height/2.0;

$new_image = imagecreatetruecolor($new_width, $new_height);

imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$color = imagecolortransparent($new_image, imagecolorallocatealpha($new_image, 0, 0, 0, 127));
imagefill($new_image, 0, 0, $color);

imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

$new_filename = str_replace('_retina.jpg', '.jpg', $filename);

imagejpeg($new_image, $new_filename);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top