Creating a thumbnail in PHP store in different folder - php

Hello I was looking at creating a thumbnail along with my main image. I would like it to be stored in a different folder than the original and be a maximum height of 400px. I have had a search around but it all seems too complex. I was looking for something fairly simple. I am new to the file uploading stuff. Below is the code I currently have.
// Configuration
$allowed_filetypes = array('.jpg', '.JPG', '.bmp', '.png', '.gif');
$max_filesize = 100000000;
$upload_path = 'artimages/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
// Random Number
$randomnumber = rand(1, 1000000);
$filename = $randomnumber.$filename;
// File Size
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// File Type
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Check CHMOD 777
if(!is_writable($upload_path))
die('Fail');
// Upload File
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Success';
else
echo 'Fail';

The code below will require PHP-GD
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}

You can do something like that:
$tmp_path = /*the temp path of your picture*/;
$imagePath = /*the path of you uploaded picture*/;
$Thumbnail = /*the path of your thumbnail folder*/;
move_uploaded_file($tmp_path, $imagePath);
copy($imagePath, $thumbnailPath);
So you will upload your image and just after that you will copy it in another location.

Related

Php Image upload failing and using imagecreatefromjpeg to process png and bmp files?

Hello I have the following code to create a thumbnail of an image then upload it. The code is failing when I try to upload the image attached below and I don't know why. Previous to this code there is a main image upload which always works but the thumbnail script above works most of the time but not with the image attached for some reason. The code dies so the page outputs the success of the main image upload but the thumbnail never uploads and neither does the rest of the page.
Also will this code process images other than jpeg? If it won't how would I go about making it process other file types like bmp and png?
// load image and get image size
$img = imagecreatefromjpeg( $upload_path . $filename );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_height = $thumbHeight;
$new_width = floor( $width * ( $thumbHeight / $height ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, $upload_paththumbs . $filename );
Image that fails
Your code works for me with your image, so the problem must be with the set values of your input variables.
As already suggested in the comments, check your PHP error log. If that doesn't show anything abnormal you'll need debug the code line-by-line.
For the second part of your question: no, your code won't work for images other than JPEG. The changes, below, will handle GIF, JPEG, and PNG.
Note that the function exif_imagetype() might not be available by default. In this case you'll need to activate the exif extension in your PHP config.
$upload_path = './';
$filename = 'b4bAx.jpg';
$upload_paththumbs = './thumb-';
$thumbHeight = 50;
switch ( exif_imagetype( $upload_path . $filename ) ) {
case IMAGETYPE_GIF:
imagegif(
thumb(imagecreatefromgif( $upload_path . $filename ), $thumbHeight),
$upload_paththumbs . $filename
);
break;
case IMAGETYPE_JPEG:
imagejpeg(
thumb(imagecreatefromjpeg( $upload_path . $filename ), $thumbHeight),
$upload_paththumbs . $filename
);
break;
case IMAGETYPE_PNG:
imagepng(
thumb(imagecreatefrompng( $upload_path . $filename ), $thumbHeight),
$upload_paththumbs . $filename
);
break;
default:
echo 'Unsupported image type!';
}
function thumb($img, $thumbHeight) {
// get image size
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_height = $thumbHeight;
$new_width = floor( $width * ( $thumbHeight / $height ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// return thumbnail
return $tmp_img;
}

PHP createThumbnail function troubleshooting

I'm using this function, to create thumbnails of images uploaded by the user, that I found here: http://webcheatsheet.com/php/create_thumbnail_images.php :
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
if (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
This function works fine and does exactly what I want it to, but, despite this, I'm still getting errors from it. See errors below:
Warning: opendir(images/008/01/0000288988r.jpg,images/008/01/0000288988r.jpg) [<a href='function.opendir'>function.opendir</a>]: The directory name is invalid. (code: 267)
Warning: opendir(images/008/01/0000288988r.jpg) [<a href='function.opendir'>function.opendir</a>]: failed to open dir: No error
Warning: readdir() expects parameter 1 to be resource, boolean given
The problem, I think, is that I'm passing an actual file, not just a directory, into the parameters for the function. This is the case for $pathtoimages and $pathtothumbs. The function is supposed to search through the directory passed to it to find all images with the .jpg extension. But I would like to just perform the function on the one image uploaded at the time of upload. Is there someway to edit this function to allow for this?
Thanks in advance
the $pathToImage must point to image file
remove
$dir = opendir( $pathToImages );
if (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
add $info = pathinfo($pathtoImages); // for the file name
$fname = $info['filename']
replace {$pathToImages}{$fname} with $pathToImages only, since its the image file.
btw, this code is not verbose.
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}" );
}
Think I prematurely posted this question. Thanks for help from everyone.
#csw looks like your solution may have worked, but I got mine working too so I didn't test it.
Quick and dirty:
function createThumb( $pathToImage, $pathToThumb, $thumbWidth )
{
$fname = $pathToImage;
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImage}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumb}{$fname}" );
}
You have to use that function like this:
createThumbs("path_to_image", "path_to_thumb", "thumb_width");
Replacing the arguments. Notice the word "path", it's a directory, like "../images/02", and you are using probably the path along with the picture name, like this:
createThumbs("images/008/01/0000288988r.jpg", " ......
And it should be:
createThumbs("images/008/01/" ...

create thumbnail of image and then save it into database

i am creating a thumbnail of an image and then save it into the database but i don't know how to do so. here is my code
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
$pathToImages = "../uploads/images/";
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpg' )
{
$pathToThumbs = "../uploads/images/thumbs/";
//echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
$thumbimage = $fname;
}
}
// close the directory
closedir( $dir );
}
createThumbs("/uploads/documents","/uploads/images/thumbs/",100);
creation of thumbnail is fine but now i dont know how to save it in db(lack of skills)
why you don't save the results in file?
i think you must select the text type in database field, then save the content of image there,
and read the data in a diffrent php file with "Content-type: image/jpg" header.
for example:
$query = "SELECT image FROM youtablename WHERE id = 10";
$result = mysql_query($query) or die('Error, query failed');
$content=mysql_result($result,0,"image");
header("Content-type: image/jpg");
echo $content;
You can use the Dropbox API that automatically generates thumbnails. I think that save binary files in a database is the worst mistake we can make. Especially for the performance and files management becomes difficult.

How to auto resize uploaded image using php

I have a script;
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $imagesDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
which am using to upload images but I would like to add a script to resize the image to a specific size before it's uploaded. How do I do that???
EDIT: I have updated this to include your script elements. I'm starting from the point where you obtain your filename.
Here is a very quick, simple script to do it:
$result = move_uploaded_file($tmpName, $filePath);
$orig_image = imagecreatefromjpeg($filePath);
$image_info = getimagesize($filePath);
$width_orig = $image_info[0]; // current width as found in image file
$height_orig = $image_info[1]; // current height as found in image file
$width = 1024; // new image width
$height = 768; // new image height
$destination_image = imagecreatetruecolor($width, $height);
imagecopyresampled($destination_image, $orig_image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// This will just copy the new image over the original at the same filePath.
imagejpeg($destination_image, $filePath, 100);
Well, you can't change the size of it before it's uploaded, but you can use the GD Library to change the size of it after it's on the server. Check out GD and Image Functions listing for all of the related functions for dealing with images.
There is also this tutorial that will show you a custom class for doing a resize, but unless you need the whole think you can focus on the function resize to see how it's done

imagejpeg() doesnt give the output properly in php

I want to upload an image from disk, resize it, and then upload it to Amazon S3.
However, I cant get the proper image output from imagejpeg().
heres my code:
$sourceUrl = $_FILES['path']['tmp_name'];
$thumbWidth = '100';
$thumbid = uniqid();
$img = imagecreatefromjpeg($sourceUrl);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// output the image
imagejpeg($tmp_img);
// upload thumbnail to s3
$s3->putObjectFile($tmp_img, "mybucket", $thumbid, S3::ACL_PUBLIC_READ);
Firebug gives me this error :
illegal character
[Break on this error] (�����JFIF���������>CREATOR: g...(using IJG JPEG v62), default quality\n
If I modify imagejpeg this way,
imagejpeg($tmp_img, 'abc.jpg');
then I get the same error. :(
Can i get some help here please ?
If you check the documentation of imagejpeg you can see it outputs the image, it means the way you call it it gets sent to the browser. You can get it to save to a file the second way you call it - by passing a filename in the second parameter.
Also, $tmp_img is an image resource, not a ready-to-use image file.
I don't know how your upload function works, but: if you need the file contents to upload, do it like this:
ob_start();
imagejpeg($tmp_image);
$image_contents = ob_get_clean();
$s3->putObjectFile($image_contents, "mybucket", $thumbid, S3::ACL_PUBLIC_READ);
if you need a filename to upload:
$filename = tempnam(sys_get_temp_dir(), "foo");
imagejpeg($tmp_image, $filename);
$s3->putObjectFile($filename, "mybucket", $thumbid, S3::ACL_PUBLIC_READ);
You have to define the header:
header('Content-type: image/jpeg');
1) $tmp_img is a resource not a file. You probably need to save the image to disc and use that for putObjectFile
2) You probably need to tell S3 that the file you're uploading is of type image/jpeg
Well guys thank you very much again, I screwed around a bit more and combining that with your responses I got this working as follows :)
$thumbid .= ".jpg";
$img = imagecreatefromgif($sourceUrl);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
$path = '/var/www/1.4/wwwroot/cdn/'.$thumbid;
// output the image
if(imagegif($tmp_img, $path)){
$thumblink = "";
// upload thumbnail to s3
if($s3->putObjectFile($path, "mybucket", $thumbid, S3::ACL_PUBLIC_READ)){
$thumblink = "http://dtzhqabcdscm.cloudfront.net/".$thumbid;
imagedestroy($tmp_img);
}
return $thumblink;
}

Categories