Unable to get the dimensions of uploaded file in php - php

Need to get the dimensions of the uploaded files such as width, height, size, etc. I tried using getimagesize() , but that does not works. I get an error,
Warning: getimagesize(C:/wamp/www/KSHRC/uploads/): failed to open stream: No such file or directory in C:\wamp\www\KSHRC\registration\multi_fileupload.php on line 31
and
Notice: Array to string conversion in C:\wamp\www\KSHRC\registration\multi_fileupload.php on line 31
Here's the code,
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
$root = $_SERVER['DOCUMENT_ROOT']."/KSHRC/uploads/";
$filename = $_FILES['userfile']['name'][$i];
echo $size = getimagesize($root.$filename);
}
Please help me..

you have to move the file from tmp to your desired folder first then you can get the image size by using your function getimagesize
for($i=0; $i < count($_FILES['userfile']['tmp_name']);$i++)
{
$root = $_SERVER['DOCUMENT_ROOT']."/KSHRC/uploads/";
$filename = $_FILES['userfile']['name'][$i];
move_uploaded_file($_FILES['userfile']['tmp_name'], $root.$filename);
echo $size = getimagesize($root.$filename);
}
Update
you can also get the file size by $_FILES['userfile']['size'] Like this
$size = $_FILES['userfile']['size'];
this will return size in bytes
UPDATE 2
$ARR_FILES = $_FILES['userfile'];
for($i=0; $i < count($ARR_FILES);$i++)
{
$root = $_SERVER['DOCUMENT_ROOT']."/KSHRC/uploads/";
$filename = $ARR_FILES[$i]['name'];
$tmp_name = $ARR_FILES[$i]['tmp_name'];
list($width, $height, $type, $attr) = getimagesize($tmp_name);
echo $width;
echo $height;
}

Related

Can't use getImageSize after calling move_uploaded_file()

I'm trying to create thumbnails after moving the full-size images to a specific folder. The function is working if it's called before if($this->moveImages($rawData, $uniqueID)) but when I put it inside the if statement it just returns the following errors:
Warning: getimagesize(/Applications/MAMP/tmp/php/phpax7wRA): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 66
Warning: Division by zero in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 70
Warning: imagecreatetruecolor(): Invalid image dimensions in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 77
Warning: imagecreatefromjpeg(/Applications/MAMP/tmp/php/phpax7wRA): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 83
Warning: imagecopyresized() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 91
Warning: imagejpeg() expects parameter 1 to be resource, boolean given in /Applications/MAMP/htdocs/Projects/Coilerz/classes/Submit.php on line 92
When returning a var_dump on the values passed in it returns what looks like correct data but it seems that it is unable to access it. I will post the functions in question below, thanks for your help.
Submit Function (Called when form is submitted / kicks off functions):
public function submitCoil ($data) {
$db = Database::getInstance();
$uniqueID = $this->hash();
$rawData = $this->interpretData($data, $uniqueID);
$queryData = $this->interpretData($data, $uniqueID)['queryData'];
$imageData = $this->interpretData($data, $uniqueID)['imageData'];
if ($this->nullCheck($data)) {
mkdir('coils/' . $uniqueID);
if($this->moveImages($rawData, $uniqueID)) {
//SUPRESS SLEEP ON UPLOADsleep(5);
for($i = 0; $i < count($data['image_name']); $i++) {
$this->createThumbnail($imageData['image_name'][$i], $imageData['image_tmp_name'][$i], $imageData['image_type'][$i], $uniqueID, $i);
}
$db->insertFew("coils", array_keys($queryData), array_values($queryData));
echo "<script>alert('Your coil was uploaded!');</script>";
}
} else {
echo "Please fill in all fields";
}
}
Move full-size images:
private function moveImages ($data, $uniqueID) {
$queryData = $data['queryData'];
$data = $data['imageData'];
$return = true;
$allowedTypes = array('image/jpg', 'image/png', 'image/jpeg');
if ($data['image_name'][0] != "") {
for($i = 0; $i < count($data['image_name']); $i++) {
if (!in_array($data['image_type'][$i], $allowedTypes)) {
$return = false;
echo "<script>alert('Files must be either jpeg or png');</script>";
} else {
$ext = pathinfo($data['image_name'][$i], PATHINFO_EXTENSION);
move_uploaded_file($data['image_tmp_name'][$i], $queryData['images'] . $i . '.' . $ext);
}
}
} else {
$return = true;
}
return $return;
}
Create/move thumbnails function:
public function createThumbnail ($fileName, $tmpName, $fileType, $location, $imageNumber) {
$name = $fileName;
$image = $tmpName;
$file_type = $fileType;
var_dump($name);
var_dump($image);
$image_size = getimagesize($image);
$image_width = $image_size[0] . "<br>";
$image_height = $image_size[1];
$new_size = ($image_width + $image_height) / ($image_width * ($image_height / 1000));
$new_width = $image_width * $new_size . "<br>";
$new_height = $image_height * $new_size;
$allowed = array("image/jpeg", "image/png");
if(in_array($file_type, $allowed)) {
$new_image = imagecreatetruecolor($new_width, $new_height);
//Switch on filetype
switch($file_type) {
case "image/jpeg":
$old_image = imagecreatefromjpeg($image);
break;
case "image/png":
$old_image = imagecreatefrompng($image);
break;
}
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
imagejpeg($new_image, 'coils/' . $location . '/' . 'thumb-' . $imageNumber . '.jpg');
}
}
my suggestion:
call createThumbnail() before move_uploaded_file() in moveImages()
I think because of move_uploaded file moves and deletes the temporary file you are geeting the error

PHP - sometime getimagesize exchange the dimension of the image

I am using Symfony2 and I have a problem with the PHP:getimagesize because sometime the dimensions that this function return are exchanged.
My use of this function is like int the http://php.net/manual/es/function.getimagesize.php page and the images are sent to the server with a POST;
I post a mwe :
//INITIALIZATION OF VARIABLES
for ($i = 0; $i < count($_FILES['filename']['tmp_name']); $i++) {
if ($_FILES['filename']['tmp_name'][$i]) {
$img = strtolower(strtotime(date('Y-m-d h:i:s')) . $random . ".jpg");
if (!is_dir($Tmppath)) {
mkdir($Tmppath, 0777, TRUE);
}
move_uploaded_file($_FILES['filename']['tmp_name'][$i], $Tmppath . $img);
if (file_exists($Tmppath . $img)) {
if (!empty($img)) {
//DO SOMEHTING
list($width, $height) = getimagesize($Tmppath . $img);
//DO SOMEHTING
}
}
}
}
But sometime the $width and $height of the image are exchanged; the images that are uploaded from the clients are of many format and sometime if the same image that is uploaded twice the width and height are exchanged. Anyone has the same problem? there is another function in PHP more precise?
Thanks

Trouble inserting two array values into database

Here is the code I am using for multiple image upload for every entry in the database; id, image, name, date. By using this code, the image name is inserting correctly but I have a problem with the name field. I want to insert the name using $product_name= $_POST['pro_name']; but it only inserts 'array' in name field.
<?php
include('../config.php');
if (isset($_POST['submit'])) {
$product_name = $_POST['pro_name'];
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']) && $product_name < count($product_name); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$finel_name = explode('/', $target_path);
$image_name_final = $finel_name[1];
$jajsj = "insert into spec_product set image='$image_name_final', name='$product_name'";
$janson = mysql_query($jajsj) or die(mysql_error());
// If file moved to uploads folder.
echo $j . ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j . ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j . ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
The value is inserting as array because the variable $product_name is not a string but an array. Whenever an array is used where a string was expected e.g.: concatenation of a string or in your case the query statment: insert into spec_product set image='$image_name_final', name='$product_name'"; PHP will automatically convert the array into its default string value "Array".
Make sure that $product_name is not an array but a string which contains name of the product you want to insert in the table.
Regards,
Nitin Thakur
replace in your code
for ($i = 0; $i < count($_FILES['file']['name']); $i++)
{
and add this before your query execute
$product_name_final= $product_name[$i];

Divide photo to X and Y pieces

I have a 96x96 image and i need to divide it in 36 pieces of 16x16 and i have a script given below works fine on my localhost but not working on my webhost.
function makeTiles($name, $imageFileName, $crop_width, $crop_height)
{
$dir = "/pic";
$slicesDir = "/pic/16X16";
// might be good to check if $slicesDir exists etc if not create it.
$ImgExt = split(".",$imageFileName);
$inputFile = $dir . $imageFileName;
$img = new Imagick($inputFile);
$imgHeight = $img->getImageHeight();
$imgWidth = $img->getImageWidth();
$cropWidthTimes = ceil($imgWidth/$crop_width);
$cropHeightTimes = ceil($imgHeight/$crop_height);
for($i = 0; $i < $cropWidthTimes; $i++)
{
for($j = 0; $j < $cropHeightTimes; $j++)
{
$img = new Imagick($inputFile);
$x = ($i * $crop_width);
$y = ($j * $crop_height);
$img->cropImage($crop_width, $crop_height, $x, $y);
$data = $img->getImageBlob();
$newFileName = $slicesDir . $name . "_" . $x . "_" . $y . ".".$ImgExt[1];
$result = file_put_contents ($newFileName, $data);
}
}
}
Getting fatal error
Fatal error: Class 'Imagick' not found in myfile.php line number
My host saying:
Imagick and image magic both are same unfortunately, we do not have
them as a PHP module we have binaries like ImageMagick binary and
Image magic path is /usr/local/bin. Include this function in your
script and check the website functionality from your end.
I dont know how to fix this error.
If I understand it correctly you will have to invoke the imagick binary from your script using exec():
exec('/usr/local/bin/convert '.$inputFile.' -crop 96x96+ox+oy '.$newFilename);
The ox and oy should be replaced with the correct offset values.
Here is are a couple of links that might help:
How do I use Imagick binaries from php
Imagick - Convert Command-line tool

IMagick function to cut an image into roughly equally-sized tiles

I'm trying to use the IMagick PHP wrapper to assist in chopping a specified image into a set of tiles (the number of which is variable).
In the ImageMagick documentation there is reference to the -crop operator accepting an optional flag of # that will instruct it to cut an image into "roughly equally-sized divisions" (see here), solving the problem of what to do when the image size is not an exact multiple of the desired tile size.
Does anyone know if there is a way to leverage this functionality in the IMagick PHP wrapper? Is there anything I can use besides cropImage()?
I had to do the same thing (if I'm reading your question correctly). Although it does use cropImage...
function slice_image($name, $imageFileName, $crop_width, $crop_height)
{
$dir = "dir where original image is stored";
$slicesDir = "dir where you want to store the sliced images;
mkdir($slicesDir); //you might want to check to see if it exists first....
$fileName = $dir . $imageFileName;
$img = new Imagick($fileName);
$imgHeight = $img->getImageHeight();
$imgWidth = $img->getImageWidth();
$crop_width_num_times = ceil($imgWidth/$crop_width);
$crop_height_num_times = ceil($imgHeight/$crop_height);
for($i = 0; $i < $crop_width_num_times; $i++)
{
for($j = 0; $j < $crop_height_num_times; $j++)
{
$img = new Imagick($fileName);
$x = ($i * $crop_width);
$y = ($j * $crop_height);
$img->cropImage($crop_width, $crop_height, $x, $y);
$data = $img->getImageBlob();
$newFileName = $slicesDir . $name . "_" . $x . "_" . $y . ".jpg";
$result = file_put_contents ($newFileName, $data);
}
}
}

Categories