Ive been looking at the move_upload_files function, but i dont think thats what i need.
I need to upload a picture (max size 2mb png, jpg, gif only) then rename it, then create a thumbnail of it, and save both to the same directory. I figure ill upload/rename the main file first, then take that and create the thumbnail. But what functions should i be looking at to do this?
if(isset($_FILES['p1']) && $_FILES['p1']['tmp_name'] != ''){
$sizes = array();
$sizes['50'] = 50;
$sizes['150'] = 150;
$sizes['500'] = 500;
$prefix = time();
list(,,$type) = getimagesize($_FILES['p1']['tmp_name']);
$type = image_type_to_extension($type);
move_uploaded_file($_FILES['p1']['tmp_name'], 'uploads/'.$prefix.$type);
$t = 'imagecreatefrom'.$type;
$t = str_replace('.','',$t);
$img = $t('uploads/'.$prefix.$type);
foreach($sizes as $k=>$v){
$width = imagesx( $img );
$height = imagesy( $img );
$new_width = $v;
$new_height = floor( $height * ( $v / $width ) );
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
imagealphablending( $tmp_img, false );
imagesavealpha( $tmp_img, true );
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
$c = 'image'.$type;
$c = str_replace('.','',$c);
$c( $tmp_img, 'uploads/'.$k.'_'.$prefix.$type );
}//
}//
I use this to upload, rename and create 3 different thumbs, hope this helps someone out.
You will at least need to look at PHP's GD functions, or better yet Imagick for creating thumbs.
There are zillions of tutorials on this, here are a couple:
http://www.webcheatsheet.com/php/create_thumbnail_images.php
http://icant.co.uk/articles/phpthumbnails/
http://php.about.com/od/advancedphp/ss/php_thumbnail.htm
Or you could just use a ready-made solution, e.g.:
http://phpthumb.sourceforge.net/
Have a look at phpThumb.
PHPThumb is what you need... Just search in the api for the method that allow you to save the image. regarding upload the image.. here you have a nice tutorial about it
#Ian Wilkinson php.net
better quality could be obtained using imagecopyresampled()
Related
When this code runs the browser screen turns black with a grey and white checkered square in the middle when it is suppose to display a thumbnail within a table cell on a form.
function createThumb( $imageUrl, $thumbWidth )
{
// load image and get image size
$img = imagecreatefromjpeg( $imageUrl );
$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 );
// display thumbnail
header("Content-type:image/jpeg");
imagejpeg( $tmp_img,$imageUrl,80);
};
And the line that calls the code is
<td >
<?php echo createThumb("CoffeeReg.jpg",75)?>
</td>
I haven't found any of the normal syntax errors, and the code even comes back clean when ran through a syntax checker so that leads me to believe either its a problem with my logic, I'm using the built in functions incorrectly or I have messed up something in the way I am trying to display the new thumbnail only with my lack of exp I don't see where I went wrong. I need to know what I did wrong so I can learn from this mistake.
Okay so after several hours debugging the code that Majid had provided when trying to help me understand where I went wrong with my code I found that the only thing that was needed to make the code he was using work was to add these two lines of code to the end of the secondary php file as shown here...
<?php
$imageUrl = $_GET['file_name'];
$thumbWidth = $_GET['thumb_width'];
// load image and get image size
$mainImage = imagecreatefromjpeg( $imageUrl );
$mainwidth = imagesx( $mainImage );
$mainheight = imagesy( $mainImage );
// calculate thumbnail size
$thumbWidth = intval($mainwidth/4);
$thumbHeight = intval($mainheight/4);;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $thumbWidth, $thumbHeight );
// copy and resize old image into new image
imagecopyresampled( $tmp_img, $mainImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainwidth, $mainheight );
// display thumbnail
header("Content-type:image/jpeg");
//Also had to remove the second and third argument from this function
imagejpeg( $tmp_img);
//these following two lines here is what was missing
imagedestroy(tmp_img);
imagedestroy(mainImage);
?>
So I guess that one must clear out the image variables of the thumbnail code or it will break it when it runs. Not sure why removing the two arguments from the imagejpeg function was also needed but it was mentioned in my textbook so i tried it, now with these changes this code works. Thank you Majid for all your help and If your post was still here you would be getting full credit with an up vote and best answer.
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/" ...
I have used the following php function to create thumbnail image.
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )
{
$dir = opendir( $pathToImages );
while (false !== ($fname = readdir( $dir ))) {
$info = pathinfo($pathToImages . $fname);
if ( strtolower($info['extension']) == 'jpg' || strtolower($info['extension']) == 'png' )
{
// load image and get image size
if(strtolower($info['extension']) == 'jpg')
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
else
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new tempopary 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 );
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg')
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
else
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
}
// close the directory
closedir( $dir );
}
Proper thumbnail is created for jpg image. But for png transparent image, thumbnail is created with black background. How do I make function work for png image? Please do suggest me. Thanks in advance.
I don't remember the exact particulars, but you'll want to read up on, and experiment with imagesavealpha() and imageaplphablending()
If memory serves me correctly, you'll want to set imagealphablending off, and then set imagesavealpha true. (In fact, yes, the manual page for imagesavealpha() implies just that)
So, at the end of your code:
// save thumbnail into a file
if(strtolower($info['extension']) == 'jpg'){
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}");
}else{
imagealphablending($tmp_img,false);
imagesavealpha($tmp_img,true);
imagepng( $tmp_img, "{$pathToThumbs}{$fname}" );
}
Are you trying to reinvent the wheel? Use php Thumbnailer :)
<?php
// load the library
require 'Thumbnailer';
// make callback function
function myfunc(& $thumb) {
// that will make a image thumbnail square 100x100px
$thumb->thumbSquare(100)->save('photos/output/'.$thumb->filename);
}
// call batch helper
// find all jpg, png and gif images in /photos/directory
Thumbnailer::batch('myfunc', '/photos/directory/*.{jpg,png,gif}');
?>
That's easy.
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;
}
I am creating thumbnails of fixed height and width from my PHP script using the following function
/*creates thumbnail of required dimensions*/
function createThumbnailofSize($sourcefilepath,$destdir,$reqwidth,$reqheight,$aspectratio=false)
{
/*
* $sourcefilepath = absolute source file path of jpeg
* $destdir = absolute path of destination directory of thumbnail ending with "/"
*/
$thumbWidth = $reqwidth; /*pixels*/
$filename = split("[/\\]",$sourcefilepath);
$filename = $filename[count($filename)-1];
$thumbnail_path = $destdir.$filename;
$image_file = $sourcefilepath;
$img = imagecreatefromjpeg($image_file);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
if($aspectratio==true)
{
$new_height = floor( $height * ( $thumbWidth / $width ) );
}
else
{
$new_height = $reqheight;
}
// 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
$returnvalue = imagejpeg($tmp_img,$thumbnail_path);
imagedestroy($img);
return $returnvalue;
}
and I call this function with following parameters
createThumbnailofSize($sourcefilepath,$destdir,48,48,false);
but the problem is the resulting image is of very poor quality, when I perform the same operation with Adobe Photo shop, it performs a good conversion.. why it is so? I am unable to find any quality parameter, through which I change the quality of output image..
Use imagecopyresampled() instead of imagecopyresized().
if it is image quality you are after you need to give the quality parameter when you save the image using imagejpeg($tmp_img,$thumbnail_path,100) //default value is 75
/*creates thumbnail of required dimensions*/
function
createThumbnailofSize($sourcefilepath,$destdir,$reqwidth,$reqheight,$aspectratio=false)
{
/*
* $sourcefilepath = absolute source file path of jpeg
* $destdir = absolute path of destination directory of thumbnail ending with "/"
*/
$thumbWidth = $reqwidth; /*pixels*/
$filename = split("[/\\]",$sourcefilepath);
$filename = $filename[count($filename)-1];
$thumbnail_path = $destdir.$filename;
$image_file = $sourcefilepath;
$img = imagecreatefromjpeg($image_file);
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
if($aspectratio==true)
{
$new_height = floor( $height * ( $thumbWidth / $width ) );
}
else
{
$new_height = $reqheight;
}
// 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
$returnvalue = imagejpeg($tmp_img,$thumbnail_path,100);
imagedestroy($img);
return $returnvalue;
}
You could also consider using ImageMagick (http://us3.php.net/manual/en/book.imagick.php) instead of Gd. I had the same problem just a couple of days ago with Java. Going for ImageMagick instead of Java Advanced Images resultet in a huge quality difference.
tried using the php.Thumbnailer ?
$thumb=new Thumbnailer("photo.jpg");
$thumb->thumbSquare(48)->save("thumb.jpg");
Result photo will be 48x48px. Easy right? :)
You might also want to take a look at the Image_Transform PEAR package. It takes care of a lot of the low-level details for you and makes creating and manipulating images painless. It also lets you use either GD or ImageMagick libraries. I've used it with great success on several projects.