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');
Related
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
i made a script to upload avatars on my website, it works as intended (the image is resized and uploaded) but I don't understand why thoses special characters are displayed after the page is reloaded.
Script :
//Session for test purpose
session_start();
$_SESSION['user']['id'] = 1337;
/*************************
AVATAR UPLOAD
**************************/
$msg='';
if(isset($_POST['upload'])){
$avatar = $_FILES['avatar']['name'];
$avatar_tmp = $_FILES['avatar']['tmp_name'];
if(!empty($avatar_tmp)){
//Extension test
$image = explode('.', $avatar);
$image_ext = end($image);
if(!in_array(strtolower($image_ext), array('png', 'gif', 'jpeg','jpg'))){
$msg .= '<div class="error">Choosen file is not an image</div>';
}
//Mime test and image create
else{
$image_size = getimagesize($avatar_tmp);
if($image_size['mime'] == 'image/jpeg'){
$image_src = imagecreatefromjpeg($avatar_tmp);
}
elseif($image_size['mime'] == 'image/png'){
$image_src = imagecreatefrompng($avatar_tmp);
}
elseif($image_size['mime'] == 'image/gif'){
$image_src = imagecreatefromgif($avatar_tmp);
}
else{
$msg .= '<div class="error">Choosen file is not an image</div>';
}
}
//No error -> resize and upload
if(empty($msg)){
$image_width = 150;
if($image_size[0] <= $image_width){
$image_finale = $image_src;
}
else{
$new_width[0] = $image_width;
$new_height[1] = ($image_size[1] / $image_size[0]) * $image_width;
$image_finale = imagecreatetruecolor($new_width[0], $new_height[1]);
imagecopyresampled($image_finale, $image_src, 0, 0, 0, 0, $new_width[0], $new_height[1], $image_size[0], $image_size[1]);
}
imagejpeg($image_finale, 'img/' . $_SESSION['user']['id'] . '.jpg');
imagejpeg($image_finale);
$msg .= '<div class="success">Avatar uploaded</div>';
}
}
}
Displayed characters :
ÿØÿàJFIFÿþ>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ÿÛC $.' ",#(7),01444'9=82<.342ÿÛC ...
Thanks in advance for your help.
You call
imagejpeg($image_finale);
second time at the end, I am sure you mean
imagedestroy($image_finale);
It is because imagejpeg without second parameter (path) outputs it to the browser, which gives garbage without header before that.
I have problem with my reszie image (code) when I run this code in localhost the code is work fine, but when I implement in website. the code give a warning.
<br /><b>Warning</b> : imagecreatefromjpeg([-1, [], 17, 1, 18, 1, 19, 23, true, [true, true],26,1,27,1,30,1,33]) expects parameter 1 to be resource, boolean given in <b>fungsi/f_upload_banner.php</b> on line <b>34</b><br />
This is my code for resize
<?php
$target_dir = "../uploads/images/banner/";
$image1 =$_FILES['txtfile']['name'];
$filename1 = stripslashes($_FILES['txtfile']['name']);
$ext1 = substr($image1, strrpos($image1, '.')+1);
$idimg1 = md5(uniqid() . time() . $filename1) . "-1." . $ext1;
$target_file1 = $target_dir . basename($idimg1);
//identify images file
$realImages = imagecreatefromjpeg($target_file1);
$width = imageSX($realImages);
$height = imageSY($realImages);
//save for thumbs size
$thumbWidth = 150;
$thumbHeight = ($thumbWidth / $width) * $height;
//change images size
$thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImage, $realImages, 0,0,0,0, $thumbWidth, $thumbHeight, $width, $height);
//save thumbnail images
imagejpeg($thumbImage,$target_dir."thumb_".$idimg1);
//remove images object from memory
imagedestroy($realImages);
imagedestroy($thumbImage);
?>
Where is wrong?
You're trying to use the original file name (after mangling) as the source for imagecreatefromjpeg(), when you should be using the temporary name assigned by the upload process: $_FILES['txtfile']['tmp_name']
Do this:
$realImages = imagecreatefromjpeg($_FILES['txtfile']['tmp_name']);
You're also not moving the uploaded file to a permanent location. The temporary version will be deleted when your script terminates and the file will be lost.
Note also that your code is doing no error checking whatsoever, so if your upload fails you won't know about it. See the PHP section on Handling File Upload
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.
I have this source code where I got it from net tutsplus. I have configured it and made it work in one PHP file. It does work by transferring the original image, but it does not generate to the thumbnails folder.
<?php
$final_width_of_image = 100;
$path_to_image_directory = "../../img/events/" . urldecode($_GET['name']) . "/";
$path_to_thumbs_directory = "../../img/events/" . urldecode($_GET['name']) . "/thumbnails/";
function createThumbnail($filename)
{
if(preg_match('/[.](jpg)$/', $filename))
{
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
}
elseif(preg_match('/[.](gif)$/', $filename))
{
$im = imagecreatefromgif($path_to_image_directory . $filename);
}
elseif(preg_match('/[.](png)$/', $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);
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
echo $tn;
}
if(isset($_FILES['fupload'])) {
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
$filename = $_FILES['fupload']['name'];
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
createThumbnail($filename);
}
}
?>
Basically it is supposed to generate a thumbnail of the uploaded image and store the original image into a different folder.
The paths are correct, it works by getting the folder name in the URL, it does work, but nothing works for the thumbnails folder.
BEFORE you ask this related question, yes, thumbnails generation does work on my server by the PHP GD, I have tested it separately. So this is not the problem. :)
How do I get this to work? :(
Well, first off, use imagecopyresampled(), as it will generate a better thumbnail.
Secondly, you shouldn't use the same variable for filesystem directory and for url directory. You should have $filesystem_path_to_thumbs and $url_path_to_thumbs. So you can set them differently.
Third, you may want to do a size check for both width and height. What happens if someone uploads a tall image? Your thumbnail will be outside the target box (but this may not be a big issue).
Fourth, you should prob do a check to see if the thumbnail file exists in the thumbs directory before generating the thumbnail (for performance reasons)...
Finally, the reason it's actually failing, is $final_width_of_image, $path_to_image_directory and $path_to_thumbs_directory are not defined within the function. Either:
Make them global at the start of the function, so you can access them inside of the function global $final_width_of_image, $path_to_image_directory, $path_to_thumbs_directory;
Make them arguments to the function: function createTumbnail($image, $width, $path_to_images, $path_to_thumbs) {
Hard code them inside of the function (Move their declaration from outside the function to inside the function).
Personally, I'd do #2, but it's up to what your requirements and needs are...