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 upload 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
Related
On a PWA, full legacy/handmade PHP/JS (jquery), i'm trying to avoid all the bug and problems with picture.
I've solved the famous bug where picture are 90° rotate
I've dicreased the weight with the "quality" parameter in imagejpeg
And i'm trying to resize it with no less than 800px for width and no more less 600px for height. Like, 810x750 it's okay for me, 1500x620 too, but no 500x450.
1 and 2 work fine. The third point is bit complicated it "crop" my picture with false position and there is this famous black bar on right.
I've read a lot of articles on it with sometimes solutions, but they are always "isolated" scripts, intended for the black bar. I want to solve my problem by keeping this big function which makes resize/rotate/decrease weight.
I don't want a copy/thumbnail, just the original with correct size.
Here's my code
function compressImage($source, $destination, $quality) {
error_log('====================');
error_log('Source : '.$source);
error_log('Destination : '.$destination);
error_log('Qualité : '.$quality);
$imgInfo = getimagesize($source);
$mime = $imgInfo['mime'];
// EXTRACT INFO
$newPic = imagecreatefromstring(file_get_contents($source));
$exif = exif_read_data($source);
$rotation = 0;
if(!empty($exif['Orientation'])) {
error_log('Orientation : '.$exif['Orientation']);
// CHECK IF PHP DID WRONG ROTATION
switch($exif['Orientation']) {
case 8:
$newPic = imagerotate($newPic, 90, 0);
break;
case 3:
$newPic = imagerotate($newPic, 180, 0);
break;
case 6:
$newPic = imagerotate($newPic, -90 ,0);
break;
}
$rotation = 1;
time_nanosleep(0, 500000000);
}
$w = 800;
$h = 600;
list($width, $height) = $imgInfo;
error_log('Actual width : '.$width);
error_log('Actual height : '.$height);
$r = $width / $height;
if($w/$h > $r) {
$newWidth = $h*$r;
$newHeight = $h;
} else {
$newHeight = $w/$r;
$newWidth = $w;
}
// CALCULATE NEW SIZE (MAYBE HERE FOR MISTAKE ?)
error_log('New width : '.$newWidth);
error_log('New height : '.$newHeight);
$thumb = imagecreatetruecolor($newWidth, $newHeight);
if($rotation == 1) {
error_log('2nd MIME : '.$mime);
switch($mime) {
case 'jpg':
error_log('JPG');
$newPic = imagejpeg($image, $destination, $quality);
break;
case 'jpeg':
error_log('JPEG');
$newPic = imagejpeg($image, $destination, $quality);
break;
}
time_nanosleep(0, 500000000);
}
imagecopyresized($thumb, $newPic, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$newPic = imagejpeg($thumb, $destination, $quality);
move_uploaded_file($newPic, $destination);
}
Here's a complete example :
Randomly wanted 9000x12000 to be 800x600 but for example if someone sends a picture of 1685x1235 (random) i want 819x600. (if we took the width as a reference in this specific case instead it would not be good because we would have 800x586 (and therefore 586 < 600)
Edit : after two weeks of tests i can't afford what i want, thanks to everyone who have solution to resize, prevent rotate bug and crop in one script.
I'm new to php, and I found a tutorial about cropping image, with a strange instruction I never see. I don't know how to search about it.
$src_img = $image_create($source_file);
Here it is the full code of the tutorial
//resize and crop image by center
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 7;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 80;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
//usage example
resize_crop_image(100, 100, "test.jpg", "test.jpg");
$image_create returns a string.
This sting is a dynamic function (whose name is decided run time)
Reference:
http://php.net/manual/en/functions.variable-functions.php
Instead of adding 3 if statements for choosing three functions:
imagecreatefromgif(), imagecreatefrompng() and imagecreatefromjpeg(),
a variable is taken which will switch the function variable (name) and that will be used.
Which is easier to use.
First up: I don't know what tutorial you're following, but it doesn't look to be a particularly good one. The code, to my eye, looks very messy and a bit dated. It also doesn't follow the coding standards at all... I'd steer clear.
To answer your question, though:
$image_create = 'imagecreatefromjpeg';
Is assigning a string to the variable, at first glance, but that string happens to be a function name, too. Basically, read this:
$src_img = $image_create($source_file);
as either one of three calls:
$src_img = imagecreatefromjpeg($source_file);
//or
$src_img = imagecreatefrompng($source_file);
//or
$src_img = imagecreatefromgif($source_file);
Depending on the value of $image_create...
It is calling a function via a variable that contains the function's name.
Note that $image_create is set depending on what type of image the code is trying to create. This allows the rest of the code that doesn't care about the image type to be consolidated, which is a good practice.
In other words...
src_img = imagecreatefromjpeg($source_file);
is-the-same-as...
$image_create = 'imagecreatefromjpeg';
src_img = $image_create($source_file);
I am uploading image with uploadify V2.1.4. After uploading image I am trying to create thumbnails of size 60x60 and 80x80 in uploadify.php file. Thumbnails are get created for jpg, png, gif file type. But it is not created when file type is jpeg.
$imgsize = getimagesize($targetFile);
switch(strtolower(substr($targetFile, -3)))
{
case "jpeg":
case "jpg":
$image = imagecreatefromjpeg($targetFile);
break;
case "png":
$image = imagecreatefrompng($targetFile);
break;
case "gif":
$image = imagecreatefromgif($targetFile);
break;
default:
exit;
break;
}
$width = 60; //New width of image
$height=60;
$src_w = $imgsize[0];
$src_h = $imgsize[1];
$picture = imagecreatetruecolor($width, $height);
imagealphablending($picture, false);
imagesavealpha($picture, true);
$bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h);
$image_name='';
if($bool)
{
$image_name=$newf_name;
$parts=explode('.',$newf_name);
$newf_name=$parts[0]."_90X90.".$parts[1];
switch(strtolower(substr($targetFile, -3)))
{
case "jpeg":
case "jpg":
header("Content-Type: image/jpeg");
$bool2 = imagejpeg($picture,$path."thumb/".$newf_name,80);
break;
case "png":
header("Content-Type: image/png");
imagepng($picture,$path."thumb/".$newf_name);
break;
case "gif":
header("Content-Type: image/gif");
imagegif($picture,$path."thumb/".$newf_name);
break;
}
}
The the operation system of the computer where you uploading your images from is absolutely irrelevant.
Instead of posting the code here you have to debug it yourself.
There is very little sense in posting code here. You will get but some wild guesses, mostly irrelevant to your case.
So, you have to make your code to tell you what is going wrong. this is called debugging and being the most important programmer's skill.
First of all you have to be sure, that you will be informed of all errors occurred.
add these lines at hthe top of your code
ini_set('display_errors',1);
error_reporting(E_ALL);
and see if if it says something.
if not - trace your program step by step.
add some exit's in your code along with printing relevant variables contents to check if they have desired value.
If you're using codeigniter (as it's been tagged) why not use codeigniter's image manipulation class?
http://codeigniter.com/user_guide/libraries/image_lib.html
It's really simple and theres plenty of documentaion to upload images and create thumbs!
I have a huge volume of thumbnailing to do. Currently, I am using ImageMagick, but it's proving too inefficient (it's too slow, uses too much CPU/memory, etc.).
I have started to evaluate GraphicsMagick, which I expected to get "wow" results from. I didn't get them. Can someone take a quick look at my benchmark script (does simple speed and file size comparison only; no CPU and memory checks yet):
http://pastebin.com/2gP7Eaxc
Here's a sample output I got:
'gm convert' took 75.0039 seconds to execute 10 iteration(s).
'convert' took 83.1421 seconds to execute 10 iteration(s).
Average filesize of gm convert: 144,588 bytes.
Average filesize of convert: 81,194 bytes.
GraphicsMagick is not that much faster -- and the outputted file sizes are SIGNIFICANTLY higher than ImageMagick.
I assume you have some sort of queue of images that require thumbs and your app works through them? You could look at siphoning off some of the work to something like EC2. If your queue gets over a certain size fire up a pre-prepared EC2 instance to process the load instead. You could even fire up several machines if the queue was massive.
You don't need these instances to run all the time - you only need them when your own server isn't able to handle the load.
Obviously you'd need to forecast your costs to see if it was worth it but given you only pay for the time you use and the prices start at 8.5c/hour it might be economical enough for your needs.
I you want to use GD2, try this function I use. It's pretty easy to use:
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;
}
}
}
I'd suggest you to use ExactImage. According to the benchmarks it is faster than the ImageMagick.
I am working on a script that uploads a picture using PHP and I wanna make it resize the image to width 180 before saving it.
I tried using the WideImage library and ->saveFileTO(...) but when I include the WideImage.php in the page, the page goes blank !!
So here is my script if you can help me and tell me how to make it save the resized version
You can use the PHP GD library to resize an image on upload.
The following code should give you an idea of how to implement the resize:
// Get the image info from the photo
$image_info = getimagesize($photo);
$width = $new_width = $image_info[0];
$height = $new_height = $image_info[1];
$type = $image_info[2];
// Load the image
switch ($type)
{
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($photo);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($photo);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($photo);
break;
default:
die('Error loading '.$photo.' - File type '.$type.' not supported');
}
// Create a new, resized image
$new_width = 180;
$new_height = $height / ($width / $new_width);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the new image over the top of the original photo
switch ($type)
{
case IMAGETYPE_JPEG:
imagejpeg($new_image, $photo, 100);
break;
case IMAGETYPE_GIF:
imagegif($new_image, $photo);
break;
case IMAGETYPE_PNG:
imagepng($new_image, $photo);
break;
default:
die('Error saving image: '.$photo);
}
You can use a class I've written for just such a task:
http://code.google.com/p/image2/source/browse/#svn/trunk/includes/classes
<?php
try
{
$image = new Image2($path_to_image);
}
catch (NotAnImageException $e)
{
printf("FILE PROVIDED IS NOT AN IMAGE, FILE PATH: %s", $path_to_image);
}
$image -> resize(array("width" => 180)) -> saveToFile($new_path); // be sure to exclude the extension
$new_file_location = $image -> getFileLocation(); // this will include the extension for future use
You don't even need to use the WideImage library.
Check this script here:
http://bgallz.org/502/php-upload-resize-image/
You start by uploading the image and saving to a temp image file. This script runs off a form with inputs for the max height or max width. So it will then generate a new image file based on the new width/height and then copy the temp image onto the new one created on the server.
You see this with the following code:
// Create temporary image file.
$tmp = imagecreatetruecolor($newwidth,$newheight);
// Copy the image to one with the new width and height.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
Dont use any library
Check this script
http://dr-wordpress.blogspot.com/2013/12/image-resizing-using-php.html
Just gave the quality of imges from (0-99)
this code will automatically resize the images while uploading