My attempt at getting the size of a newly uploaded image appears not to be working properly.
list($w, $h) = getimagesize($_FILES['image_field']);
echo 'width:'.$w;
outputs:
width:
How is this possible? I know for a fact the image (.jpg) is uploading fine because it's now on my server.
Use this code:
list($w, $h) = getimagesize($_FILES["image_field"]["tmp_name"]);
first you need to upload file then pass the uploaded location
getimagesize("location_of_file/".$file_name);
OR
getimagesize($path['path'].'/'.$_POST['name']);
OR
$file_name=$_FILES['fileToUpload']['name'];
getimagesize($target_dir.'/'.$file_name);
OR
$file_tmp=$_FILES['fileToUpload']['tmp_name']; list($width, $height) =
getimagesize($file_tmp);
$file_width=$width;
$file_height=$height;
Related
I have a problem when uploading the image, I used a function to resize the image, my problem is that when I upload a small size image, It's resize successfully. But with a large size image the error cannot be found. I tried the following code:
if(move_uploaded_file($file_name,$folder.$file_name) && file_exists($folder.$file_name)){
$img = new imageLib($folder.$file_name);
$img->resizeImage(360, 360, 'portrait', true);
$img->saveImage($folder.'thumb-'.$file_name, 100);
echo "Uploaded";
}
else{
echo "Error";
}
I think the problem is that the image has not yet been uploaded but has run the resize function, so the error cannot be found.
Any help much appreciated! Thanks very much!
You Should Try:
$img = resize_image(‘/path/to/some/image.jpg’, 360, 360);
I need to resize the uploaded image and save it with given resolutions. Assume user uploads just only one single image and I save it like 35x35, 100x100 and 512x512 after finishing the upload. finally his one upload save in my folder as 3 images with different resolutions. I've done up to this point using laravel...
public function postSingleUpload()
{
//create the relevant directory to add the user image
//get the directory name (directory name equals to user id)
$dirPath = sprintf("images/users/avatar/%s/", Auth::user()->id);
//create the directory named by user id
if (!file_exists($dirPath)) {
mkdir($dirPath, 0700);
}
$file = Input::file('image');
//save image with given resulutions
//---- this part i need --------//
}
so please help me for this.
Here is what I have done to save the uploaded image with given resolutions:
//First Copy the uploaded image to some location
Input::file('profilePic')->move('Users/'.$username.'/Wallpics/',$name)
//Set this attribute for quality after resampling
$quality = 90;
$src = 'Users/'.$username.'/Wallpics/'.$name;
//Run this on recently saved uploaded image
$img = imagecreatefromjpeg($src);
//get this values from user by submitting form ( either by crop or by textboxes)
$width=(int)Input::get('w');
$height=(int)Input::get('h');
$x=(int)Input::get('x');
$y=(int)Input::get('y');
//This is the code to resample the image and generate a new to ur requirements
$dest = ImageCreateTrueColor($width, $height);
imagecopyresampled($dest, $img, 0, 0,$x,$y, $width, $height,$width,$height);
imagejpeg($dest, 'Users/'.$username.'/profilePic/'.$name, $quality);
//Set the path in database
$profile->profilePic=asset('Users/'.$username.'/profilePic/'.$name);
$profile->save();
I have a client that sends me text messages from his iPhone with images for me to upload into his gallery. I'm trying to create a admin system so I can simply take the images from the texts, go to the admin page on my iPhone and upload the images straight to the gallery.
This would save me tons of time in my day to day work schedule.
Using the provided code. How can I add the following functions:
I would like to compress the file size down to a smaller size if possible, similar to the save to web jpg function in Photoshop. (Most images I get are around 1-3 MB. I would like to get them down to around 150-500kb max)
I would like to automatically change the width to 760px, but keep the aspect ratio so the images are not squished. He sends me landscape and portrait images.
Beings they are iPhone images. They have an extension .JPG (all caps) I would like this to change to .jpg (all lower case.) This is not a deal breaker I would just like to know how to do this for future use.
Either one of these functions would be very helpful, but all 3 would be ideal for my situation.
Here is the code I'm working with?
THIS IS THE FINAL CORRECT CODE FOR UPLOADING AND RESIZING IMAGES PROVIDED By #tman
Make sure you have imagick installed in your php.ini file. Check with your hosting provider to install it.
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);
$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);
///NEW
$size = getimagesize($target_path);
$width=$size[0];
$height=$size[1];
$newwidth = 760;
$newheight = $height*($newwidth/$width);
$pic = new Imagick($target_path);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
unlink($target_path);
$pic->writeImage($target_path);
$pic->destroy();
///NEW
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>
uploader.php Original code. Allows me to upload 4 images at once. WORKS!!!
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
for($i=0;$i<count($_FILES["image"]["name"]);$i++){
if($_FILES["image"]["name"][$i] != ''){ // don't insert if file name empty
$dataType = mysql_real_escape_string($_POST["dataType"][$i]);
$title = mysql_real_escape_string($_POST["title"][$i]);
$fileData = pathinfo($_FILES["image"]["name"][$i]);
$fileName = uniqid() . '.' . $fileData['extension'];
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $fileName;
if (move_uploaded_file($_FILES["image"]["tmp_name"][$i], $target_path)){ // The file is in the images/gallery folder.
// Insert record into database by executing the following query:
$sql="INSERT INTO images (data_type, title, file_name) "."VALUES('$dataType','$title','$fileName')";
$retval = mysql_query($sql);
echo "The image {$_FILES['image']['name'][$i]} was successfully uploaded and added to the gallery<br />
<a href='index.php'>Add another image</a><br />";
}
else
{
echo "There was an error uploading the file {$_FILES['image']['name'][$i]}, please try again!<br />";
}
}
} // close your foreach
?>
FYI, This will allow you to give a unique names to your images, resize the width, but keep the correct aspect ratio and upload multiple file at the same time.
Awesome Stuff!
Like this:
$filelocation='http://help.com/images/help.jpg';
$newfilelocation='http://help.com/images/help1.jpg';
$size = getimagesize($filelocation);
$width=$size[0];//might need to be ['1'] im tired .. :)
$height=$size[1];
// Plz note im not sure of units pixles? & i could have the width and height confused
//just had some knee surgery so im kinda loopy :)
$newwidth = 760;
$newheight = $height*($newwidth/$width)
$pic = new Imagick( $filelocation);//specify name
$pic->resizeImage($newwidth,$newhight,Imagick::FILTER_LANCZOS,1);
//again might have width and heing confused
$pic->writeImage($newfilelocation);//output name
$pic->destroy();
unlink($filelocation);//deletes image
Here is something kind of similar, lets check the size and compress if the image seems that it is too big. I didn't resize it which just requires that you get the dimensions and resize based on desire.
All this is doing is if the file is greater than 250KB compress it to 85% ..
$bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
//$maxSizeInBytes = 26400; //is 250KB? No? compress it.
if ($bytes > 26400) {
$img = new Imagick($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->stripImage();
$img->setImageCompressionQuality(85);
$img->writeImage($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
}
OR:
// resize with imagejpeg ($image, $destination, $quality); if greater than byte size KB
// Assume only supported file formats on website are jpg,jpeg,png, and gif. (any others will not be compressed)
$bytes = filesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
//$maxSizeInBytes = 26400; //is gtr than 250KB? No? compress it.
if ($bytes > 26400) {
$info = getimagesize($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
$quality = 85; //(1-100), 85-92 produces 75% quality
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName);
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($inventory_path.DIRECTORY_SEPARATOR.$this->uploadName
imagejpeg($image,$inventory_path.DIRECTORY_SEPARATOR.$this->uploadName,$quality);
}
}
How can I check for height and width before uploading image, using PHP.
Must I upload the image first and use "getimagesize()"? Or can I check this before uploading it using PHP?
<?php
foreach ($_FILES["files"]["error"] as $key => $error) {
if(
$error == UPLOAD_ERR_OK
&& $_FILES["files"]["size"][$key] < 500000
&& $_FILES["files"]["type"][$key] == "image/gif"
|| $_FILES["files"]["type"][$key] == "image/png"
|| $_FILES["files"]["type"][$key] == "image/jpeg"
|| $_FILES["files"]["type"][$key] == "image/pjpeg"
){
$filename = $_FILES["files"]["name"][$key];
if(HOW TO CHECK WIDTH AND HEIGHT)
{
echo '<p>image dimenssions must be less than 1000px width and 1000px height';
}
}
?>
We can do this with temp file easily.
$image_info = getimagesize($_FILES["file_field_name"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];
This is how I solved it.
$test = getimagesize('../bilder/' . $filnamn);
$width = $test[0];
$height = $test[1];
if ($width > 1000 || $height > 1000)
{
echo '<p>iamge is to big';
unlink('../bilder/'.$filnamn);
}
This work for me
$file = $_FILES["files"]['tmp_name'];
list($width, $height) = getimagesize($file);
if($width > "180" || $height > "70") {
echo "Error : image size must be 180 x 70 pixels.";
exit;
}
If the file is in the $_FILES array (because it's been selected in a Multipart form), it has already been uploaded to the server (usually to /tmp or similar file path) so you can just go ahead and use the getimagesize() function in php to get the dimensions (including all details as array).
To get the width and height of the image use getimagesize(path_name), this function returns the array which contains the height, width, image_type constant and other image related info. By the following code you can achive that.
Note -
Need to pass temporary location of the image, and use the following piece of code before you use move_upload_file(), else it will move the file to destination path and you wont get the desired result for the image
$imageInformation = getimagesize($_FILES['celebrity_pic']['tmp_name']);
print_r($imageInformation);
$imageWidth = $imageInformation[0]; //Contains the Width of the Image
$imageHeight = $imageInformation[1]; //Contains the Height of the Image
if($imageWidth >= your_value && $imageHeight >= your_value)
{
//Your Code
}
You need something that is executed on the client before the actual upload happens.
With (server-side) php you can check the dimension only after the file has been uploaded or with upload hooks maybe while the image is uploaded (from the image file header data).
So your options are flash, maybe html5 with its FileAPI (haven't tested that, maybe that's not doable), java-applet, silverlight, ...
array getimagesize ( string $filename [, array &$imageinfo ] )
The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.
For more update visit site:
http://www.php.net/manual/en/function.getimagesize.php
Very important - if you are using Dreamweaver to code and you try to get the image size using the $_FILES[anyFormName][tmp_name] it will display an error in live view.. It took me a while to figure this out.
I am new to jQuery but im loving it! ive have a problem i cant get round as of yet.
I am using http://www.zurb.com/playground/ajax_upload
which i have got working using the following upload.php
<?
$time= time();
$uploaddir = 'users/'; //<-- Changed this to my directory for storing images
$uploadfile = $uploaddir.$time.basename($_FILES['userfile']['name']); //<-- IMPORTANT
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo $uploaddir.$time.$_FILES['userfile']['name']; // IMPORTANT
#print_r($_FILES);
} else {
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
// Otherwise onSubmit event will not be fired
echo "error";
}
?>
i have added the time variable to ensure each image is unique. The problem i have is i want to resize and optimise the image on the fly and i am not sure how to do this.
The resize is the most important featuer i require - for example i would like a max width of 300px for the image that is saved even if it was originally 1000px wide. I need to resize proportionaly ( is that a word? :) )
Any help will be great.
Regards
M
To resize images you need libs like GD
The standard function to do this is GD's imagecopyresampled.
In the example is shown one way to resize and keeping the proportion:
//> MAx
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
There is two main image manipulation things in PHP, GD or Imagemagick. Both will be able to do what you need. You will need to configure them on your PHP webserver.