Image resampling script for png and gifs - php

I have this PHP script that receives an uploaded image. The uploaded image is saved in a temp folder, and then this script resamples the image and saves it to the correct folder. A user can upload either JPG, PNG or GIF files. This script only caters for JPG files though.
How would I modify this script to resize both PNG's and GIF's without losing transparency?
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = $_POST['n'];
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
$new_src = str_replace('/temp','',$_POST['n']);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($dst_r,$new_src,$jpeg_quality);

JPEG images can't have transparent background.
Instead you can make the image based on imagesavealpha():
$targ_w = $targ_h = 150;
$newImage = imagecreatetruecolor($targ_w, $targ_h);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $targ_w, $targ_h, $transparent);
$src = $_POST['n'];
$img_r = imagecreatefromstring(file_get_contents($src));
$img_r_size = getimagesize($src);
$width_r = $img_r_size[0];
$height_r = $img_r_size[1];
if($width_r > $height_r){
$width_ratio = $targ_w / $width_r;
$new_width = $targ_w;
$new_height = $height_r * $width_ratio;
} else {
$height_ratio = $targ_h / $height_r;
$new_width = $width_r * $height_ratio;
$new_height = $targ_h;
}
imagecopyresampled($newImage, $img_r, 0, 0, 0, 0, $new_width, $new_height, $width_r, $height_r);
$new_src = str_replace('/temp','',$_POST['n']);
imagepng($newImage, $new_src);
It will make a PNG from both PNG and GIF (that have transparent background, and resize to 150x150.
This is just an example, as it does not constrain proportions.

I had this problem few months ago and solved it by using code below:
imagealphablending($target_image, false);
imagesavealpha($target_image, true);

Related

resize or crop base64 images using php

I'm uploading images from the pc to a server using this php code
$ImageToLoad=mysql_real_escape_string($_POST['image_attached']);
if($ImageToLoad){
$token=$token;//variable
$ImageToLoad = str_replace('data:image/png;base64,', '', $ImageToLoad);
$ImageToLoad = str_replace('data:image/jpeg;base64,', '', $ImageToLoad);
$ImageToLoad = str_replace(' ', '+', $ImageToLoad);
$fileData = base64_decode($ImageToLoad);
$destino_path="/images/$token/image.png";
file_put_contents($destino_path, $fileData);
}
It works ok.
PROBLEM
I need to know how to resize it/crop them before to store the image in the server. Otherwise it keeps the same size (problem when huge image)
Resizing images can be is a costly operation and should be handled by a specialized library. In the past, the default pointer was ImageMagick's Imagick::resizeImage. However, this package does not work for everybody and other solutions have emerged in the meantime.
I suggest gumlet's php-image-resize. Resizing a base64 encoded image can be as simple as that:
$image = ImageResize::createFromString(base64_decode('R0lGODlhAQABAIAAAAQCBP///yH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=='));
$image->scale(50);
$image->save('image.jpg');
If we want to create a temp image from an image file for resizing, we can use
imagecreatefromjpeg($filename);
or
imagecreatefrompng($filename);
If we want to create a temp image from blob we can use
imagecreatefromstring($blob);
imagecreatefromstring()
So, give this a try:
<?php
$filename = 'folder_name/resized_image.png'; // output file name
$im = imagecreatefromstring($fileData);
$source_width = imagesx($im);
$source_height = imagesy($im);
$ratio = $source_height / $source_width;
$new_width = 300; // assign new width to new resized image
$new_height = $ratio * 300;
$thumb = imagecreatetruecolor($new_width, $new_height);
$transparency = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
imagefilledrectangle($thumb, 0, 0, $new_width, $new_height, $transparency);
imagecopyresampled($thumb, $im, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
imagepng($thumb, $filename, 9);
imagedestroy($im);
?>

Resize image while uploading to amazon s3

I need to resize image to 150 x 150 px and then upload it to Amazon S3
Following is the code:
$image = $_FILES["userImage"]["name"];
$fileTempName = $_FILES['userImage']['tmp_name'];
$new_width = 150;
$new_height = 150;
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromstring(file_get_contents($fileTempName));
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, imagesx($image), imagesy($image));
$newFielName = tempnam(sys_get_temp_dir(), "tempfilename");
imagepng($image_p, $newFielName, 9);
$s3 = new S3(awsAccessKey, awsSecretKey);
//move the file
if ($s3->putObjectFile($fileTempName, "urimages", $newFielName, S3::ACL_PUBLIC_READ)) {
$image_link = 'https://s3-us-west-2.amazonaws.com/urimages/' . $newFielName . '';
$this->Product->saveField('image', $image_link);
}
Following is the link which i receive upon uploading : https://s3-us-west-2.amazonaws.com/urimages/C:/Users/LS/AppData/Local/Temp/9102.tmp
Could be you please help me debug the code
i think issue in path. Please create folder on s3 and make a valid
path according to that folder
https://s3-us-west-2.amazonaws.com/urimages/C:/Users/LS/AppData/Local/Temp/9102.tmp
Example :- Resampling an image proportionally
<?php
// The file
$filename = 'test.jpg';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>

Uploading PNG to Website Server

I have seen loads of other topics and I've tried them all. Can someone please help with why this script won't upload PNG files? Blank PNG image being displayed.
$image = $_FILES['file']['tmp_name'];
$image_name = $_FILES['file']['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$location = "Profiles/{$user}/Picture/{$image_name}";
$new_image = imagecreatetruecolor(100, 100);
$source_image = imagecreatefrompng($image);
imagealphablending($source_image, false);
imagesavealpha($source_image, true);
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, 100, 100, $image_width, $image_height);
imagepng($new_image, '../' . $location, 9);
You're not declaring $image_width or $image-height and you are referencing $image instead of $source_image in imagecopyresampled().
I too was getting a plain white image, but after this I get the expected result:
$image = $_FILES['file']['tmp_name'];
$image_name = $_FILES['file']['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$location = "Profiles/{$user}/Picture/{$image_name}";
$new_image = imagecreatetruecolor(100, 100);
$source_image = imagecreatefrompng($image);
// Get the width & height of the uploaded image.
$image_width = imagesx($source_image);
$image_height = imagesy($source_image);
imagealphablending($source_image, false);
imagesavealpha($source_image, true);
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, 100, 100, $image_width, $image_height);
imagepng($new_image, '../' . $location, 9);

Image transparency in imagepng() and imagegif()

I want to resize 2 types of images (png, gif) with transparent background...
But in png it works well in big size of the original image.
eg. Original file dimension is 150x150
change into 200x200 or exceeding the original size it works well. but in 100x100 it displays
Then the last GIF it doesn't work.
Here my code for png
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
$transparentindex = imagecolorallocatealpha($new_img, 255, 255, 255, 127);
imagefill($new_img, 0, 0, $transparentindex);
imagepng($new_img, $dir);
Here my code for gif
imagegif($new_img, $dir);
I know no PHP, but this seems to do the trick:
#!/usr/local/bin/php -f
<?php
$neww=100;
$newh=100;
// Load original image and get its dimensions
$img = imagecreatefrompng("badge.png");
$w=imagesx($img);
$h=imagesy($img);
// Create output image, and fill with lots of transparency
$out = imagecreatetruecolor($neww,$newh);
imagealphablending($out,false);
$transparentindex = imagecolorallocatealpha($out,0,0,0,127);
imagefill($out,0,0,$transparentindex);
imagesavealpha($out, true);
// Copy original image, reized on top
imagecopyresized($out,$img,0,0,0,0,$neww,$newh,$w,$h);
imagepng($out,"out.png");
?>
Here is a little hack :)
Don't have any other ideas.
It involves a second image (1x1 trasparent gif)
create image
resize
create a transparent background with same size as resized image
use imagecolortransparent() to get the rgb index
imagecopymerge() images
voilĂ 
.
$dir = 'http://i.stack.imgur.com/DbhrJ.png';
$max_w = 50;
$max_h = 50;
// get image size
list($src_w, $src_h) = getimagesize($dir);
if ($src_w > $max_w) {
$ratio = $max_w / $src_w;
$max_w = $src_w * $ratio;
}
else if ($src_h > $max_h) {
$ratio = $max_h / $src_h;
$max_h = $src_h * $ratio;
}
// resize image to $max_w and $max_h, and also save alpha
$src = imagecreatefromstring(file_get_contents($dir));
$new_img = imagecreatetruecolor($max_w, $max_h);
imagealphablending($new_img, false);
imagesavealpha($new_img, true);
imagecopyresampled($new_img, $src, 0, 0, 0, 0, $max_w, $max_h, $src_w, $src_h);
// create a new image with $max_w and $max_h
$maxsize = imagecreatetruecolor($max_w, $max_h);
// add 1x1 gif and resize, then copy over $maxsize
$background = imagecreatefromgif("http://i.imgur.com/atRjCdk.gif"); // transparent 1x1 gif
imagecopyresampled($maxsize, $background, 0, 0, 0, 0, $max_w, $max_h, 1, 1);
// allocate transparency
$transparent = imagecolortransparent($maxsize);
$transparent_index = imagecolorallocate($maxsize, $transparent['red'], $transparent['green'], $transparent['blue']);
imagecolortransparent($maxsize, $transparent_index);
// image copy
imagecopymerge($maxsize, $new_img, 0, 0, 0, 0, $max_w, $max_h, 100);
// save or output
imagegif($maxsize, $path_to_save);
// destroy images
imagedestroy($maxsize);
imagedestroy($new_img);
imagedestroy($background);
imagedestroy($src);

download image from remote source and resize then save

Do any of you know of a good php class I can use to download an image from a remote source, re-size it to 120x120 and save it with a file name of my choosing?
So basically I would have an image at "http://www.site.com/image.jpg" save to my web server "/images/myChosenName.jpg" as a 120x120 pixels.
Thanks
You can try this:
<?php
$img = file_get_contents('http://www.site.com/image.jpg');
$im = imagecreatefromstring($img);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = '120';
$newheight = '120';
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,'/images/myChosenName.jpg'); //save image as jpg
imagedestroy($thumb);
imagedestroy($im);
?>
More information about PHP image function : http://www.php.net/manual/en/ref.image.php
You can resize keeping the ratio of image
$im = imagecreatefromstring($img);
$width_orig = imagesx($im);
$height_orig = imagesy($im);
$width = '800';
$height = '800';
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
If you're looking to have the ability to do this for both jpg and png file formats, here's what helped me:
$imgUrl = 'http://www.example.com/image.jpg';
// or $imgUrl = 'http://www.example.com/image.png';
$fileInfo = pathinfo($imgUrl);
$img = file_get_contents($imgUrl);
$im = imagecreatefromstring($img);
$originalWidth = imagesx($im);
$originalHeight = imagesy($im);
$resizePercentage = 0.5;
$newWidth = $originalWidth * $resizePercentage;
$newHeight = $originalHeight * $resizePercentage;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
if ($fileInfo['extension'] == 'jpg') {
imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagejpeg($tmp, '/img/myChosenName.jpg', -1);
}
else if ($fileInfo['extension'] == 'png') {
$background = imagecolorallocate($tmp , 0, 0, 0);
imagecolortransparent($tmp, $background);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
imagepng($tmp, '/img/myChosenName.png');
}
else {
// This image is neither a jpg or png
}
imagedestroy($tmp);
imagedestroy($im);
The extra code on the png side of things ensures that the saved image contains any and all transparent sections.

Categories