Allow users to upload a pic for their profile
Oddly enough, I can't find any info on this topic: user profile pictures.
Is there a PHP solution for the following?
- Allows users to uplo开发者_运维技巧ad a pic from their hard drive for storage on our server
- Shrinks the image if it's too big; expands it if it's too small (height/width)
Is this easy to build yourself? Or is there already a library for it?
To upload and store the image, I would recommend generating a random filename for the picture, instead of keeping the original file name. This will prevent conflicts and also add a measure of security. I would suggest a pretty long name; just random numbers and letters.
Then, store the random file name in the database record along with your user info. This way, you won't have to worry about file names and user names getting out of sync, and, as I said earlier, someone won't be able to guess that Joe Schmoe's profile picture is stored as JoeSchmoe.jpg.
For when you get to the image-resizing part, use this function below I modified (from the PHP user comments). In your case, "images/smallerpicture.jpeg"
would probably be replaced by "images/<some random name here>.jpeg"
.
Example:
scaleImage("images/bigpicture.jpeg", 100, 100, "images/smallerpicture.jpeg");
Function:
function scaleImage($source, $max_width, $max_height, $destination) {
list($width, $height) = getimagesize($source);
if ($width > 150 || $height > 150) {
$ratioh = $max_height / $height;
$ratiow = $max_width / $width;
$ratio = min($ratioh, $ratiow);
// New dimensions
$newwidth = intval($ratio * $width);
$newheight = intval($ratio * $height);
$newImage = imagecreatetruecolor($newwidth, $newheight);
$exts = array("gif", "jpg", "jpeg", "png");
$pathInfo = pathinfo($source);
$ext = trim(strtolower($pathInfo["extension"]));
$sourceImage = null;
// Generate source image depending on file type
switch ($ext) {
case "jpg":
case "jpeg":
$sourceImage = imagecreatefromjpeg($source);
break;
case "gif":
$sourceImage = imagecreatefromgif($source);
break;
case "png":
$sourceImage = imagecreatefrompng($source);
break;
}
imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output file depending on type
switch ($ext) {
case "jpg":
case "jpeg":
imagejpeg($newImage, $destination);
break;
case "gif":
imagegif($newImage, $destination);
break;
case "png":
imagepng($newImage, $destination);
break;
}
}
}
It supports gifs, jpgs, and pngs.
Maybe this basic tut can hep you:
Building your own Tutorial CMS
To manipulate images with php, it is very easy with:
PHP: GD 1 Good luck
It's hard to answer this because "easy" is very relative term. For an experiences php coder it's easy, for a beginner it's not so easy. Yes, there are libraries for image resizing. You probably will have to handle processing of upload yourself, it's really easy For resizing you can take a look at pear library here
精彩评论