Make a move_uploaded_file after imagecopyresampled in PHP - php

I'm trying to resize image in PHP.
But after all this work how can I use the move_uploaded_file function to move the tmp_file file to it final directory ?
Here's my code:
$image = imagecreatefromjpeg($_FILES['REG_Image']['tmp_name']);
// Target dimensions
$max_width = 1014;
$max_height = 768;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
if($old_width > $max_height) {
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
}
Thanks.

You can use imagejpeg instead after
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width,$new_height, $old_width, $old_height);
imagejpeg($new, "/path/to/image.jpeg");
this will save the image to the new path that you have specified as image.jpeg. You can use imagepng as well if you want a PNG image as output.

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);
?>

Why is my scaled image always black?

I am making thumbnails and for some reason, my output is the correct size, but always black. I saw another Stack Overflow post on a similar topic but in his case, he was passing parameters incorrectly.
I am capturing an image from a video camera and then using this code:
$data = base64_decode($data); // the data will be saved to the db
$image = imagecreatefromstring($data); // need to create an image to grab the width and height
$img_width = imagesx($image);
$img_height = imagesy($image);
// calculate thumbnail size
$new_height = 100;
$new_width = floor( $img_width * ( 100 / $img_height ) );
// create a new temporary image
$new_image = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
$url = IMGDIR.$imgname;
$thumburl = IMGDIR."thumb/".$imgname;
// save image and thumb to disk
imagepng($image,$url);
imagepng($new_image,$thumburl);
The result I get is both files saved to the proper directories, both the proper size, but the thumbnail is all black. There must be something simple I am missing. Any ideas?
Remember that PNG files have alpha channels. So be sure to use imagealphablending and imagesavealpha. Here they are integrated into your code.
$data = base64_decode($data); // the data will be saved to the db
$image = imagecreatefromstring($data); // need to create an image to grab the width and height
$img_width = imagesx($image);
$img_height = imagesy($image);
// calculate thumbnail size
$new_height = 100;
$new_width = floor( $img_width * ( 100 / $img_height ) );
// create a new temporary image
$new_image = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
$url = IMGDIR . $imgname;
$thumburl = IMGDIR . "thumb/" . $imgname;
// Set the image alpha blending settings.
imagealphablending($image, false);
imagealphablending($new_image, false);
// Set the image save alpha settings.
imagesavealpha($image, true);
imagesavealpha($new_image, true);
// save image and thumb to disk
imagepng($image,$url);
imagepng($new_image,$thumburl);
Try saving your image's alpha channel with imagesavealpha and passing true for the 2nd argument
imagesavealpha($image, true);
imagepng($image,$url);
imagesavealpha($new_image, true);
imagepng($new_image,$thumburl);

PNG - preserving transparency

I'm trying to redesign my site so that my original square, tile-based rendering of images can be more of a cutout of the image... to get rid of that grid pattern.
Here's how it looked originally...
Here's a rough mock-up of what I'm going for:
So I resaved an image thumbnail with a transparent background... I just want the dog to show, and the square is transparent which will show the site's background underneath.
Yet when I render it on the page, it has this black background.
I've checked my CSS to see if there is some sort of img class, or class for the rendered comics... or even the bootstrap to see where there may be a background-color being assigned to black (and also searched for hex code 000000), but didn't find one...
Then I found that it had to do with the way my thumbnailing script was resampling the png... Since I'm getting a black background for the supposedly transparent image, I blame imagecreatetruecolor() which returns an image identifier representing a black image of the specified size..
I tried following Cheekysoft's question here about preserving transparency after resampling... but it didn't work... with his two main points being:
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );
I found if I put $img = imagecreatefrompng($image_file); before I resize/resample it, it displays transparently... which is what I want... but not after I resample it.
Thumbnailer.php code:
<?php
#Appreciation goes to digifuzz (http://www.digifuzz.net) for help on this
$image_file = $_GET['img']; //takes in full path of image
$MAX_WIDTH = $_GET['mw'];
$MAX_HEIGHT = $_GET['mh'];
global $img;
//Check for image
if(!$image_file || $image_file == "") {
die("NO FILE.");
}
//If no max width, set one
if(!$MAX_WIDTH || $MAX_WIDTH == "") {
$MAX_WIDTH="100";
}
//if no max height, set one
if(!$MAX_HEIGHT || $MAX_HEIGHT == "") {
$MAX_HEIGHT = "100";
}
$img = null;
//create image file from 'img' parameter string
if( preg_match('/\.jpg$/',$image_file) || preg_match('/\.jpeg$/',$image_file) ){
$img = imagecreatefromjpeg($image_file);
} else {
$img = imagecreatefrompng($image_file);
}
//if image successfully loaded...
if($img) {
//get image size and scale ratio
$width = imagesx($img);
$height = imagesy($img);
//takes min value of these two
$scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height);
//if desired new image size is less than original, output new image
if($scale < 1) {
$new_width = floor($scale * $width);
$new_height = floor($scale * $height);
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//copy and resize old image to new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//replace actual image with new image
$img = $tmp_img;
}
}
//set the content type header
header('Content-Type: image/png', true);
imagealphablending( $img, false );
imagesavealpha( $img, true );
imagepng($img);
imagedestroy($img);
?>
Can anyone help?
Thanks!
You need to call imagealphablending() on your destination image BEFORE you resample/resize the image:
//copy and resize old image to new image
imagealphablending($tmp_img, false);
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// ...
You placed alphablending and traparent code well below after creating image. Just place them before the your createresample line and transparent image with image that created by imagecreatefrompng.
imagealphablending( $tmp_img, false );
imagesavealpha( $tmp_img, true );
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
Or you can Try following
$img = ImageCreateFromPNG($image_file);
$tmp_img = imagecreatetruecolor($new_width,$new_height);
imagecolortransparent($tmp_img, imagecolorallocate($tmp_img, 0, 0, 0));
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

Proportional image resizing

i want to resize uploaded images to width: 180px with proportional height. Is there any classes to do this?
Thanks for help!
I think this question can use an answer with an actual code example. The code below shows you how you to resize an image inside a directory uploaded, and save the resized image in the folder resized.
<?php
// the file
$filename = 'uploaded/my_image.jpg';
// the desired width of the image
$width = 180;
// content type
header('Content-Type: image/jpeg');
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
$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, 'resized/my_image.jpg', 80);
?>
First you need to get the current image dimensions:
$width = imagesx($image);
$height = imagesy($image);
Then calculate the scaling factor:
$scalingFactor = $newImageWidth / $width;
When having the scaling factor just calculate the new height of the image:
$newImageHeight = $height * $scalingFactor;
Then just create the new image;
$newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
Probably these snippets will help:
http://www.codeslices.net/snippets/resize-scale-image-proportionally-to-given-width-in-php http://www.codeslices.net/snippets/resize-scale-image-proportionally-in-php
at least they worked for me.
you may use imagecopyresampled php function. new sizes you also can calculate.
User jquery plugin JCrop, and set its aspect ratio for the image...
Check this link for details:
http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/

Creat temporay thumb image in PHP

Hey, i am looking for a method to creat temporay thumb file in PHP. Is there any way not to store the image on the server or delete them right after. What I am looking for is a solution like this: http://www.dig2go.com/index.php?shopbilde=772&type=1&size=120
Could some one explain to me how the php code behind this works? For the moment are am using a php code I found on the net for creation of thumb nails:
function createThumb($pathToImage, $pathToThumb, $thumbWidth, $thumbHeight, $saveNameAndPath)
{
if(!file_exists($pathToImage))
return false;
else
{
//Load image and size
$img = imagecreatefromjpeg($pathToImage);
$width = imagesx($img);
$height = imagesy($img);
//Calculate the size of thumb
$new_width = $thumbWidth;
$new_height = $thumbHeight; //floor($height * ($thumbWidth / $width));
//Make the new thumb
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//Copy the old image and calculate the size
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//Save the thumb to jpg
imagejpeg($tmp_img, $saveNameAndPath);
return true;
}
}
function createThumb($pathToImage, $pathToThumb, $thumbWidth, $thumbHeight, $saveNameAndPath)
{
if(!file_exists($pathToImage))
return false;
else
{
//Load image and size
$img = imagecreatefromjpeg($pathToImage);
$width = imagesx($img);
$height = imagesy($img);
//Calculate the size of thumb
$new_width = $thumbWidth;
$new_height = $thumbHeight; //floor($height * ($thumbWidth / $width));
//Make the new thumb
$tmp_img = imagecreatetruecolor($new_width, $new_height);
//Copy the old image and calculate the size
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// sets the header and creates the temporary thumbnail
// ideal for ajax requests / <img> elements
header("Content-type: image/jpeg");
imagejpeg($img);
return true;
}
}
You can use ini_set("memory_limit","12M"); to set memory limit in your script. You can extend it from 12 megabytes to maximum memory you have.
Generally 64M is good.

Categories