I'm kind of a beginner in PHP and here's what I'm trying to do:
Recieve an uploaded image and move it to temp/ folder
Examine it and decide whether it needs to be resized or not (it needs, if it's not 135px wide)
If needs to be resized, resize it and save as results/{number}_cover.jpg
If it doesn't, copy an uploaded image right away to the same place, without resizing
And here's my code:
$target_path = "temp/";
$target_path = $target_path . basename($_FILES["file" . $a]["name"]);
move_uploaded_file($_FILES["file" . $a]["tmp_name"], $target_path);
list($current_width, $current_height, $type, $attr) = getimagesize($target_path);
if($current_width != 135) {
$filename = $a . "_cover.jpg";
$result_image = "results/" . $filename;
$writing = fopen($result_image, 'w');
$scale = (135 / $current_width);
$new_width = 135;
$new_height = $current_height * $scale;
$result_image = imagecreatetruecolor($new_width, $new_height);
$current_image = imagecreatefromjpeg($target_path);
imagecopyresampled($result_image, $current_image, 0, 0, 0, 0, $new_width, $new_height, $current_width, $current_height);
imagejpeg($result_image, null, 100);
fclose($writing);
} else {
$target_path = "results/";
$target_path = $target_path . $a . "_cover.jpg";
move_uploaded_file($_FILES["file" . $a]["tmp_name"], $target_path);
}
However, this is what this code does for me:
1. If an image needs resizing, it just give me an image data to the browser instead of saving it to the file
2. If it doesn't need resizing, nothing happens.
What am I doing wrong?
Thanks in advance for your help!
Related
i am trying to upload image and then resizing the image and save it. the upload is working fine and the resizing is also working but the resized image is not saving. if i use header ("Content-type: image/jpeg"); then it showing the resized image also. but after resizing the image is not getting saved.
here is my code:
$filename = $_FILES['myfile']['name'][$count] ;
$filename = uploadfilename($filename);
$filename1=$iiid."blog".$filename;
$target_path = "../photo/";
$target_path = $target_path . repc($filename1);
move_uploaded_file($_FILES['myfile']['tmp_name'][$count], $target_path);
$dbfield = $count+1;
$sql="update product set img_".$dbfield." ='".rep($filename1)."' where id='".$iiid."'";
$result=mysql_query($sql);
$count++;
// header ("Content-type: image/jpeg");
// print_r(get_resource_type($uploadedImage));exit();
// $resizedImage = PIPHP_ImageResize($target_path,400,400);
$w = 100;
$h = 100;
list($width, $height) = #getimagesize($target_path);
$source = #ImageCreateFromJPEG($target_path);
$resized_img = #ImageCreateTrueColor($w, $h);
#ImageCopyResampled($resized_img, $source, 0, 0, 0, 0, $w, $h, $width, $height);
#ImageJPEG($resized_img);
I've been building a gallery in php as a learning exercise and also because I'll need one to display my wedding photos in a couple of months.
I have written a function that processes the images. It looks to see what images are in the original folder and generates a thumbnail and preview for each. It's worked fine up until now as I've been testing with small batches of images.
Now I have 24 images in the original folder it only process the first 18. I don't get any errors displayed it just seems to stop.
Function
function processImgs($previewWidth, $thumbWidth, $thumbPath, $previewPath, $originalPath) {
$images = glob($originalPath."*");
foreach($images as $image){
$path_parts = pathinfo($image);
// setup filenames
$thumbFile = $thumbPath . "thumb_" . $path_parts['filename'] . ".jpg";
$previewFile = $previewPath . "preview_" . $path_parts['filename'] . ".jpg";
// calculate new images sizes
$size = getimagesize($image);
$originalWidth = $size['0'];
$originalHeight = $size['1'];
$previewHeight = $originalHeight / ($originalWidth / $previewWidth);
$thumbHeight = $originalHeight / ($originalWidth / $thumbWidth);
//create new images
$original = imagecreatefromjpeg($image);
$preview = imagecreatetruecolor($previewWidth, $previewHeight);
$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($preview, $original, 0, 0, 0, 0, $previewWidth, $previewHeight, $originalWidth, $originalHeight);
imagecopyresampled($thumb, $original, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $originalWidth, $originalHeight);
// save images to their new folders
imagejpeg($preview, $previewFile);
imagejpeg($thumb, $thumbFile);
imagedestroy($original);
imagedestroy($preview);
imagedestroy($thumb);
// give some feedback when the script runs
if (file_exists($thumbFile) && file_exists($previewFile)) {
echo ". " . $path_parts['filename'] . " processed successfully.<br>";
} else {
echo ". " . $path_parts['filename'] . " <strong>failed.</strong><br>";
}
}
}
I call the function like this
processImgs(1200, 400, "thumb/", "preview/", "original/");
I don't know why it doesn't work with more files. Is there a time limit that I could be hitting? It does take a while. I'm currently building this locally on MAMP.
UPDATE
Mike was correct, the function was timing out. His solution is much more suitable.
I have now created a script that does what he suggested and it has solved the problem. Thanks for the help. I've added the script below in case it's of use to others.
$newWidth = 400;
if (isset($_GET['img'])) {
$img = $_GET['img'];
$filename = $img . ".jpg";
if (file_exists($filename)) {
$fp = fopen($filename, 'rb');
header("Content-Type: image/jpeg");
header("Content-Length: " . filesize($filename));
fpassthru($fp);
exit;
} else {
$originalFile = "../original/" . $filename;
$original = imagecreatefromjpeg($originalFile);
$size = getimagesize($originalFile);
$newHeight = $size['1'] / ( $size['0'] / $newWidth);
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $original, 0, 0, 0, 0, $newWidth, $newHeight, $size['0'], $size['1']);
imagejpeg($new, $filename);
imagedestroy($original);
imagedestroy($new);
$fp = fopen($filename, 'rb');
header("Content-Type: image/jpeg");
header("Content-Length: " . filesize($filename));
fpassthru($fp);
}
}
I really need another brain here. I have a script that makes three different versions of an image, and saves them in different folders (large, medium, thumbnail). It resizes them and puts them in their folders, but the large one is not readable (the other two are). It has nothing to do with the folder, so I'm stuck...
Here's my (simplified) code:
<?php
$target_folder = "images/";
$uploads_dir = $target_folder;
$upload_image = $_FILES['Filedata']['tmp_name'];
$id = $_POST['post_id'];
$image_name = $id . "." . time(); //this just generates the image name
$large_name = $target_folder . "large/" . $image_name . ".jpg";
$medium_name = $target_folder . "medium/" . $image_name . ".jpg";
$small_name = $target_folder . "small/" . $image_name . ".jpg";
list($width, $height) = getimagesize($upload_image); //width/height of original image
$medium_newwidth = $width * 0.60; //scales image down to 60%
$medium_newheight = $height * 0.60;
$small_newwidth = $width * 0.20; //scales image down to 20%
$small_newheight = $height * 0.20;
$large = imagecreatefromjpeg($upload_image); //here's where I think the problem might be
$medium = imagecreatetruecolor($medium_newwidth, $medium_newheight);
$small = imagecreatetruecolor($small_newwidth, $small_newheight);
imagecopyresized($medium, $large, 0, 0, 0, 0, $medium_newwidth, $medium_newheight, $width, $height);
imagecopyresized($small, $large, 0, 0, 0, 0, $small_newwidth, $small_newheight, $width, $height);
imagejpeg($medium, $medium_name, 100);
imagejpeg($small, $small_name, 100);
rename($upload_image, $large_name);
?>
Any ideas?
Thanks!
You should use move_uploaded_file instead of rename if you want to use the original upload. Alternatively you could save the large image like you are doing with the other ones:
imagejpeg($large, $large_name, 100);
In one of my applications, I'm using the code snippet below to copy uploaded images to a directory. It works fine but copying large images (> 2MB) takes more time than ideal and I really don't need images this big, so, I'm looking for a way to resize the images. How to achieve this using PHP?
<?php
$uploadDirectory = 'images/0001/';
$randomNumber = rand(0, 99999);
$filename = basename($_FILES['userfile']['name']);
$filePath = $uploadDirectory.md5($randomNumber.$filename);
// Check if the file was sent through HTTP POST.
if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) {
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['userfile']['size'] <= 5000000) {
// Move the file to the path specified.
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) {
// ...
}
}
}
?>
Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
To anyone else seeking a complete example, create two files:
<!-- send.html -->
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<center>
<div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">
Select an image.
<br/>
<br/>
<form action="receive.php" enctype="multipart/form-data" method="post">
<input type="file" name="image" size="40">
<input type="submit" value="Send">
</form>
</div>
</center>
</body>
<?php
// receive.php
$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";
echo "File path:".$filePath."<br/>";
if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {
echo "File successfully received through HTTP POST.<br/>";
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['image']['size'] <= 5000000) {
echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";
// Resize and save the image.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
// Save the original image.
if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {
echo "Copied the original file to the specified destination.<br/>";
}
}
}
?>
I made a small function to resize images, the function is below:
function resize_image($path, $width, $height, $update = false) {
$size = getimagesize($path);// [width, height, type index]
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
if ( array_key_exists($size['2'], $types) ) {
$load = 'imagecreatefrom' . $types[$size['2']];
$save = 'image' . $types[$size['2']];
$image = $load($path);
$resized = imagecreatetruecolor($width, $height);
$transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
imagesavealpha($resized, true);
imagefill($resized, 0, 0, $transparent);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
imagedestroy($image);
return $save($resized, $update ? $path : null);
}
}
And here's how you use it:
if ( resize_image('dir/image.png', 50, 50, true) ) {// resize image.png to 50x50
echo 'image resized!';
}
there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use
check out :
https://github.com/Nimrod007/PHP_image_resize
hope this helps
ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.
Thanks to Mateus Nunes!
i edited his work a bit to get transparent pngs working:
$source = $_FILES["..."]["tmp_name"];
$destination = 'abc/def/ghi.png';
$maxsize = 45;
$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
$height = round($width*$height_orig/$width_orig);
$width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig = imagecreatefromstring( file_get_contents($source) );
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
$images_fin = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);
You could also use an x*y/width method for resizing and then calling imagecopyresampled() like is shown at http://www.virtualsecrets.com/upload-resize-image-php-mysql.html That page also puts images (after resizing) into mySQL via the PDO.
I am trying to take a photograph and create a thumbnail without losing the IPTC info that contains copyright info and other information. I am scripting using GD for the resize which of course results in the loss of the IPTC data since it creates an entire new file, not actually resizing the original. So, my solution was to extract the IPTC data from the original image and then embed it in the thumbnail. As of now, everything runs fine and the thumbnail is generated except the IPTC data is not copied over. My code snippet is below. Can anyone see anyhting I am missing? This is based off of the examples in the PHP manual for iptcembed(). Oh yeah, I am working within the Zend Framework but apart from the Registry to handle the config, this is pretty straightforward OOP code. Thanks!
public function resizeImage($image, $size)
{
// Get Registry
$galleryConfig = Zend_Registry::get('gallery_config');
$path = APPLICATION_PATH . $galleryConfig->paths->mediaPath . $image->path . '/';
$file = $image->filename . '.' . $image->extension;
$newFilename = $image->filename . '_' . $size . '.' . $image->extension;
// Get Original Size
list($width, $height) = getimagesize($path . $file);
// Check orientation, create scalar
if($width > $height){
$scale = $width / $size;
}else{
$scale = $height / $size;
}
// Set Quality
switch($size){
case ($size <= 200):
$quality = 60;
break;
case ($size > 200 && $size <= 600):
$quality = 80;
break;
case ($size > 600):
$quality = 100;
break;
}
// Recalculate new sizes with default ratio
$new_width = round($width * (1 / $scale));
$new_height = round($height * (1/ $scale));
// Resize Original Image
$imageResized = imagecreatetruecolor($new_width, $new_height);
$imageTmp = imagecreatefromjpeg ($path.$file);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save File
$complete = imagejpeg($imageResized, $path . $newFilename, $quality);
// Copy IPTC info into new file
$imagesize = getImageSize($path . $file, $info);
if(isset($info['APP13'])){
$content = iptcembed($info['APP13'], $path . $newFilename);
$fw = fopen($path . $newFilename , 'wb');
fwrite($fw, $content);
fclose($fw);
}
}
I think iptcembed does automatically save the file, which means that the php.net manual example is wrong:
Return Values
If success and spool flag is lower than 2 then the JPEG will not be returned as a string, FALSE on errors.
See http://php.net/iptcembed