Hit PHP from node server to process images - php

I'm trying to hit a php page from a node server so that it will generate some thumbnail images. The problem is that it isn't generating the images when i hit do a jquery.get request from node. It works perfectly if I hit the page from a browser, though.
Here is the php code:
<?php
$thumbsFolder = 'output/thumbs/';
$mediumFolder = 'output/medium/';
$originals = glob("output/*.jpg");
$thumbs = glob("output/thumbs/*.jpg");
// only process the images that are missing
$diff = array_diff($originals, $thumbs);
foreach ($diff as $file) {
processImage($file, $thumbsFolder, 150);
processImage($file, $mediumFolder, 600);
}
function processImage($imagePath, $outputFolder, $targetWidth){
$imageSize = getimagesize($imagePath);
$originalWidth = $imageSize[0];
$originalHeight = $imageSize[1];
$targetHeight = round($originalHeight * $targetWidth / $originalWidth);
$urlElements = explode("/", $imagePath);
$fileName = array_pop($urlElements);
$fileName = explode(".", $fileName);
$ext = array_pop($fileName);
$newFilePath = $outputFolder.join($fileName, "").".".$ext;
$im = imagecreatefromjpeg($imagePath);
$sm = imagecreatetruecolor($targetWidth, $targetHeight);
imagealphablending($sm, false);
imagecopyresampled($sm, $im, 0, 0, 0, 0, $targetWidth, $targetHeight, $originalWidth, $originalHeight);
imagejpeg($sm, $newFilePath, 75);
}
?>
Here is the node script that hits the endpoint.
$.get("http://absolutepath.com/pi-lapse/thumb-gen.php", function(e){console.log(e)})
I also tried curl, and it didn't work.

Related

Uploading Jpeg fails with this function

So this function works almost perfectly but it fails with jpeg, works fine with jpg I think because the file extension bit i am not sure.
Anyone can see where I have gone wrong? I am also thinking to get the file extension by reading backward to the dot to be sure the file does not have other dots. Some ideas about that would be welcome.
function watermark($OriginalFileUpload,$DestinationWaterMarkedFile)
{
$OutPutFile = $DestinationWaterMarkedFile;
$imagesource = $OriginalFileUpload;
$File_Extention = explode(".", $imagesource); // this will fail if some file has two dots
$File_Extention = end($File_Extention);
$File_Extention = strtolower($File_Extention);
if($File_Extention == ".gif") $New_Image = #imagecreatefromgif($imagesource);
if($File_Extention == ".jpg") $New_Image = #imagecreatefromjpeg($imagesource);
if($File_Extention == ".png") $New_Image = #imagecreatefrompng($imagesource);
if($File_Extention == ".jpeg") $New_Image = #imagecreatefromjpeg($imagesource);
$watermark = imagecreatefrompng('Logo.png');
$wm_x = imagesx($watermark);
$wm_y = imagesy($watermark);
$img_x = imagesx($New_Image);
$img_y = imagesy($New_Image);
$wm_scale = 6; // 2 = 1/2
$wm_w = $img_x/$wm_scale;
$wm_aspect = $wm_y/$wm_x;
$wm_h = (int) ($wm_aspect * $wm_w);
$margin_scale = 6; // 2 = 1/2
$margen_right = $wm_w/$margin_scale;
$margen_bottom = $wm_h/$margin_scale;
$dst_x = $img_x - $wm_w - $margen_right;
$dst_y = $img_y - $wm_h - $margen_bottom;
imagecopyresized ($New_Image, $watermark, $dst_x, $dst_y, 0, 0, $wm_w, $wm_h, $wm_x, $wm_y);
imagejpeg($New_Image,$OutPutFile,100,NULL); // writes the watermarked file to the Marked folder
imagedestroy($New_Image);
}

crop image rotate and save - php

I want to rotate my crop image and then save. But its not working.
<?php
$newNamePrefix = $newname;
$manipulator = new ImageManipulator($_FILES['blogo']['tmp_name']);
$width = $manipulator->getWidth();
$height = $manipulator->getHeight();
$min= min($width ,$height);
$max= max($width ,$height);
$n=$min/800;
$d=$max/$n;
$newImage = $manipulator->resample($d,$d);
$newImage2 = $newImage->crop(0, 0, 800, 600);
// saving file to uploads folder
$manipulator->save('uploads/stores/'.$formData['url'] .'/'. $newNamePrefix.$fileExtension );
return $newname.$fileExtension;
?>
I tried this below code but it didn't work.
$degrees = 90;
$filename = $newImage2;
$source = imagecreatefromjpeg( $filename );
$rotate = imagerotate( $source, $degrees, 0 );
$fileName = 'uploads/stores/'.$formData['url'] .'/'. $newNamePrefix.$fileExtension;
// Output
imagejpeg( $rotate, $fileName, 100 );
If i use $filename = $_FILES['blogo']['tmp_name'] it works but if i use $filename = $newImage2; then it doesn't.
I am doing this first time so I have no idea whats the right way to do it.
It is because $_FILES['blogo']['tmp_name'] is a valid name whereas $newImage2 is not... Try to do something like:
echo $newImage2;
And you will understand what I mean.

GD script fails to process all images in array

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

Copying image file

I'm uploading an image file, copying it, resizing it, then moving the original file and resizing it!
I've written the following function, I know there's a lot of room to tidy the code up etc.
public function useImage($image, $photoid){
$source = $image['tmp_name'];
$target = "projectimages/";
//prepare the largest image
copy($source, $target);
$targetname = $photoid."large.jpg";
$file = $target.$targetname;
list($width, $height) = getimagesize($file);
$modwidth = 800;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $file, 100);
//prepare the smaller image
move_uploaded_file($source, $target);
$targetname = $photoid."small.jpg";
$file = $target.$targetname;
list($width, $height) = getimagesize($file);
$modwidth = 400;
$diff = $width / $modwidth;
$modheight = $height / $diff;
$tn = imagecreatetruecolor($modwidth, $modheight);
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $file, 100);
}
I'm getting plenty of errors but the crucial one that the others are built upon is the first one when I try and copy or move the uploaded file...
Warning: copy(projectimages/) [function.copy]: failed to open stream: Is a directory in /Applications/MAMP/htdocs/bs/classes/image.php on line 171
I've used var_dump on image and it appears the image is in place.
Any ideas?
The destination of the copy() call is a directory. Try to change your code like this:
$source = $image['tmp_name'];
$target = "projectimages/";
//prepare the largest image
$targetname = $photoid."large.jpg";
$file = $target.$targetname;
copy($source, $file);
// The rest of your code goes here.

Wrong colors when merging images with PHP

I want to get images ID's and creat from files a merged image according to the given ID's.
This code is called by ajax and return the image file name (which is the server time to prevent browser caching).
code:
if (isset($_REQUEST['items'])){
$req_items = $_REQUEST['items'];
} else {
$req_items = 'a';
}
$items = explode(',',$req_items);
$bg_img = imagecreatefrompng('bg.png');
for ($i=0; $i<count($items); $i++){
$main_img = $items[$i].'-large.png';
$image = imagecreatefrompng($main_img);
$image_tc = imagecreatetruecolor(300, 200);
imagecopy($image_tc,$image,0,0,0,0,300,200);
$black = imagecolorallocate($image_tc, 0, 0, 0);
imagecolortransparent($image_tc, $black);
$opacity = 100;
$bg_width = 300;
$bg_height = 200;
$dest_x = 0;//$image_size[0] - $bg_width - $padding;
$dest_y = 0;//$image_size[1] - $bg_height - $padding;
imagecopymerge($bg_img, $image_tc, $dest_x, $dest_y, 0, 0, $bg_width, $bg_height, $opacity)
;
}
$file = $_SERVER['REQUEST_TIME'].'.jpg';
imagejpeg($bg_img, $file, 100);
echo $file;
imagedestroy($bg_img);
imagedestroy($image);
die();
The images are shown exactly as I want but with wrong colors. I lately added the part with imagecreatetruecolor and imagecolortransparent, and still got wrong results.
I also saved the PNG itself on a 24 bit format and also later as 8 bit - not helping.
every ideas is very welcomed !
Thanks
After long time of trying... as always the solution was very simple:
Just make the background image a 24 bit as well.
So if someone is looking for a way to make layered transparent images this is the complete code:
<?php
if (isset($_REQUEST['items'])){
$req_items = $_REQUEST['items'];
} else {
$req_items = 'a';
}
$items = explode(',',$req_items);
$bg_img = imagecreatefrompng('bg.png');
$bg_tc = imagecreatetruecolor(300, 200);
imagecopy($bg_tc,$bg_img,0,0,0,0,300,200);
for ($i=0; $i<count($items); $i++){
$main_img = $items[$i].'-large.png';
$image = imagecreatefrompng($main_img);
$image_tc = imagecreatetruecolor(300, 200);
imagecopy($image_tc,$image,0,0,0,0,300,200);
$black = imagecolorallocate($image_tc, 0, 0, 0);
imagecolortransparent($image_tc, $black);
$opacity = 100;
$bg_width = 300;
$bg_height = 200;
$dest_x = 0;//$image_size[0] - $bg_width - $padding;
$dest_y = 0;//$image_size[1] - $bg_height - $padding;
imagecopymerge($bg_tc, $image_tc, $dest_x, $dest_y, 0, 0, $bg_width, $bg_height, $opacity);
}
$file = $_SERVER['REQUEST_TIME'].'.jpg';
imagejpeg($bg_tc, $file, 100);
echo $file;
imagedestroy($image);
imagedestroy($bg_img);
imagedestroy($bg_tc);
imagedestroy($image_tc);
die();
?>

Categories