Can't use getImageSize after calling move_uploaded_file() - php

I'm trying to create thumbnails after moving the full-size images to a specific folder. The function is working if it's called before if($this->moveImages($rawData, $uniqueID)) but when I put it inside the if statement it just returns the following errors:
Warning: getimagesize(/Applications/MAMP/tmp/php/phpax7wRA): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 66
Warning: Division by zero in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 70
Warning: imagecreatetruecolor(): Invalid image dimensions in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 77
Warning: imagecreatefromjpeg(/Applications/MAMP/tmp/php/phpax7wRA): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 83
Warning: imagecopyresized() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 91
Warning: imagejpeg() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 92
When returning a var_dump on the values passed in it returns what looks like correct data but it seems that it is unable to access it. I will post the functions in question below, thanks for your help.
Submit Function (Called when form is submitted / kicks off functions):
public function submitCoil ($data) {
$db = Database::getInstance();
$uniqueID = $this->hash();
$rawData = $this->interpretData($data, $uniqueID);
$queryData = $this->interpretData($data, $uniqueID)['queryData'];
$imageData = $this->interpretData($data, $uniqueID)['imageData'];
if ($this->nullCheck($data)) {
mkdir('coils/' . $uniqueID);
if($this->moveImages($rawData, $uniqueID)) {
//SUPRESS SLEEP ON UPLOADsleep(5);
for($i = 0; $i < count($data['image_name']); $i++) {
$this->createThumbnail($imageData['image_name'][$i], $imageData['image_tmp_name'][$i], $imageData['image_type'][$i], $uniqueID, $i);
}
$db->insertFew("coils", array_keys($queryData), array_values($queryData));
echo "<script>alert('Your coil was uploaded!');</script>";
}
} else {
echo "Please fill in all fields";
}
}
Move full-size images:
private function moveImages ($data, $uniqueID) {
$queryData = $data['queryData'];
$data = $data['imageData'];
$return = true;
$allowedTypes = array('image/jpg', 'image/png', 'image/jpeg');
if ($data['image_name'][0] != "") {
for($i = 0; $i < count($data['image_name']); $i++) {
if (!in_array($data['image_type'][$i], $allowedTypes)) {
$return = false;
echo "<script>alert('Files must be either jpeg or png');</script>";
} else {
$ext = pathinfo($data['image_name'][$i], PATHINFO_EXTENSION);
move_uploaded_file($data['image_tmp_name'][$i], $queryData['images'] . $i . '.' . $ext);
}
}
} else {
$return = true;
}
return $return;
}
Create/move thumbnails function:
public function createThumbnail ($fileName, $tmpName, $fileType, $location, $imageNumber) {
$name = $fileName;
$image = $tmpName;
$file_type = $fileType;
var_dump($name);
var_dump($image);
$image_size = getimagesize($image);
$image_width = $image_size[0] . "<br>";
$image_height = $image_size[1];
$new_size = ($image_width + $image_height) / ($image_width * ($image_height / 1000));
$new_width = $image_width * $new_size . "<br>";
$new_height = $image_height * $new_size;
$allowed = array("image/jpeg", "image/png");
if(in_array($file_type, $allowed)) {
$new_image = imagecreatetruecolor($new_width, $new_height);
//Switch on filetype
switch($file_type) {
case "image/jpeg":
$old_image = imagecreatefromjpeg($image);
break;
case "image/png":
$old_image = imagecreatefrompng($image);
break;
}
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
imagejpeg($new_image, 'coils/' . $location . '/' . 'thumb-' . $imageNumber . '.jpg');
}
}

my suggestion:
call createThumbnail() before move_uploaded_file() in moveImages()
I think because of move_uploaded file moves and deletes the temporary file you are geeting the error

Related

Cannot upload two of the same image files

I have an issue with uploading the same image twice, but in different sizes. What I thought I could do was having one file input, where I choose the image. In the upload php file, I have two variables:
$img = $_POST["file"];
$imgThumbnail = $_POST["file"];
I have then created a function to upload images to my webpage in php. I call the functions twice after each other, but the second time the function is called, I get the error "No such file or directory.." - the first image is uploaded correctly, but the second is not because of this error. What am I doing wrong, when the file is actually the same?
// First time, normal size img
uploadNewsIMG($imgFile, $pathToUpload, $img_author, $img_text, $img_tags, 950, "false");
// Second time, thumbnail size img - ERROR IS HERE "No such file or directory.. etc."
uploadNewsIMG($imgFileThumbnail, $pathToUpload, $img_author, $img_text, $img_tags, 400, "true");
When uploading the second image, this is the line that gives me the "No such.." error:
$fileName = $fileIMG['tmp_name']; // <- THIS IS THE VARIABLE "$imgFileThumbnail"
$image_size = getimagesize($fileName); // <- ERROR HERE
EDIT
This is the function uploadNewsIMG():
function uploadNewsIMG($fileIMG, $path, $author, $alt_text, $img_tags, $max_width, $thumbnail) {
global $con;
$realFileName = $fileIMG['name'];
$fileName = $fileIMG['tmp_name'];
$realFileName = str_replace("(", "", $realFileName);
$realFileName = str_replace(")", "", $realFileName);
$fileName = str_replace("(", "", $fileName);
$fileName = str_replace(")", "", $fileName);
$realFileName = strtolower($realFileName);
$now = strtotime("now");
if ($thumbnail != "true") {
$targetFilePath = "../../" . $path . $now . "-" . $realFileName;
$img_source_link = $path . $now . "-" . $realFileName;
} else {
$targetFilePath = "../../" . $path . "thumb-" . $now . "-" . $realFileName;
$img_source_link = $path . "thumb-" . $now . "-" . $realFileName;
}
$targetFilePath = str_replace(" ","", $targetFilePath);
$img_source_link = str_replace(" ","", $img_source_link);
// Resize billedet
$dimension = $max_width;
$image_size = getimagesize($fileName);
$mime = $image_size['mime'];
$width = $image_size[0];
$height = $image_size[1];
$ratio = $width / $height;
if ($ratio > 1) {
$new_width = $dimension;
$new_height = $dimension / $ratio;
} else {
$new_height = $dimension;
$new_width = $dimension * $ratio;
}
$src = imagecreatefromstring(file_get_contents($fileName));
$destination = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($destination, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if ($mime == "image/jpeg") {
imagejpeg($destination, $fileName, 100);
} else if ($mime == "image/png") {
imagepng($destination, $fileName, 9);
}
imagedestroy($src);
imagedestroy($destination);
if (move_uploaded_file($fileName, $targetFilePath)) {
}
}
The problem here is that once you call:
move_uploaded_file
The file is gone, and you can't access it on the second try because no such file exists anymore.
What I would recommend you to do instead is just copy the image instead of moving it. This way you will be able to run this function as many times as you like.
Here is the link for this function: PHP copy.

Create thumnail to existing image with GD

I want to create thumb for existing image. I have three image input fields and only want for 1st image to make thumb.
$_FILES['img_1']['name']
$_FILES['img_2']['name']
$_FILES['img_3']['name']
And for create i usee this function
function createThumbnail($filename, $path_to_image_directory, $final_width_of_image, $path_to_thumbs_directory) {
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}else if (preg_match('/[.](jpeg)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
And when i call createThumbnail($_FILES["img_1"]["tmp_name"],'./uploads', 370, './uploads');
Files are successfull moved to directory img_1, img_2, img_3 but thumb is not created. I set error to E_ALL to see and i get to many warrnings.
Notice: Undefined variable: im in
/var/www/http_myoffice/petbook/web/ogi/admin/dodaj_vozilo_proccess.php
on line 21
Warning: imagesx() expects parameter 1 to be resource, null given in
/var/www/http_myoffice/petbook/web/ogi/admin/dodaj_vozilo_proccess.php
on line 21
Notice: Undefined variable: im in
/var/www/http_myoffice/petbook/web/ogi/admin/dodaj_vozilo_proccess.php
on line 22
Warning: imagesy() expects parameter 1 to be resource, null given in
/var/www
Warning: Division by zero in /var/www/
Warning: imagecreatetruecolor(): Invalid image dimensions in /var/www
Notice: Undefined variable: im in /var/www/
Warning: imagecopyresized() expects parameter 1 to be resource,
boolean given in /var/www/
Warning: imagejpeg() expects parameter 1 to be resource, boolean given
in /var/www/ image Congratulations. Your file has been successfully
uploaded, and a thumbnail has been created.
Your problem seems to be that you pass the temp name of the image to the function. This temp name has no file extension. You have to pass the name (with extension) and the temp name (path to file on disk).
If you want to get rid of the regex search for the file type, a user could upload a file with wrong extension, you can use $image = imagecreatefromstring( file_get_contents( $path ) );. PHP GD will get the file type on its own.
Changed PHP Code:
function createThumbnail($tempname, $filename, $final_width_of_image, $path_to_thumbs_directory) {
$im = imagecreatefromstring( file_get_contents( $tempname ) );
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename . '.jpg');
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Edit:
You can call this function:
createThumbnail($_FILES["img_1"]["tmp_name"],$_FILES["img_1"]["name"], 370, './uploads');

Why am I getting this php warning? imagecopyresampled() expects parameter 2 to be resource, null given in

I'm trying to make a basic news system in PHP and I'm about to finish but I have a little problem in the image upload part. The problem is when I try to resize the image when it exceeds a certain size. The image uploads correctly but in a null state: the image is in black.
When I upload the image in the form of my html it displays me the following warning:
Warning: imagecopyresampled() expects parameter 2 to be resource,
string given in C:\USBWebserver
v8.6\root\CCCHermosillo\anadir_noticia.php on line 116
here is the part for the image upload:
if($_POST['aƱadir']) {
if (is_uploaded_file($_FILES['image']['tmp_name'])) {
if($_FILES['image']['size'] < 500000) {
copy($_FILES['image']['tmp_name'], "C:/USBWebserver v8.6/root/CCCHermosillo/image_upload/".$_FILES['image']['name']);
$subio = true;
}else{
// $ruta_imagen = $_FILES['image']['name'];
$ruta_imagen = $_FILES['image']['tmp_name'];
$miniatura_ancho_maximo = 200;
$miniatura_alto_maximo = 200;
$info_imagen = getimagesize($ruta_imagen);
$imagen_ancho = $info_imagen[0];
$imagen_alto = $info_imagen[1];
$imagen_tipo = $info_imagen['mime'];
$lienzo = imagecreatetruecolor( $miniatura_ancho_maximo, $miniatura_alto_maximo );
switch ( $imagen_tipo ){
case IMAGETYPE_JPEG:
$imagen = imagecreatefromjpeg( $ruta_imagen );
break;
case IMAGETYPE_PNG:
$imagen = imagecreatefrompng( $ruta_imagen );
break;
case IMAGETYPE_GIF:
$imagen = imagecreatefromgif( $ruta_imagen );
break;
}
imagecopyresampled($lienzo, $imagen, 0, 0, 0, 0, $miniatura_ancho_maximo, $miniatura_alto_maximo, $imagen_ancho, $imagen_alto);
imagejpeg( $lienzo, ("C:/USBWebserver v8.6/root/CCCHermosillo/image_upload/".$_FILES['image']['name']), 90 );
$subio=TRUE;
}
}
if($subio) {
echo "<br>El archivo subio con exito";
} else {
echo "<br>El archivo no cumple con las reglas establecidas";
}
die();
}
the warning is given in this line:
imagecopyresampled($lienzo, $imagen, 0, 0, 0, 0,$miniatura_ancho_maximo,$miniatura_alto_maximo, $imagen_ancho, $imagen_alto);

Failed to open stream: No such file or directory

Hi i am new to php and i am working on image upload and crop and save bth upload and cropped image in zend on windows 7 but it's giving me these errors. Please help me to solve these errors.
Warning: imagecreatefromjpeg(public/image/) [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: failed to open stream: No such file or directory in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 64
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 68
Warning: imagejpeg() [<a href='function.imagejpeg'>function.imagejpeg</a>]: Unable to open 'public/image/crop/' for writing: No such file or directory in C:\wamp\www\ModuleEx.com\application\modules\admin\controllers\IndexController.php on line 71
Here is my controller.php code.
if(isset($_FILES['file']['name'])){ //user upload file
$file_name = stripslashes($_FILES['file']['name']);
$ext_idx = strrpos($file_name,".");
if(!$ext_idx) //hide this if ur app can upload without ext
echo "File invalid.";
else{
$ext_length = strlen($file_name) - $ext_idx;
$extension = strtolower(substr($file_name,$ext_idx+1,$ext_length));
//allowed extension
$ext_list = array("pdf", "doc","jpg", "jpeg", "gif", "png");
if(!in_array($extension, $ext_list))
echo "System can't support your extension.";
else{
$size = (2500 * 1024); //2500 Kb
$file_size=filesize($_FILES['file']['tmp_name']);
if($file_size > $size)
echo "File is oversize. Max 2500 Kb.";
else{
//change name
$file_name = "image".rand(10,1000).".".$extension;
$file_obj="public/image/".$file_name;
$copied = copy($_FILES['file']['tmp_name'], $file_obj);
if(!$copied)
echo "Failed.";
else
{
$file_data = array( 'file_name' => $file_name );
$this->view->file_obj=$file_obj;
}
}
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = "public/image/".$file_name;
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,(int)$_POST['x'],(int)$_POST['y'],
$targ_w,$targ_h,(int)$_POST['w'],(int)$_POST['h']);
//header('Content-type: image/jpeg');
imagejpeg($dst_r,"public/image/crop/".$file_name,$jpeg_quality);
}
Look at this "imagecreatefromjpeg(public/image/)" - this is NOT a image resource. It only works with a valid file resource like
imagecreatefromjpeg('public/image/test.jpg');
try this code:
$a="./images/".$file_name;
list($width, $height) = getimagesize($a);
$newwidth = "300";
$newheight = "200";
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($a);
imagecopyresized($dest, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($dest, $a, 100);
Warning: imagecreatefromjpeg(public/image/)
your path is not correct you should use the absolute path with __DIR__ for example.
imagecreatefromjpeg(__DIR__."public/image/test.jpg");
and your filename is missing. The next errors result from the first error that your image can't load.

unable to save image php

I have a snippet of code used to upload images into my gallery. All seems to work until it gets to the last part of the code.
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$pubID = $_POST['pubID'];
$size = 260; // the thumbnail height
$filedir = '../images/gallery/'.$pubID.'/'; // the directory for the original image
$thumbdir = '../images/gallery/'.$pubID.'/thumb/'; // the directory for the thumbnail image
$maxfile = '2000000';
$mode = '0777';
$userfile_name = $_FILES['Gallimage']['name'];
$userfile_tmp = $_FILES['Gallimage']['tmp_name'];
$userfile_size = $_FILES['Gallimage']['size'];
$userfile_type = $_FILES['Gallimage']['type'];
if (isset($_FILES['Gallimage']['name']))
{
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$userfile_name;
move_uploaded_file($userfile_tmp, $prod_img);
chmod ($prod_img, octdec($mode));
$sizes = getimagesize($prod_img);
$aspect_ratio = $sizes[1]/$sizes[0];
if ($sizes[1] <= $size)
{
$new_width = $sizes[0];
$new_height = $sizes[1];
}else{
$new_height = $size;
$new_width = abs($new_height/$aspect_ratio);
}
$destimg=ImageCreateTrueColor($new_width,$new_height)
or die('Problem In Creating image');
$srcimg=ImageCreateFromJPEG($prod_img)
or die('Problem In opening Source Image');
if(function_exists('imagecopyresampled'))
{
imagecopyresampled($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
or die('Problem In resizing');
}else{
Imagecopyresized($destimg,$srcimg,0,0,0,0,$new_width,$new_height,ImageSX($srcimg),ImageSY($srcimg))
or die('Problem In resizing');
}
ImageJPEG($destimg,$prod_img_thumb,90)
or die('Problem In saving');
imagedestroy($destimg);
}
The error arrives on this line: ImageJPEG($destimg,$prod_img_thumb,90).
Here is the error code line 84 being the : ImageJPEG($destimg,$prod_img_thumb,90)
Warning: imagejpeg() [function.imagejpeg]: Unable to open '../images/gallery/264/thumb/Hair-Salon-1.jpg' for writing: No such file or directory in /home/www/public_html/console/gallery.php on line 84. Problem In saving
It's conceivable that the directory '../images/gallery/'.$pubID.'/thumb/' does not exist. Try to use mkdir('../images/gallery/'.$pubID.'/thumb/', 0775, true) and see what happens. This should create writable directories along the path, down to thumb at the end.
Try this code with a bit more error checking, a few corrections and some general improvements. Everything commented, if you don't understand anything just ask:
// Try not to over-use parenthesis, it makes code less readable. You only need them to group conditions.
if (isset($_POST["MM_insert"]) && $_POST["MM_insert"] == "form1") {
// Pass through basename() for sanitization
$pubID = basename($_POST['pubID']);
$size = 260; // the thumbnail height
$filedir = '../images/gallery/'.$pubID.'/'; // the directory for the original image
$thumbdir = '../images/gallery/'.$pubID.'/thumb/'; // the directory for the thumbnail image
$maxfile = '2000000';
// PHP understands proper octal representations - no need to turn it into a string
$mode = 0777;
if (isset($_FILES['Gallimage']['name'])) {
// Get upload info and create full paths
$userfile_name = $_FILES['Gallimage']['name'];
$userfile_tmp = $_FILES['Gallimage']['tmp_name'];
$userfile_size = $_FILES['Gallimage']['size'];
$userfile_type = $_FILES['Gallimage']['type'];
$prod_img = $filedir.$userfile_name;
$prod_img_thumb = $thumbdir.$userfile_name;
// Create directories if they don't exist - this is the crux of your problem
if (!is_dir($filedir)) {
mkdir($filedir, $mode, TRUE)
or die('Unable to create storage directory');
}
if (!is_dir($thumbdir)) {
mkdir($thumbdir, $mode, TRUE))
or die('Unable to create thumb directory');
}
// Move it to the correct location and set permissions
move_uploaded_file($userfile_tmp, $prod_img)
or die('Unable to move file to main storage directory');
chmod($prod_img, $mode)
or die('Unable to set permissions of file');
// Get info about the image
$sizes = getimagesize($prod_img);
$aspect_ratio = $sizes[1] / $sizes[0];
if ($sizes[1] <= $size) {
$new_width = $sizes[0];
$new_height = $sizes[1];
} else {
$new_height = $size;
$new_width = abs($new_height / $aspect_ratio);
}
// Create image resources
$destimg = imagecreatetruecolor($new_width, $new_height)
or die('Problem in creating image');
$srcimg = imagecreatefromjpeg($prod_img)
or die('Problem in opening source Image');
// Manipulate the image
if (function_exists('imagecopyresampled')) {
imagecopyresampled($destimg, $srcimg, 0, 0, 0, 0, $new_width, $new_height, imagesx($srcimg), imagesy($srcimg))
or die('Problem in resizing');
} else {
imagecopyresized($destimg, $srcimg, 0, 0, 0, 0, $new_width, $new_height, imagesx($srcimg), imagesy($srcimg))
or die('Problem in resizing');
}
// Save the thumbnail and destroy the resources
imagejpeg($destimg, $prod_img_thumb, 90)
or die('Problem in saving');
imagedestroy($destimg);
}
// More code here? If not, merge all of this into a single if block
}

Categories