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
Related
I have tried a lot of solutions that I have found on internet but nothing is working for me. I am trying to resize and rotate the image depends on exif data but the image is not rotating. Resizing the image is working fine. But the rotation is not working. Below is the function I used to do that.
function resize_imageb($newbfile,$max_resolution){
if(file_exists($newbfile)){
$original_image = imagecreatefromjpeg($newbfile);
$exif = exif_read_data($newbfile, 0, true);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$original_image = imagerotate($original_image,90,0);
break;
case 3:
$original_image = imagerotate($original_image,180,0);
break;
case 6:
$original_image = imagerotate($original_image,-90,0);
break;
}
}
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);
$ratio = $max_resolution/$original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
if($new_height > $max_resolution){
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
if($original_image){
$new_image = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_image, $original_image, 0, 0, 0, 0,$new_width, $new_height, $original_width, $original_height);
imagejpeg($new_image,$newbfile,100);
imagedestroy($original_image);
imagedestroy($new_image);
}
}
}
When I check the resized image the Orientation information is gone from exif data however the original image I have uploaded did had the Orientation information. I am not sure what i am missing or doing wrong. Can someone help me with this?
Instead of doing the 2 part (resize and rotate) in one function, I made two functions one for rotation created by Wes and then for resize. First called the rotation function and then resize function.
Is there any way to resize the $_FILES["xfile1"]["tmp_name"] before I send it off to the move_uploaded_file() function? I checked every where but nobody seems to use this function after resizing the image.
ADDED*
// Create image from file
switch(strtolower($_FILES['xfile1']['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES['xfile1']['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES['xfile1']['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES['xfile1']['tmp_name']);
break;
default:
exit('Unsupported type: '.$_FILES['xfile1']['type']);
}
// Delete original file
#unlink($_FILES['image']['tmp_name']);
// Target dimensions
$max_width = 540;
$max_height = 540;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resample old into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
ob_start();
imagejpeg($new,'saved.jpeg' , 90);
$data = ob_get_clean();
So i have this so far. I have this $data variable which i want to replace with $_FILES["xfile1"]["tmp_name"] in the move_uploaded_file() function. Is that possible?
Thanks in Advance.
The script I have below is for users to upload a profile picture to their account. It also deletes a current profile picture if they want to upload a new one.
Something I have been struggling with over the past few months is building an image upload form that works all the time, on all browsers. I have broader questions about how to make my upload script more robust, but in particular I am having one major issue.
Why does this script not work with Internet Explorer? Uploads through Chrome, Firefox, and Safari all work just fine. However, when I upload an image using IE it gets rejected for being an incorrect file type.
Here is what I have tried/researched over the course of trying to solve this issue.
1) Made sure enctype="multipart/form-data" was included in my html form
2) Tried using exif_imagetype($file) to get the file type as opposed to getimagesize() (Note: I also enabled exif_imagetype() in my php.ini file). I read that this was a more reliable method for determining file types. This function works on the three other browsers, however when using IE it still can't determine the file type.
3) I used var_dump($_FILES) to see what is being uploaded. This shows the name, size, type, etc on all browsers except IE. On IE it seems that there is no name for the uploaded file. echoing the name displays: "string '' (length=0)"
The html form, image upload script, and image resize script are all located below.
FORM:
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="625000">
<input type="file" class="span2" name="image" id="image" size="20">
<input name="picture" type="submit" value="update" class="btn btn-primary" style="margin-bottom: -10px">
</form>
UPLOAD SCRIPT:
if (isset($_POST['picture'])){
//THIS SECTION IS FOR UPLOADING THE PROFILE PICTURE.
//It will create a standard profile image size 320 by 320.
//It also then creates a 'thumbnail' picture size 100 x 100
//delete the original profile image (if there was one)
$CurrentImage = getImage("profile",$id,FALSE);
$CurrentImageThumb = getImage("profile",$id,TRUE);
//if the current image is something other than the generic image, delete the current images
if($CurrentImage!="images/profile/generic.jpg")unlink($CurrentImage); if($CurrentImageThumb!="images/profile/genericthumb.jpg")unlink($CurrentImageThumb);
//get the type of the upload
$pic_type = ".".pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
//save the initial file
$saveto = "images/profile/$id"."$pic_type";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
//resize it and display the appropriate message if it works/doesn't work
//CREATE FULL SIZE
if (true === ($pic_error = image_resize($saveto,$saveto, 320, 320, 0))){
//CREATE THUMBNAIL
$saveto2 = "images/profile/$id"."thumb"."$pic_type";
if (true === ($pic_error = image_resize($saveto,$saveto2, 100, 100, 0))){
showAlert(2,"Your image has been uploaded!"," If the image did not change, click here to reload the page.");
}}else{
showAlert(3,"File Issue: ",$pic_error);
unlink($saveto);//delete the upload
unlink($saveto2);//delete the upload
}
}
IMAGE RESIZE SCRIPT:
function image_resize($src, $dst, $width, $height, $crop=0){
//if getimagesize doesn't output an array with the first two values being width and height, we reject the file
if(!list($w, $h) = getimagesize($src)) return "Unsupported file type. We only accept image files the extension .jpg, .jpeg, .png, .gif, or .bmp";
//get the image type based on the file extension
$type = strtolower(substr(strrchr($src,"."),1));
//based on file type, create a new image from the url
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported file type. We only accept image files with the extension .jpg, .jpeg, .png, .gif, or .bmp";
}
// resize (get the dimensions for resize if $crop or not)
if($crop){
//if initial image is smaller than crop size display error
if($w < $width or $h < $height) return "Picture is too small. Your image must be LARGER than ".$width."pixels by ".$height." pixels.";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small. Your image must be LARGER than ".$width."pixels by ".$height." pixels.";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
//create a new true color image
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
//COPY AND RESIZE THE IMAGE
/**imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y ,
int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
imagecopyresampled() will take an rectangular area from src_image of width src_w and height src_h at
position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x,dst_y).
*/
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
//then output the image to the file
switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
The issue did not reside in PHP whatsoever and the HTML form itself was setup just fine.
Our designer created a unique "browse" button for file uploads. This button conflicted with IE and prevented uploaded files from being POSTed.Not sure if this question and answer will help anybody else or not.
Moral of the story, when you hit dead ends with debugging, talk to the designer.
I am trying to add a watermark to an image using PHP and the GD image library. I can apply the watermark where I specify with the correct opacity setting.
The problem is that my watermark itself has a transparent background. When I try to apply this watermark to the image I get a black background.
The image which the watermark is being applied to is a jpeg. Could this be the problem? If so how would I convert the jpeg into a format which supports transparency, apply watermark, then convert it back?
This is the key bit of code I have at the moment.
// Determine image size and type
$size = getimagesize($this->image_path);
$size_x = $size[0];
$size_y = $size[1];
$image_type = $size[2]; // This is always a JPEG
// load source image
$image = $this->ImageCreateFromType($image_type, $this->image_path);
// Determine watermark size and type
$wsize = getimagesize($watermark_path);
$watermark_x = $wsize[0];
$watermark_y = $wsize[1];
$watermark_type = $wsize[2]; // This is typically a PNG
// load watermark
$watermark = $this->ImageCreateFromType($watermark_type, $watermark_path);
$dest_x = $this->setX($size_x, $watermark_x);
$dest_y = $this->setY($size_y, $watermark_y);
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_x, $watermark_y, $this->opacity);
While not really relevant, here is the code for the ImageCreateFromType function
function ImageCreateFromType($type,$filename) {
$im = null;
switch ($type) {
case 1:
$im = ImageCreateFromGif($filename);
break;
case 2:
$im = ImageCreateFromJpeg($filename);
break;
case 3:
$im = ImageCreateFromPNG($filename);
imagealphablending($im, true);
imagesavealpha($im, true);
break;
}
return $im;
}
Have a read about the imagecolortransparent() function: http://php.net/manual/en/function.imagecolortransparent.php
You may also want to look at this question: Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled?
ive done my research on the net and here as well and i keep on coming up with no answer that can help me:
i have the below code which displays an image from a folder based on a user's location however the image is too big and i need to resize it.
all the scripts that i have tried or read relate to files being uploaded. can anyone push me in the right direction?
thank you.
<?php
print"
<table <td width=\"138\" height=\"73\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
<tr>
<td align=\"center\" valign=\"middle\"><a href=\"map.php\"><img src=\"" .
esc('img/' . $db_name . '_maps/sm' . $user['location'] . '.png') .
"\" alt=\"Map of systems around {$user['location']}\" /></a></td>
</tr>
</table>
"
?>
My problem arises from the fact that i need to pull the images as:
<img src=\"" .esc('img/' . $db_name . '_maps/sm' . $user['location'] . '.png') . "\" alt=\"Map of systems around {$user['location']}\" /></a>
Wrote a tutorial about this a while ago. Perhaps it can help. It starts with uploading, but most of it is about resizing. Just swap out the usage of the $_FILES array by geting the image type and file name a different way. Here's the code you should need:
// Create image from file
switch(strtolower($_FILES['image']['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
default:
exit('Unsupported type: '.$_FILES['image']['type']);
}
// Target dimensions
$max_width = 240;
$max_height = 180;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
// Catch the imagedata
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
// Set new content-type and status code
header("Content-type: image/jpeg", true, 200);
// Output data
echo $data;
If you want to store the image as a file rather than dumping it to the browser, remove the head and echo part at the end and then swap out the NULL parameter in the imagejpeg call with an actual filename. Hope that helps :)
Here's the code in use: http://samples.geekality.net/image-resize/
You make take a look at gd : http://www.php.net/manual/en/function.imagecopyresized.php
You can try this:
$extension = substr( $img_url, -3 );
$extension = strtolower($extension);
switch ($extension) {
case "jpg":
case "jpeg":
$src_im = createimagefromjpeg($img_url);
break;
case "gif":
$src_im = createimagefromgif($img_url);
break;
case "png":
$src_im = createimagefrompng($img_url);
break;
}
// Get size
$size = GetImageSize($img_url);
$src_w = $size[0];
$src_h = $size[1];
// $width has to be fixed to your wanted width
$dst_w = $width;
$dst_h = round(($dst_w / $src_w) * $src_h);
$dst_im = ImageCreateTrueColor($dst_w, $dst_h);
ImageCopyResampled($dst_im, $src_im, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
ImageJpeg($dst_im);
ImageDestroy($dst_im);
imageDestroy($src_im);
There a simple to use, open source library called PHP Image Magician that has some nice features and documentation.
It uses 100% GD.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');
If you need more features convert might be a help.