Basically an Image is created on a canvas html5 element and saved as image on server using the following code
<?php
$upload_dir = "uploads/";
$img = $_POST['hidden_data'];
$imageID = $_POST['imageID'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . "gillette_" . $imageID . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I want to save a thumbnail version 100X100 px but prefer to do it straight from the stream. Any help would be greatly appreciated
the following code for resizing and saving image did not work trying to use imagecreatefromstring
<?php
############ Configuration ##############
$thumb_square_size = 100; //Thumbnails will be cropped to 200x200 pixels
$max_image_size = 520; //Maximum image size (height and width)
$thumb_prefix = "small_"; //Normal thumb Prefix
$destination_folder = 'uploads/'; //upload directory ends with / (slash)
$jpeg_quality = 90; //jpeg quality
##########################################
$upload_dir = "uploads/";
$img = $_POST['hidden_data'];
$imageID = $_POST['imageID'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . "gillette_" . $imageID . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
$im = imagecreatefromstring($data);
if($im){
$new_file_name = $imageID . ".png";
$thumb_save_folder = $destination_folder . $thumb_prefix . $new_file_name;
//call crop_image_square() function to create square thumbnails
if(!crop_image_square($im, $thumb_save_folder, "png", $thumb_square_size, 520, 382, $jpeg_quality))
{
die('Error Creating thumbnail');
}
imagedestroy($im); //freeup memory
}
##### This function corps image to create exact square, no matter what its original size! ######
function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
if( $image_width > $image_height )
{
$y_offset = 0;
$x_offset = ($image_width - $image_height) / 2;
$s_size = $image_width - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($image_height - $image_width) / 2;
$s_size = $image_height - ($y_offset * 2);
}
$new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
##### Saves image resource to file #####
function save_image($source, $destination, $image_type, $quality){
switch(strtolower($image_type)){//determine mime type
case 'image/png':
imagepng($source, $destination); return true; //save png file
break;
case 'image/gif':
imagegif($source, $destination); return true; //save gif file
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($source, $destination, $quality); return true; //save jpeg file
break;
default: return false;
}
}
?>
problem solved:
code works now. image type was supposed to be the whole mime type - image/png and not just png
this is the fixed code, hope it helps someone:
<?php
############ Configuration ##############
$thumb_square_size = 100; //Thumbnails will be cropped to 200x200 pixels
$max_image_size = 520; //Maximum image size (height and width)
$thumb_prefix = "small_"; //Normal thumb Prefix
$destination_folder = 'uploads/'; //upload directory ends with / (slash)
$jpeg_quality = 90; //jpeg quality
##########################################
$upload_dir = "uploads/";
$img = $_POST['hidden_data'];
$imageID = $_POST['imageID'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . "gillette_" . $imageID . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
$im = imagecreatefromstring($data);
if($im){
$new_file_name = $imageID . ".png";
$thumb_save_folder = $destination_folder . $thumb_prefix . $new_file_name;
//call crop_image_square() function to create square thumbnails
if(!crop_image_square($im, $thumb_save_folder, "image/png", $thumb_square_size, 520, 382, $jpeg_quality))
{
die('Error Creating thumbnail');
}
imagedestroy($im); //freeup memory
}
##### This function corps image to create exact square, no matter what its original size! ######
function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
if( $image_width > $image_height )
{
$y_offset = 0;
$x_offset = ($image_width - $image_height) / 2;
$s_size = $image_width - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($image_height - $image_width) / 2;
$s_size = $image_height - ($y_offset * 2);
}
$new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
##### Saves image resource to file #####
function save_image($source, $destination, $image_type, $quality){
switch(strtolower($image_type)){//determine mime type
case 'image/png':
imagepng($source, $destination); return true; //save png file
break;
case 'image/gif':
imagegif($source, $destination); return true; //save gif file
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($source, $destination, $quality); return true; //save jpeg file
break;
default: return false;
}
}
?>
Related
I tried 2 implementations, shown below. Both are working well but when I tried to mix them it is not working anymore.
$output['status']=FALSE;
set_time_limit(0);
$allowedImageType = array("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/x-png" );
if ($_FILES['image_file_input']["error"] > 0) {
$output['error']= "File Error";
}
elseif (!in_array($_FILES['image_file_input']["type"], $allowedImageType)) {
$output['error']= "Invalid image format";
}
elseif (round($_FILES['image_file_input']["size"] / 1024) > 4096) {
$output['error']= "Maximum file upload size is exceeded";
} else {
$temp_path = $_FILES['image_file_input']['tmp_name'];
$file = pathinfo($_FILES['image_file_input']['name']);
$fileType = $file["extension"];
$photo_name = $productname.'-'.$member_id."_".time();
$fileName1 = $photo_name . '-125x125' . ".jpg";
$fileName2 = $photo_name . '-250x250' . ".jpg";
$fileName3 = $photo_name . '-500x500' . ".jpg";
$small_thumbnail_path = "uploads/large/";
createFolder($small_thumbnail_path);
$small_thumbnail = $small_thumbnail_path . $fileName1;
$medium_thumbnail_path = "uploads/large/";
createFolder($medium_thumbnail_path);
$medium_thumbnail = $medium_thumbnail_path . $fileName2;
$large_thumbnail_path = "uploads/large/";
createFolder($large_thumbnail_path);
$large_thumbnail = $large_thumbnail_path . $fileName3;
$thumb1 = createThumbnail($temp_path, $small_thumbnail,$fileType, 125, 125 );
$thumb2 = createThumbnail($temp_path, $medium_thumbnail, $fileType, 250, 250);
$thumb3 = createThumbnail($temp_path, $large_thumbnail,$fileType, 500, 500);
if($thumb1 && $thumb2 && $thumb3) {
$output['status']=TRUE;
$output['small']= $small_thumbnail;
$output['medium']= $medium_thumbnail;
$output['large']= $large_thumbnail;
}
}
echo json_encode($output);
Function File
function createFolder($path)
{
if (!file_exists($path)) {
mkdir($path, 0755, TRUE);
}
}
function createThumbnail($sourcePath, $targetPath, $file_type, $thumbWidth, $thumbHeight){
$source = imagecreatefromjpeg($sourcePath);
$width = imagesx($source);
$height = imagesy($source);
$tnumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($tnumbImage, $source, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
if (imagejpeg($tnumbImage, $targetPath, 90)) {
imagedestroy($tnumbImage);
imagedestroy($source);
return TRUE;
} else {
return FALSE;
}
}
Aspect ratio code, which is another one I tried to mix this code. But I was unsuccessful
$fn = $_FILES['image']['tmp_name'];
$size = getimagesize($fn);
$ratio = $size[0]/$size[1]; // width/height
$photo_name = $productname.'-'.$member_id."_".time();
{
if( $ratio > 1) {
$width1 = 500;
$height1 = 500/$ratio;
}
else {
$width1 = 500*$ratio;
$height1 = 500;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width1,$height1);
$fileName3 = $photo_name . '-500x500' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width1,$height1,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName3); // adjust format as needed
imagedestroy($dst);
if( $ratio > 1) {
$width2 = 250;
$height2 = 250/$ratio;
}
else {
$width2 = 250*$ratio;
$height2 = 250;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width2,$height2);
$fileName2 = $photo_name . '-250x250' . ".jpg";
imagecopyresampled($dst,$src,0,0,0,0,$width2,$height2,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$fileName2); // adjust format as needed
imagedestroy($dst);
}
What I need is to save my image after resizing but in second code there is no condition check, and I can't get image upload folder path. That's why I need to merge these 2 codes.
Basically I need need to save my image in 3 size formats: 500x500,250x250 and 125x125. Width is fixed, but height is set as per aspect ratio and set upload folder and condition in second code block.
Try this thumbnail function, which takes your source image resource and thumbnail size, and returns a new image resource for the thumbnail.
function createThumbnail($src, int $width = 100, int $height = null) {
// Ensure that src is a valid gd resource
if (!(is_resource($src) && 'gd' === get_resource_type($src))) {
throw new InvalidArgumentException(
sprintf("Argument 1 of %s expected type resource(gd), %s supplied", __FUNCTION__, gettype($src))
);
}
// Extract source image width, height and aspect ratio
$source_width = imagesx($src);
$source_height = imagesy($src);
$ratio = $source_width / $source_height;
// We know that width is always supplied, and that height can be null
// We must solve height according to aspect ratio if null is supplied
if (null === $height) {
$height = round($width / $ratio);
}
// Create the thumbnail resampled resource
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, $source_width, $source_height);
return $thumb;
}
Given your code above, you can now use the function like this
// Get uploaded file information as you have
// Create your source resource as you have
$source = imagecreatefromstring(file_get_contents($fn));
// Create thumbnails and save + destroy
$thumb = createThumbnail($source, 500);
imagejpeg($thumb, $thumb500TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 250);
imagejpeg($thumb, $thumb250TargetPath, 90);
imagedestroy($thumb);
$thumb = createThumbnail($source, 125);
imagejpeg($thumb, $thumb125TargetPath, 90);
imagedestroy($thumb);
// Don't forget to destroy the source resource
imagedestroy($source);
So I'm not sure what I'm doing wrong, I thought I had this working perfectly until I uploaded a PNG with a transparent background, and it saved after with a black background. Can anyone point out what I'm doing wrong? Here is my image class and upload code. I thought the 'imagecreatefrompng' section was what would keep the transparency, but maybe I'm wrong or doing it wrong?
Image Class
<?php
ini_set("memory_limit","50M");
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
if(save_image($source, $destination, $image_type, $quality)){
return true;
}
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
imagealphablending($new_canvas,true);
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
save_image($new_canvas, $destination, $image_type, $quality); //save resized image
}
return true;
}
function thumb_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
if(save_image($source, $destination, $image_type, $quality)){
return true;
}
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
imagealphablending($new_canvas,true);
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
save_image($new_canvas, $destination, $image_type, $quality); //save resized image
}
return true;
}
##### This function corps image to create exact square, no matter what its original size! ######
function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
if( $image_width > $image_height )
{
$y_offset = 0;
$x_offset = ($image_width - $image_height) / 2;
$s_size = $image_width - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($image_height - $image_width) / 2;
$s_size = $image_height - ($y_offset * 2);
}
$new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
imagealphablending($new_canvas,true);
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
##### Saves image resource to file #####
function save_image($source, $destination, $image_type, $quality){
switch(strtolower($image_type)){//determine mime type
case 'image/png':
imagepng($source, $destination); return true; //save png file
break;
case 'image/gif':
imagegif($source, $destination); return true; //save gif file
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($source, $destination, $quality); return true; //save jpeg file
break;
default: return false;
}
}
?>
Here is the code to upload.
if(isset($_POST['addImages'])) {
$valid_formats = array("jpg", "jpeg", "png", "gif", "bmp", "JPG", "JPEG", "PNG", "GIF", "BMP");
$max_file_size = 50971520; //50mb
$path = "images/media/"; // Upload directory
$count = 0;
$thumb_square_size = 300; //Thumbnails will be cropped
$max_image_size = 1200; //Maximum image size (height and width)
$thumb_prefix = "_thumb"; //Normal thumb Prefix
$destination_folder = 'images/media/'; //upload directory ends with / (slash)
$jpeg_quality = 90; //jpeg quality
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $foto => $name) {
if ($_FILES['files']['error'][$foto] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$foto] == 0) {
if ($_FILES['files']['size'][$foto] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else { // No error found!
$image_name = $name; //file name
$image_size = $_FILES['files']['size'][$foto]; //file size
$image_temp = $_FILES['files']['tmp_name'][$foto]; //file temp
$image_size_info = getimagesize($image_temp); //get image size
if($image_size_info){
$image_width = $image_size_info[0]; //image width
$image_height = $image_size_info[1]; //image height
$image_type = $image_size_info['mime']; //image type
} else {
die("Make sure image file is valid!");
}
//switch statement below checks allowed image type as well as creates new image from given file.
switch($image_type){
case 'image/png':
$image_res = imagecreatefrompng($image_temp);
imageAlphaBlending($image_res, true);
imageSaveAlpha($image_res, true);
break;
case 'image/gif':
$image_res = imagecreatefromgif($image_temp); break;
case 'image/jpeg': case 'image/pjpeg':
$image_res = imagecreatefromjpeg($image_temp); break;
default:
$image_res = false;
}
if($image_res){
//Get file extension and name to construct new file name
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]); //image extension
$image_name_only = strtolower($image_info["filename"]);//file name only, no extension
$dateRec = date('d-M-Y-h-i-s');
//create a random name for new image (Eg: fileName_293749.jpg) ;
$new_file_name = $dateRec. '_' . rand(0, 9999999999);
//folder path to save resized images and thumbnails
$thumb_save_folder = $destination_folder . $new_file_name . $thumb_prefix . '.' . $image_extension ;
$image_save_folder = $destination_folder . $new_file_name. '.' . $image_extension;
//call normal_resize_image() function to proportionally resize image
if(normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality)) {
//call crop_image_square() function to create square thumbnails
if(!thumb_resize_image($image_res, $thumb_save_folder, $image_type, $thumb_square_size, $image_width, $image_height, $jpeg_quality)) {
die('Error Creating thumbnail');
}
}
}
$post_img = $new_file_name.'.'.$image_extension;
$post_img_thumb = $new_file_name.$thumb_prefix.'.'.$image_extension;
$stmt = $mysqli->prepare('INSERT INTO media_images(image, image_thumb, members_id) VALUES (?,?,?)');
$stmt->bind_param('ssi', $post_img, $post_img_thumb, $members_id);
$stmt->execute();
$stmt->close();
$count++;
}
}
}
$MEMUS = memory_get_usage();
ob_start();
header("Location: media.php");
}
You need to enable alpha and save the setting
case 'image/png':
$image_res = imagecreatefrompng($image_temp);
imageAlphaBlending($image_res, true);
imageSaveAlpha($image_res, true);
break;
Your issue is fixed with the following.
function resizeImage($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality) {
//RETURN FALSE IF NOTHING TO RESIZE
if($image_width <= 0 || $image_height <= 0){return false;}
//CHECK IF SMALLER THAN THE MAX SIZES
if($image_width <= $max_size && $image_height <= $max_size) { //IF SMALLER THAN MAX SIZES
$new_width = $image_width;
$new_height = $image_height;
} else { //ELSE CONSTRUCT PROPORTIONAL SIZE OF NEW IMAGE
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
}
$new_canvas = imagecreatetruecolor($new_width, $new_height);
$black = imagecolorallocate($new_canvas, 0, 0, 0);
imagecolortransparent($new_canvas, $black);
imagealphablending($new_canvas,false);
imagesavealpha($new_canvas, true);
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
$this->save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
//Resize Image Normal
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality) {
//RETURN FALSE IF NOTHING TO RESIZE
if($image_width <= 0 || $image_height <= 0){return false;}
//CHECK IF SMALLER THAN THE MAX SIZES
if($image_width <= $max_size && $image_height <= $max_size) { //IF SMALLER THAN MAX SIZES
$new_width = $image_width;
$new_height = $image_height;
} else { //ELSE CONSTRUCT PROPORTIONAL SIZE OF NEW IMAGE
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
}
$new_canvas = imagecreatetruecolor($new_width, $new_height);
$black = imagecolorallocate($new_canvas, 0, 0, 0);
imagecolortransparent($new_canvas, $black);
imagealphablending($new_canvas,false);
imagesavealpha($new_canvas, true);
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
$this->save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
Let me know if that works. Might need some tweaking for you.
You have to use imagealphablending(). Put imagealphablending($new_canvas,true); after your imagecreatetruecolor command.
You need to use imagealphablending any time you create an image or layer as well. So in your upload you'll use it after your imagecreatefromX switch and after your imagecopyresampled calls as well.
So I know this question has been asked before, but I'm having trouble understanding how to implement the way to prevent an image from loosing it's transparent backgrounds.
My script allows me to set up a way to create thumbnails, and resize the uploaded image.
So here is my code below, can someone help me? Please and thank you! :)
Resize Function:
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
if(save_image($source, $destination, $image_type, $quality)){
return true;
}
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
save_image($new_canvas, $destination, $image_type, $quality); //save resized image
}
return true;
}
function thumb_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
if(save_image($source, $destination, $image_type, $quality)){
return true;
}
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
save_image($new_canvas, $destination, $image_type, $quality); //save resized image
}
return true;
}
##### This function corps image to create exact square, no matter what its original size! ######
function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
if( $image_width > $image_height )
{
$y_offset = 0;
$x_offset = ($image_width - $image_height) / 2;
$s_size = $image_width - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($image_height - $image_width) / 2;
$s_size = $image_height - ($y_offset * 2);
}
$new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
##### Saves image resource to file #####
function save_image($source, $destination, $image_type, $quality){
switch(strtolower($image_type)){//determine mime type
case 'image/png':
imagepng($source, $destination); return true; //save png file
break;
case 'image/gif':
imagegif($source, $destination); return true; //save gif file
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($source, $destination, $quality); return true; //save jpeg file
break;
default: return false;
}
}
Here is the upload code:
$sm_square_size = 300; //will ! be cropped
$md_square_size = 600; //will ! be cropped
$max_image_size = 1200; //Maximum image size (height and width)
$lg_prefix = "_lg"; //Large thumb Prefix
$md_prefix = "_md"; //Medium thumb Prefix
$sm_prefix = "_sm"; //Small thumb Prefix
$destination_folder = 'images/post_images/'; //upload directory ends with / (slash)
$jpeg_quality = 90; //jpeg quality
$image_name = $_FILES['image_file']['name']; //file name
//IF IMAGE UPLOADED
if($image_name != "") {
$image_size = $_FILES['image_file']['size']; //file size
$image_temp = $_FILES['image_file']['tmp_name']; //file temp
$image_size_info = getimagesize($image_temp); //get image size
if($image_size_info){
$image_width = $image_size_info[0]; //image width
$image_height = $image_size_info[1]; //image height
$image_type = $image_size_info['mime']; //image type
} else {
die("Make sure image file is valid!");
}
//switch statement below checks allowed image type
//as well as creates new image from given file
switch($image_type){
case 'image/png':
$image_res = imagecreatefrompng($image_temp); break;
case 'image/gif':
$image_res = imagecreatefromgif($image_temp); break;
case 'image/jpeg': case 'image/pjpeg':
$image_res = imagecreatefromjpeg($image_temp); break;
default:
$image_res = false;
}
if($image_res){
//Get file extension and name to construct new file name
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]); //image extension
$image_name_only = strtolower($image_info["filename"]);//file name only, no extension
$dateRec = date('d-M-Y-h-i-s');
//create a random name for new image (Eg: fileName_293749.jpg) ;
$new_file_name = $dateRec. '_' . rand(0, 9999999999);
//folder path to save resized images and thumbnails
$thumb_save_folder = $destination_folder.$new_file_name.$sm_prefix.'.'.$image_extension;
$medium_save_folder = $destination_folder.$new_file_name.$md_prefix.'.'.$image_extension;
$large_save_folder = $destination_folder.$new_file_name.$lg_prefix.'.'.$image_extension;
//call normal_resize_image() function to proportionally resize image
if(normal_resize_image($image_res, $large_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality)) {
//call crop_image_square() function to create square thumbnails
if(!thumb_resize_image($image_res, $thumb_save_folder, $image_type, $sm_square_size, $image_width, $image_height, $jpeg_quality))
{ die('Error Creating thumbnail'); }
if(!thumb_resize_image($image_res, $medium_save_folder, $image_type, $md_square_size, $image_width, $image_height, $jpeg_quality))
{ die('Error Creating thumbnail'); }
$post_img_lg_New = $new_file_name.$lg_prefix.'.'.$image_extension;
$post_img_md_New = $new_file_name.$md_prefix.'.'.$image_extension;
$post_img_sm_New = $new_file_name.$sm_prefix.'.'.$image_extension;
$stmt = $mysqli->prepare('UPDATE HERE');
$stmt->bind_param('is', $results);
$stmt->execute();
$stmt->close();
}
}
//IF NO IMAGE UPLOADED
}
See my answer here:
Trouble keeping transparency with upload script
I posted the answer below here too:
function resizeImage($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality) {
//RETURN FALSE IF NOTHING TO RESIZE
if($image_width <= 0 || $image_height <= 0){return false;}
//CHECK IF SMALLER THAN THE MAX SIZES
if($image_width <= $max_size && $image_height <= $max_size) { //IF SMALLER THAN MAX SIZES
$new_width = $image_width;
$new_height = $image_height;
} else { //ELSE CONSTRUCT PROPORTIONAL SIZE OF NEW IMAGE
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
}
$new_canvas = imagecreatetruecolor($new_width, $new_height);
$black = imagecolorallocate($new_canvas, 0, 0, 0);
imagecolortransparent($new_canvas, $black);
imagealphablending($new_canvas,false);
imagesavealpha($new_canvas, true);
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
$this->save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
//Resize Image Normal
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality) {
//RETURN FALSE IF NOTHING TO RESIZE
if($image_width <= 0 || $image_height <= 0){return false;}
//CHECK IF SMALLER THAN THE MAX SIZES
if($image_width <= $max_size && $image_height <= $max_size) { //IF SMALLER THAN MAX SIZES
$new_width = $image_width;
$new_height = $image_height;
} else { //ELSE CONSTRUCT PROPORTIONAL SIZE OF NEW IMAGE
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
}
$new_canvas = imagecreatetruecolor($new_width, $new_height);
$black = imagecolorallocate($new_canvas, 0, 0, 0);
imagecolortransparent($new_canvas, $black);
imagealphablending($new_canvas,false);
imagesavealpha($new_canvas, true);
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
$this->save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
I am using php and js for uploading images to a folder. I installed XAMPP and everything worked in localhost. Later, I uploaded my code to a server, changed the paths but it does not work.
I checked the paths in my error.log file and they are OK, also made permissions to 777 and this is the error that it shows:
"PHP Warning: imagejpeg(): Unable to open './uploads/Cartas/imagen_5923239258.jpg' for writing: No such file or directory in /ImageUploader/processupload.php on line 152"
My line 152 is the next one:
imagejpeg($source, $destination, $quality); return true;
My php code is here:
<?php
include '../php/connectionData.php';
$mytype=$_REQUEST['type'];
$updating=$_REQUEST['edit'];
global $image_save_folder;
############ Configuration ##############
$thumb_square_size = 200; //Thumbnails will be cropped to 200x200 pixels
$max_image_size = 500; //Maximum image size (height and width)
$thumb_prefix = "thumb_"; //Normal thumb Prefix
$destination_folder = './ImageUploader/uploads/'.$mytype."/";
//$destination_folder = 'C:/xampp/htdocs/pfc/ImageUploader/uploads/'.$mytype."/"; //old working directory in
$jpeg_quality = 90; //jpeg quality
##########################################
error_log("Destination folder: ".$destination_folder);
//continue only if $_POST is set and it is a Ajax request
if(isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$access=1;
// check $_FILES['ImageFile'] not empty
if(!isset($_FILES['image_file']) || !is_uploaded_file($_FILES['image_file']['tmp_name'])){
$access=0;
}
if ($access){
//uploaded file info we need to proceed
$image_name = $_FILES['image_file']['name']; //file name
$image_size = $_FILES['image_file']['size']; //file size
$image_temp = $_FILES['image_file']['tmp_name']; //file temp
$image_size_info = getimagesize($image_temp); //get image size
if($image_size_info){
$image_width = $image_size_info[0]; //image width
$image_height = $image_size_info[1]; //image height
$image_type = $image_size_info['mime']; //image type
}else{
die("Make sure image file is valid!");
}
//switch statement below checks allowed image type
//as well as creates new image from given file
switch($image_type){
case 'image/png':
$image_res = imagecreatefrompng($image_temp); break;
case 'image/gif':
$image_res = imagecreatefromgif($image_temp); break;
case 'image/jpeg': case 'image/pjpeg':
$image_res = imagecreatefromjpeg($image_temp); break;
default:
$image_res = false;
}
if($image_res){
//Get file extension and name to construct new file name
$image_info = pathinfo($image_name);
$image_extension = strtolower($image_info["extension"]); //image extension
$image_name_only = strtolower($image_info["filename"]);//file name only, no extension
//create a random name for new image (Eg: fileName_293749.jpg) ;
$new_file_name = $image_name_only. '_' . rand(0, 9999999999) . '.' . $image_extension;
//folder path to save resized images and thumbnails
$thumb_save_folder = $destination_folder . $thumb_prefix . $new_file_name;
$image_save_folder = $destination_folder . $new_file_name;
//call normal_resize_image() function to proportionally resize image
if(normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality))
{
//call crop_image_square() function to create square thumbnails
if(!crop_image_square($image_res, $thumb_save_folder, $image_type, $thumb_square_size, $image_width, $image_height, $jpeg_quality))
{
die('Error Creating thumbnail');
}
/* We have succesfully resized and created thumbnail image
We can now output image to user's browser or store information in the database*/
echo '<div align="center">';
echo '<img src="./ImageUploader/uploads/'.$thumb_prefix . $new_file_name.'" alt="Thumbnail">';
echo '<br />';
echo '<img src="./ImageUploader/uploads/'. $new_file_name.'" alt="Resized Image">';
echo '</div>';
}
imagedestroy($image_res); //freeup memory
}
}
}
##### This function will proportionally resize image #####
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
//do not resize if image is smaller than max size
if($image_width <= $max_size && $image_height <= $max_size){
if(save_image($source, $destination, $image_type, $quality)){
return true;
}
}
//Construct a proportional size of new image
$image_scale = min($max_size/$image_width, $max_size/$image_height);
$new_width = ceil($image_scale * $image_width);
$new_height = ceil($image_scale * $image_height);
$new_canvas = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
save_image($new_canvas, $destination, $image_type, $quality); //save resized image
}
return true;
}
##### This function crops image to create exact square, no matter what its original size! ######
function crop_image_square($source, $destination, $image_type, $square_size, $image_width, $image_height, $quality){
if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize
if( $image_width > $image_height )
{
$y_offset = 0;
$x_offset = ($image_width - $image_height) / 2;
$s_size = $image_width - ($x_offset * 2);
}else{
$x_offset = 0;
$y_offset = ($image_height - $image_width) / 2;
$s_size = $image_height - ($y_offset * 2);
}
$new_canvas = imagecreatetruecolor( $square_size, $square_size); //Create a new true color image
//Copy and resize part of an image with resampling
if(imagecopyresampled($new_canvas, $source, 0, 0, $x_offset, $y_offset, $square_size, $square_size, $s_size, $s_size)){
save_image($new_canvas, $destination, $image_type, $quality);
}
return true;
}
##### Saves image resource to file #####
function save_image($source, $destination, $image_type, $quality){
switch(strtolower($image_type)){//determine mime type
case 'image/png':
imagepng($source, $destination); return true; //save png file
break;
case 'image/gif':
imagegif($source, $destination); return true; //save gif file
break;
case 'image/jpeg': case 'image/pjpeg':
imagejpeg($source, $destination, $quality); return true; //save jpeg file
break;
default: return false;
}
}
I am uploading an image to my folder and I have created a thumbnail from uploaded image.
/*
save this image to try --
http://images.dpchallenge.com/images_challenge/0-999/319/800/Copyrighted_Image_Reuse_Prohibited_157378.jpg
*/
$source = 'H:/xampp/htdocs/myfolder/new.jpg';
$destination = $_SERVER['DOCUMENT_ROOT'] . 'myfolder/New/';
$quality = 60;
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
}
echo $image;
print(imagejpeg($image, $destination, $quality));
imagejpeg($image, $destination, $quality);
But, it is not creating anything at all, I alreday have uploaded image in
Source=> /myfolder/
Now, how to create a thumbnail of smaller size and save it to
destination=> myfolder/New/
or May be my approach is wrong, If so please tell what is the right way.
Any help is really appreciated.
Try this it will works for .jpg and .png images
<?php
$file = 'H:/xampp/htdocs/myfolder/phool.png';
$pathToSave = 'H:/xampp/myfolder/New/';
$what = getimagesize($file);
$file_name = basename($file);
//print "MIME ".$what['mime'];
switch(strtolower($what['mime']))
{
case 'image/png':
$img = imagecreatefrompng($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/png');
imagepng($new,$pathToSave.$file_name,9);
imagedestroy($new);
break;
case 'image/jpeg':
$img = imagecreatefromjpeg($file);
$new = imagecreatetruecolor($what[0],$what[1]);
imagecopy($new,$img,0,0,0,0,$what[0],$what[1]);
header('Content-Type: image/jpeg');
imagejpeg($new,$pathToSave.$file_name);
imagedestroy($new);
break;
case 'image/gif':
$img = imagecreatefromgif($file);
break;
default: die();
}
?>
I have always found image manipulation a pain so I use a library called Intervention.
Here is example to create a thumbnail based on your scenario:
// open an image file
$img = Image::make('H:/xampp/htdocs/myfolder/new.jpg');
// now you are able to resize the instance
$img->resize(75, 75);
// save the image as a new file
$img->save($destination.'new.jpg');
can this function help you:
function makeThumbnails($updir, $img, $id)
{
$thumbnail_width = 134;
$thumbnail_height = 189;
$thumb_beforeword = "thumb";
$arr_image_details = getimagesize("$updir" . $id . '_' . "$img"); // pass id to thumb name
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if ($original_width > $original_height) {
$new_width = $thumbnail_width;
$new_height = intval($original_height * $new_width / $original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width * $new_height / $original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom("$updir" . $id . '_' . "$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresized($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
$imgt($new_image, "$updir" . $id . '_' . "$thumb_beforeword" . "$img");
}
}
you can do it like this
list($sourceWidth,$sourceHeight) = getimagesize($filepath)
$destWidth = round($sourceWidth/2);
$destHeight = round($sourceHeight/2);
$sourceImage = imagecreatefromjpeg($filepath);
$destinationImage = imagecreatefromtrue($destWidth,$destHeight);
//Now Main function for resizing purpose
imagecopyresized($destinationImage,$sourceImage,0,0,0,0,$destWidth,$destHeight,$sourceWidth,$sourceHeight);
// Now You can save Image
imagejpeg($destImage,$pathToSave);
Try this