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.
Related
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');
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
This is the code that uploads users logo's I was wondering if anyone could help me.
I want to be able to allow users to upload .png and .gif files too.
Sorry if this is a simple fix but I am very new to php.
<?
//edit logo
function resize_image ($image) {
$imgsize = getimagesize($image);
//check for gallery type to determine thumbnail size
$size_x = 150;
$ratio = 150 / $imgsize[0];
$size_y = $imgsize[1] * $ratio;
$srcimage = ImageCreateFromjpeg ($image);
$newimage = ImageCreateTrueColor($size_x,$size_y);
//$newimage = imagecreate ($size_x, $size_y);
imagecopyresized ($newimage, $srcimage, 0, 0, 0, 0, $size_x, $size_y,
imagesx($srcimage), imagesy($srcimage));
return $newimage;
}
$myrepairer = new repairer;
//resize and upload image
$file = $_FILES['logo']['tmp_name'];
$file_name = $_FILES['logo']['name'];
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.jpg')) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.jpg');
unlink('logos/'.$_REQUEST['id'].'.jpg');
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.jpg');
}
$resultmessage = '<div align="center" class="GreenText">Logo Updated</div>';
You can just get the file extension and use it instead of '.jpg'.
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
So, it'll be something like:
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.'.$ext)) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.'.$ext);
unlink('logos/'.$_REQUEST['id'].'.'.$ext);
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.'.$ext);
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
}
When i made this function:
function makeThumbnail($type, $name, $size, $tmp_name, $thumbSize) {
//make sure this directory is writable!
$path_thumbs = "uploaded_files/";
//the new width of the resized image, in pixels.
$img_thumb_width = $thumbSize; //
$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
//List of allowed extensions if extlimit = yes
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");
//the image -> variables
$file_type = $type;
$file_name = $name;
$file_size = $size;
$file_tmp = $tmp_name;
//check if you have selected a file.
echo $file_tmp."<br>";
echo $file_name."<br>";
echo $file_type."<br>";
echo $file_size."<br>";
if(!is_uploaded_file($file_tmp)){
echo "Error: Please select a file to upload!. <br>--back";
exit(); //exit the script and don't process the rest of it!
}
//check the file's extension
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
//uh-oh! the file extension is not allowed!
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
echo "Wrong file extension. <br>--back";
exit();
}
//so, whats the file's extension?
$getExt = explode ('.', $file_name);
$file_ext = $getExt[count($getExt)-1];
//create a random file name
$rand_name = md5(time());
$rand_name= rand(0,999999999);
//the new width variable
$ThumbWidth = $img_thumb_width;
/////////////////////////////////
// CREATE THE THUMBNAIL //
////////////////////////////////
//keep image type
if($file_size){
if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
$new_img = imagecreatefromjpeg($file_tmp);
}elseif($file_type == "image/x-png" || $file_type == "image/png"){
$new_img = imagecreatefrompng($file_tmp);
}elseif($file_type == "image/gif"){
$new_img = imagecreatefromgif($file_tmp);
}
//list the width and height and keep the height ratio.
list($width, $height) = getimagesize($file_tmp);
//calculate the image ratio
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $ThumbWidth;
$newheight = $ThumbWidth/$imgratio;
}else{
$newheight = $ThumbWidth;
$newwidth = $ThumbWidth*$imgratio;
}
//function for resize image.
if (function_exists(imagecreatetruecolor)){
$resized_img = imagecreatetruecolor($newwidth,$newheight);
}else{
die("Error: Please make sure you have GD library ver 2+");
}
//the resizing is going on here!
imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//finally, save the image
ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext", 100);
ImageDestroy ($resized_img);
ImageDestroy ($new_img);
}
//ok copy the finished file to the thumbnail directory
// move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");
/*
Don't want to copy it to a separate directory?
Want to just display the image to the user?
Follow the following steps:
2. Uncomment this code:
/*
/* UNCOMMENT THIS IF YOU WANT */
echo "OK THUMB " . $thumbSize;
exit();
//*/
//and you should be set!
//success message, redirect to main page.
$msg = urlencode("$title was uploaded! Upload More?");
}
Then it stopped working, but outside a function, it works good.
As you can see i added "echo $file...." because i wanted to see if they have value, and they do have the right values.
I just get the error Error: Please select a file to upload.
This function is running after an normal upload image script(full size).
When i call the function i do:
makeThumbnail($_FILES[$fieldname]['type'], $_FILES[$fieldname]['name'], $_FILES[$fieldname]['size'], $_FILES[$fieldname]['tmp_name'], 100);
At my other file where its not in a function, theres no difference only that the variables is:
$file_type = $_FILES['file']['type'];
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
But it should work, I cant find anything wrong, but it doesnt and i keep getting that error. If i remove the is_uploaded_file function, i get a bunch of another errors.
Make sure you are not using move_uploaded_file() before calling the function.
I use timthumb to process the image into a thumbnail when it outputs it to screen, instead of when it's uploaded.
It means you only have one file and not one master size and one thumb size. TimThumb reduces the size of the file on serverside so it appears nice and smooth on the browserside. Have a look at it: TimThumb Link