I'm having a hard time to make my web-application work properly. I have been trying to make my avatar not feel pushed and make it resize automatically when uploaded. I'm not the best with PHP hence why I can't do this on my own. I would appreciate if someone could help me out. That's the code of the file that is the avatar.
Best regards!
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
You'll require to store Uploaded Picture on your webserver
For that:
You'll Require:
move_uploaded_file()
and for resizing purpose you can use:
imagecopyresampled()
as follows:
function resizeIMG($o_img // original image
, $target_image // Resized New Image
, $newWidth, $newHeight){
// Get Original Dimensions as follows:
$original_width=imagesx($o_image); //Returns width of image
$original_height=imagesy($o_image); //Returns height of image
$tmp = imagecreatetruecolor($newWidth, $newHeight); // Create New temp. image with new dimensions
imagecopyresampled($tmp_img, $o_img, 0, 0, 0, 0, $newWidth, $newHeight, $original_width, $original_height); // Resize original image to temporary Image
imagejpeg($tmp, $target_image, $quality); // Copy temp Image to Target File for JPG images
imagedestroy($tmp); // Destroy Temporary Image.
/* Use
imagepng() instead of imagejpeg() for PNG images
imagegif() instead of imagejpeg() for GIF images
*/
}
For all these functions mentioned you'll need to enable gd_drivers for your php. By simply removing ; before line extension=php_gd2.dll if you're using windows or See this for others.
Or you can Use image_magick for php.
also do have a look at: Resize images in PHP without using third-party libraries?
hope it helps.. cheers :).
Related
I wish to resize an image-file before it is being upload. My idea is, resize the 'temp' file & upload it. But the code gives error. Below I attached my code & comments.
<input type="file" name="file" id="file" required /> <!-- HTML Front-end through which the file would be uploaded-->
php code begins...
$fileName = $_FILES['file']['tmp_name']; //get the uploaded file's name
$ext = strtolower(substr(strrchr(fileName, '.'), 1)); //get the file's extension
$tempFile = $_FILES['file']['tmp_name']; //temporary file's path
$identityNumber="20150816"; //assigns an identity number and...
$targetPath = "uploads/".$identityNumber.'.'.$ext; //rename file & upload it
$image_properties = getimagesize($tempFile);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$percent = 0.5; //Percentage by which the image is going to be resized
$newWidth = $image_width * $percent;
$newHeight = $image_height * $percent;
if ($ext == "jpeg" || $ext == "jpg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($tempFile);
} elseif ($ext == "png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($tempFile);
}
$modifiedFile = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled(
$modifiedFile,
$thumb,
0,
0,
0,
0,
$new_width,
$new_height,
$width,
$height
);
And this is the code which gives warning as stated below...
move_uploaded_file($modifiedFile,$targetPath);
Warning: move_uploaded_file() expects parameter 1 to be string, resource given in...
And the 'echo is'
Resource id #10
Why the function move_uploaded_file gives warning..? could anyone help to achieve it?
I know there are several ways to resize the image such as "GD", "ImageMajick" etc. But I prefer the above code only...
You can save the file using imagepng function which, contrary to move_uploaded_file, accepts resource argument. imagejpeg function also exists.
imagepng ($modifiedFile, $targetPath);
http://us3.php.net/manual/en/function.imagejpeg.php
move_uploaded_file() file used for moving uploaded file from temp folder to destination folder . It works like copy. So It expect both parameters to be strings.
In your case you are create an entirely new image file so you need to use imageXXX() function for writing image to disk. For jpeg image you call imagejpeg() for png you use imagepng() etc.
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
I have this code that I have tried creating and don't know what I am doing wrong.
// SET ERROR FLAG
$error = false;
// MAKE SURE FILE IS AN IMAGE
if (!list($width, $height) = getimagesize($_FILES['avatar']['tmp_name'])) {
$error = true;
}
// MAKE SURE FILE COMES FROM FORM
if (!is_uploaded_file($_FILES['avatar']['tmp_name'])) {
$error = true;
}
// MAKE SURE FILESIZE IS NOT OVER 1MB
if (filesize($_FILES['avatar']['tmp_name']) > 1048576) {
$error = true;
}
// TARGER TO SAVE FILE AND CHANGE FILENAME AND FILE TYPE
$target = 'images/avatars/' . md5($user['id']) . '.gif';
// IMAGE RATIO AND RESIZING
$imgRatio = $width / $height;
if ($imgRatio > 1) {
$newWidth = 200;
$newHeight = 200 / $imgRatio;
} else {
$newWidth = 200 * $imgRatio;
$newHeight = 200;
}
$imgResized = imagecreatetruecolor($newWidth, $newHeight);
$newImg = imagecreatefromgif($_FILES['avatar']['tmp_name']);
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// SUCCESSFULL IMAGE UPLOAD
if (!$error && move_uploaded_file($newImg, $target)) {
echo '<p>Your avatar was uploaded successfully.</p>';
// ERROR UPLOADING IMAGE
} else {
echo '<p>There was an error uploading your avatar.</p>';
}
It always fails I cannot get the resizing to work, even a link to a good tutorial will suffice,
Happy new year!!
I think the problem is that you use GD to open the temporary image file:
$newImg = imagecreatefromgif($_FILES['avatar']['tmp_name']);
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
And then you try to move the temporary avatar file with move_uploaded_file without freeing GD resource and also discarding all the work done with GD (the resizing I mean, and I can add here you have to use resample instaead of resize method).
if (!$error && move_uploaded_file($newImg, $target)) {
The code moves the temporary uploaded file (currently opened by GD and however not physically altered by your GD work, so not resized) to the $target path.
Edit. Now I see more errors with your code. You cannot do:
$newImg = imagecopyresized($imgResized, $newImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
Because imagecopyresized do not returns anything but true or false. It simply copy one portion of a source image to a different destination resource. It do not return a resource itself!
Finally. The correct workflow to the what you want to do is:
Check the uploaded file if it's ok for you (and you do it good, it seems).
Create a $img GD resource opening the uploaded file with imagecopyresized.
Create an empty destination resource $newImg with imagecreatetruecolor.
Resize or resample using imagecopyresized or imagecopyresampled to copy source image to destination resource.
Save destination resource into a GIF file using imagegif.
Discard temporary source uploaded image.
You can learn more googling something like php gd resize uploaded images. Tons of tutorial will be one click far from you.
The code itself looks alright, however there could be a number reasons why it fails. Some debug output would be helpful. Some general pointers:
check that the path for the tmp_name is set and readable
check your php settings for post_max_size, it may be set very low or not set at all.
in your code you are only handling gif type images (imagecreatefromgif), you may need to check for the filetype prior to reading from the image resource
check that GD is properly installed in your php installation (phpinfo(); in a php script or php -i from command line should display it as acticated)
That being sad, add some error messages to your output so we can help further.
So I have a function that turns a jpeg into a png image resizes it then saves it. Then a bit later i come back to it and use the image in a rotate function. I keep getting errors though. It says uploads/image.png isnt a valid PNG file. The weird thing is that it only does then on php edited png files. If i delete image.png and download a png from the internet name is image.png is works fine as long as i dont run it through the first resize script.
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$imagecreated = imagecreatefromjpeg($filename);
$this->image = $imagecreated;
$extention = pathinfo($filename, PATHINFO_EXTENSION);
$basename = basename($filename, ".".$extention);
$newname = "uploads/".$basename;
imagepng($imagecreated, $newname.".png", 0);
// ....???
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height,
$this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
Then i save the file with just a simple
imagepng(etc etc);
I go to the uploads folder and it looks fine. its resized and everything. I also noticed photoshop wont open the edited png either.
Also the line of code that produces the error is here..
$image = imagecreatefrompng('uploads/image.png');
Possible fix is to add a NULL for your filters parameter (the last parameter in imagepng)
ie.
imagepng($image,$file_location,0,NULL);
I can't say this should be needed, but I read a similar case where someone noted they had to do this, may be dependant on the version of libpng or gd lib.
I have a bunch of high quality PNG files. I want to use PHP to convert them to JPG because of it's smaller file sizes while maintaining quality. I want to display the JPG files on the web.
Does PHP have functions/libraries to do this? Is the quality/compression any good?
Do this to convert safely a PNG to JPG with the transparency in white.
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);
Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.
To convert, you may use the following function:
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
This function uses the imagecreatefrompng() and the imagejpeg() functions from the GD library.
This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:
<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>
Hope that helps
<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
$explode = explode(".", $imageName);
$filetype = $explode[1];
if ($filetype == 'jpg') {
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
$srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
} else
if ($filetype == 'png') {
$srcImg = imagecreatefrompng("$imageDirectory/$imageName");
} else
if ($filetype == 'gif') {
$srcImg = imagecreatefromgif("$imageDirectory/$imageName");
}
$origWidth = imagesx($srcImg);
$origHeight = imagesy($srcImg);
$ratio = $origWidth / $thumbWidth;
$thumbHeight = $origHeight / $ratio;
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);
if ($filetype == 'jpg') {
imagejpeg($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'jpeg') {
imagejpeg($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'png') {
imagepng($thumbImg, "$thumbDirectory/$imageName");
} else
if ($filetype == 'gif') {
imagegif($thumbImg, "$thumbDirectory/$imageName");
}
}
?>
This is a very good thumbnail script =)
Here's an example:
$path = The path to the folder where the original picture is.
$name = The filename of the file you want to make a thumbnail of.
$thumbpath = The path to the directory where you want the thumbnail to be saved into.
$maxwidth = the maximum width of the thumbnail in PX eg. 100 (wich will be 100px).
createThumbnail($path, $name, $thumbpath, $maxwidth);
You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.
HTH.
PHP has some image processing functions along with the imagecreatefrompng and imagejpeg function. The first will create an internal representation of a PNG image file while the second is used to save that representation as JPEG image file.
See this list of php image libraries. Basically it's GD or Imagemagick.
I know it's not an exact answer to the OP, but as answers have already be given...
Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit, max_execution_time, ...
I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )
Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)
You'd have to write a shell-script that goes through all .png files, and gives them to either
convert to create a new .jpg file for each .png file
or mogrify to directly work on the original file and override it.
As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^
I've use the shell script + convert/mogrify a few times (having them run for something like 10 hours one time), and they do the job really well :-)