Uploading Jpeg fails with this function - php

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

Related

Image cannot resize using PHP

I'm trying to resize an image that I copy from Flickr. But it seems I'm getting the original size itself. Here is my code:
$img = Input::get('FlickrUrl');
$filename = gmdate('Ymdhis', time());
copy($img, $_SERVER["DOCUMENT_ROOT"].'/upload/'.$filename.'.jpeg');
$newImg = '/upload/'.$filename.'.jpeg';
list($CurWidth, $CurHeight) = getimagesize($_SERVER["DOCUMENT_ROOT"].$newImg);
$width = $CurWidth;
$height = $CurHeight;
$image_ratio = $CurWidth / $CurHeight;
//resize image according to container
$container_width = 300;
$container_height = 475;
if($CurWidth > $container_width)
{
$CurWidth = $container_width;
$CurHeight = $CurWidth / $image_ratio;
}
if($CurHeight > $container_height)
{
$CurHeight = $container_height;
$CurWidth = $CurHeight * $image_ratio;
}
if($CurWidth < $container_width)
{
$CurWidth = $container_width;
$CurHeight = $CurWidth / $image_ratio;
}
if($CurHeight < $container_height){
$CurHeight = $container_height;
$CurWidth = $CurHeight * $image_ratio;
}
$img_orginal = $_SERVER["DOCUMENT_ROOT"].'/upload/'.$filename.'.jpeg';
$img_org = ImageCreateFromJPEG($img_orginal);
$NewCanves = imagecreatetruecolor($CurWidth, $CurHeight);
imagecopyresized($NewCanves, $img_org, 0, 0, 0, 0, $CurWidth, $CurHeight, $width, $height);
$finalImg = '/upload/'.$filename.'.jpeg';
return Response::json(["success"=>"true", "images"=>$finalImg, "width"=>$CurWidth, "height"=>$CurHeight]);
First I copy the Image from the URL, saves it in my server and then trying to resize it.
Can't understand whats wrong with this code.
The problem here is you don't save your file. After:
imagecopyresized($NewCanves, $img_org, 0, 0, 0, 0, $CurWidth, $CurHeight, $width, $height);
$finalImg = '/upload/'.$filename.'.jpeg'
you should add:
imagejpeg($NewCanves, $finalImg);
to save it in filesystem
Try intervention/image package with great Laravel integration:
// open an image file
$img = Image::make('FlickrUrl');
// now you are able to resize the instance
$img->resize($container_width, $container_height);
// finally we save the image as a new file
$img->save('/upload/'.$filename.'.jpeg');

PHP MySQL imagejpeg() not working

I'm trying to save a thumbnail image onto my server using the below code...
// Get Variables
$image = $_FILES['file']['tmp_name'];
$image_name = $_FILES['file']['name'];
$page = $_POST['page'];
$sub_category = $_POST['sub_category'];
$title = $_POST['title'];
$description = $_POST['description'];
$paypal = $_POST['paypal'];
// Resize Image
$image_size = getimagesize($image);
$image_width = $image_size[0];
$image_height = $image_size[1];
// Resizes image to roughly 150px by 100px
$new_size = ($image_width + $image_height)/($image_width * ($image_height / 65));
$new_width = $image_width * $new_size;
$new_height = $image_height * $new_size;
// Image locations on server
$location_large = "Product Images/Large Images/{$image_name}";
$location_small = "Product Images/Small Images/{$image_name}";
// Create New Image
$new_image = imagecreatetruecolor($new_width, $new_height);
$source_image = imagecreatefromjpeg($image);
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
imagejpeg($new_image, $location_small, 100);
// Upload original image
move_uploaded_file($image, "../Product Images/Large Images/{$image_name}");
All server permissions are fine! 0777!
Saves original image into 'Large Images' no problems.
Since you upload the large image to the parent folder you could do:
if (!imagejpeg($new_image, '../' . $location_small, 100))
{
// Here you make sure this is the function that failed
die('Imagejpeg failed');
}

Hit PHP from node server to process images

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.

Image imagejpeg() returns nothing. CakePHP

I am modifieng this plug in to save a record of the path and make a thumbnail image and save that aswell http://bakery.cakephp.org/articles/srs2012/2012/03/12/ajaxmultiupload_plugin_for_cake_2_0_x_and_2_1
I modified the upload.php in the plugin like this:
function save($path, $folder, $filename) {
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()){
return false;
}
$width = 290;
$height = 146;
$target = fopen($path, "w");
//$this->Upload->setImage($this->Image);
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
$val = $this->resizeImage($filename, $filename, $folder, $folder.'/small/', $width, $height, 100);
$this->saveToDatabase(array('path' => $folder.$filename, 'thumb' => $folder.'/small/'.$filename));
return true;
}
This is the function i made to save:
function saveToDatabase($data){
$this->Image->save($data);
}
The following I added to create the thumbnail:
function resizeImage($src_img, $dst_img, $src_path2, $dst_path2, $dst_w, $dst_h, $dst_quality){
//Stop and giving an error if the file does not exists.
$src_path = 'img/';
$dst_path = 'img/';
$src_path .= $src_path2;
$dst_path .= $dst_path2;
if(file_exists($src_path . basename($src_img)) == false){
echo 0;
}
//Get variables for the function.
//complete path of the source image.
$src_cpl = $src_path . basename($src_img);
//return $src_cpl;
//complete path of the destination image.
$dst_cpl = $dst_path . basename($dst_img);
//extension excl "." of the source image, in lowercase.
$src_ext = strtolower(end(explode(".", $src_img)));
//width and height sizes of the source image.
list($src_w, $src_h) = getimagesize($src_cpl);
//get type of image.
//return 'IETS: '.$src_cpl.' :IETS';
$src_type = exif_imagetype($src_cpl);//
//Checking extension and imagetype of the source image and path.
if( ($src_ext =="jpg") && ($src_type =="2") ){
$src_img = imagecreatefromjpeg($src_cpl);
}else if( ($src_ext =="jpeg") && ($src_type =="2") ){
$src_img = imagecreatefromjpeg($src_cpl);
}else if( ($src_ext =="gif") && ($src_type =="1") ){
$src_img = imagecreatefromgif($src_cpl);
}else if( ($src_ext =="png") && ($src_type =="3") ){
$src_img = imagecreatefrompng($src_cpl);
}else{
die('<p>The file "'. $src_img . '" with the extension "' . $src_ext . '" and the imagetype "' . $src_type . '" is not a valid image. Please upload an image with the extension JPG, JPEG, PNG or GIF and has a valid image filetype.</p>');
}
//Get heights and width so the image keeps its ratio.
$x_ratio = $dst_w / $src_w;
$y_ratio = $dst_h / $src_h;
if( (($x_ratio > 1) || ($y_ratio > 1)) && ($x_ratio > $y_ratio) ){
//If one of the sizes of the image is smaller than the destination (normal: more height than width).
$dst_w = ceil($y_ratio * $src_w);
$dst_h = $dst_h;
}elseif( (($x_ratio > 1) || ($y_ratio > 1)) && ($y_ratio > $x_ratio) ){
//If one of the sizes of the image is smaller than the destination (landscape: more width than height).
$dst_w = $dst_w;
$dst_h = ceil($x_ratio * $src_h);
}elseif (($x_ratio * $src_h) < $dst_h){
//if the image is landscape (more width than height).
$dst_h = ceil($x_ratio * $src_h);
$dst_w = $dst_w;
}elseif (($x_ratio * $src_h) > $dst_h){
//if the image is normal (more height than width).
$dst_h = ceil($x_ratio * $src_h);
$dst_w = $dst_w;
}else{
//if the image is normal (more height than width).
$dst_w = ceil($y_ratio * $src_w);
$dst_h = $dst_h;
}
// Creating the resized image.
$dst_img=imagecreatetruecolor($dst_w,$dst_h);
$result = imagecopyresampled($dst_img,$src_img,0,0,0,0,$dst_w, $dst_h,$src_w,$src_h);
// Saving the resized image.
$result2 = imagejpeg($dst_img,$dst_cpl,$dst_quality);
return 'dfdfhdfhhgfddghhgffddghdghhdgghgfhdh: '.$result.'|||asdasda'.$result2;
// Cleaning the memory.
imagedestroy($src_img);
imagedestroy($dst_img);
}
enter code here
Now I already used this code on the same server and it worked perfectly fine. But in my return value i get the following:
[uploader] responseText = dfdfhdfhhgfddghhgffddghdghhdgghgfhdh: 1|||asdasda{"success":true}
The function imagejpeg does not return anything.
Now what could be wrong? I am only an intern and I can't figure out what is wrong.
Greetings,
Harm.
bump?
See http://php.net/manual/en/function.imagejpeg.php - I think, that you have problem in function imagejpeg - see parameter filename.
If there will be more problems, see http://www.php.net/manual/en/function.gd-info.php

Resize images in PHP without using third-party libraries?

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.

Categories