PHP check IF non-empty, non-zero - php

I get the width and height of image with getimagesize function, like below:
list($width,$height) = getimagesize($source_pic);
How can I use IF condition to check that the getimagesize function executed without error and $width and $height got non-empty, non-zero values?

if ($size = getimagesize($source_pic)) {
list($width,$height) = $size;
if($height > 0 && $width > 0) {
// do stuff
}
}

if ($width === NULL) {
//handle error
}
If there's an error getimagesize returns FALSE, not an an array, so the list assignment will result in the variables being NULL.

This should be enough:
list($width, $height) = getimagesize($source_pic);
if( $width>0 && $height>0 ){
// Valid image with known size
}
If it isn't a valid image, both $width and $height will be NULL. If it's a valid image but PHP could not determine its dimensions, they'll be 0.
A note from the manual:
Some formats may contain no image or
may contain multiple images. In these
cases, getimagesize() might not be
able to properly determine the image
size. getimagesize() will return zero
for width and height in these cases.

$size = getimagesize('image.jpg');
list($height,$width) = getimagesize('image.jpg');
if($height>0 && $width>0){
//it comes into if block if and only if both are not null
}

Related

ErrorException: imagecreatetruecolor(): Invalid image dimensions in file while Intervention\Image\Image::resize()

I'm working on Laravel project and I need resize image and return it from controller as file. If image has width or height parameter equals 0, I have to compute another parameter.
I tried it like this (as I found it in documentation of library http://image.intervention.io/api/resize):
public function viewImage($w, $h, $path){
$image = Image::where('path', $path)->first();
if($image){
$manager = new ImageManager(array('driver' => 'gd'));
if ($w === 0){
$img = $manager->make(asset("storage/galleries/".$image->fullpath))
->resize($w, $h, function ($constraint) {
$constraint->aspectRatio();
});
return $img->response('jpg');
}
else{
if ($h === 0){
$img = $manager->make(asset("storage/galleries/".$image->fullpath))
->resize($w, $h, function ($constraint) {
$constraint->aspectRatio();
});
return $img->response('jpg');
}
$img = $manager->make(asset("storage/galleries/".$image->fullpath))->resize($w, $h);
return $img->response('jpg');
}
}
...
But it gives me error like this:
ErrorException: imagecreatetruecolor(): Invalid image dimensions in file C:\xampp\htdocs\PROGRAMATOR.SK_API\vendor\intervention\image\src\Intervention\Image\Gd\Commands\ResizeCommand.php on line 47
I use Intervention\Image\Image library
Could you help me please?
First of all, route parameters in laravel return string. So $w and $h are strings.
You have these options
Convert $w and $h to int in the begginning of your function
$w = intval($w);
$h = intval($h);
Change your condition comparation. PHP is able to compare String and int values. Your current comparation returns false every time. Remember that "0" === 0 will always result in false as php also compares variable type. However if you use "0" == 0 this will return true.
Also in case of width or height being 0 or "0" change it to null, so resize method works as intended.
Take a look at documentation once more

Compress and RESCALE uploaded image

I have a function that uploads files up to 8MB but now I also want to compress or at least rescale larger images, so my output image won't be any bigger than 100-200 KB and 1000x1000px resolution. How can I implement compress and rescale (proportional) in my function?
function uploadFile($file, $file_restrictions = '', $user_id, $sub_folder = '') {
global $path_app;
$new_file_name = generateRandomString(20);
if($sub_folder != '') {
if(!file_exists('media/'.$user_id.'/'.$sub_folder.'/')) {
mkdir('media/'.$user_id.'/'.$sub_folder, 0777);
}
$sub_folder = $sub_folder.'/';
}
else {
$sub_folder = '';
}
$uploadDir = 'media/'.$user_id.'/'.$sub_folder;
$uploadDirO = 'media/'.$user_id.'/'.$sub_folder;
$finalDir = $path_app.'/media/'.$user_id.'/'.$sub_folder;
$fileExt = explode(".", basename($file['name']));
$uploadExt = $fileExt[count($fileExt) - 1];
$uploadName = $new_file_name.'_cache.'.$uploadExt;
$uploadDir = $uploadDir.$uploadName;
$restriction_ok = true;
if(!empty($file_restrictions)) {
if(strpos($file_restrictions, $uploadExt) === false) {
$restriction_ok = false;
}
}
if($restriction_ok == false) {
return '';
}
else {
if(move_uploaded_file($file['tmp_name'], $uploadDir)) {
$image_info = getimagesize($uploadDir);
$image_width = $image_info[0];
$image_height = $image_info[1];
if($file['size'] > 8000000) {
unlink($uploadDir);
return '';
}
else {
$finalUploadName = $new_file_name.'.'.$uploadExt;
rename($uploadDirO.$uploadName, $uploadDirO.$finalUploadName);
return $finalDir.$finalUploadName;
}
}
else {
return '';
}
}
}
For the rescaling I use a function like this:
function dimensions($width,$height,$maxWidth,$maxHeight)
// given maximum dimensions this tries to fill that as best as possible
{
// get new sizes
if ($width > $maxWidth) {
$height = Round($maxWidth*$height/$width);
$width = $maxWidth;
}
if ($height > $maxHeight) {
$width = Round($maxHeight*$width/$height);
$height = $maxHeight;
}
// return array with new size
return array('width' => $width,'height' => $height);
}
The compression is done by a PHP function:
// set limits
$maxWidth = 1000;
$maxHeight = 1000;
// read source
$source = imagecreatefromjpeg($originalImageFile);
// get the possible dimensions of destination and extract
$dims = dimensions(imagesx($source),imagesy($source),$maxWidth,$maxHeight);
// prepare destination
$dest = imagecreatetruecolor($dims['width'],$dims['height']);
// copy in high-quality
imagecopyresampled($dest,$source,0,0,0,0,
$width,$height,imagesx($source),imagesy($source));
// save file
imagejpeg($dest,$destinationImageFile,85);
// clear both copies from memory
imagedestroy($source);
imagedestroy($dest);
You will have to supply $originalImageFile and $destinationImageFile. This stuff comes from a class I use, so I edited it quite a lot, but the basic functionality is there. I left out any error checking, so you still need to add that. Note that the 85 in imagejpeg() denotes the amount of compression.
you can use a simple one line solution through imagemagic library the command will like this
$image="path to image";
$res="option to resize"; i.e 25% small , 50% small or anything else
exec("convert ".$image." -resize ".$res." ".$image);
with this you can rotate resize and many other image customization
Take a look on imagecopyresampled(), There is also a example that how to implement it, For compression take a look on imagejpeg() the third parameter helps to set quality of the image, 100 means (best quality, biggest file) and if you skip the last option then default quality is 75 which is good and compress it.

php imagecopyresized() making full black thumbnail

So, I have this class that's half-working.
Somehow I'm not being able to copy a re-sized sample of the uploaded image, only a black "square" with the "correct" dimensions (screw the dimensions, as long as the thumb comes up clear. one step at the time).
I'm sorry for the WOT but it's driving me cray-cray.
Thanks in advance.
<?php
class Upload {
#function from http://stackoverflow.com/a/10666106/587811
public function resize_values($origWidth,$origHeight,$maxWidth = 200,$maxHeight = 200){
#check for longest side, we'll be seeing that to the max value above
if($origHeight > $origWidth){ #if height is more than width
$newWidth = ($maxHeight * $origWidth) / $origHeight;
$retval = array(width => $newWidth, height => $maxHeight);
}
else{
$newHeight= ($maxWidth * $origHeight) / $origWidth;
$retval = array(width => $origWidth, height => $newHeight);
}
return $retval;
}
public function image($picurl, $file, $path="images/uploaded/") {
echo "function chamada!";
if ($picurl) {
$picFileName=rand(1,9999).$_SESSION['id'];
$picExt=substr(strstr($picurl,'.'),1,3);
$picExt=strtolower($picExt);
$allowed = array("jpg","png","gif","bmp");
if (in_array($picExt,$allowed)) {
if (getimagesize($file)) {
$picNewName=str_replace(" ","_",$picFileName.'.'.$picExt);
$picWhereTo=$path.$picNewName;
$copy=move_uploaded_file($file, $picWhereTo);
if ($copy) {
list($width, $height) = getimagesize($picWhereTo);
$size = $this->resize_values($width,$height,250,250);
$thumb = imagecreatetruecolor($size['width'],$size['height']);
imagealphablending($thumb, false);
$source = imagecreatefromjpeg($picWhereTo);
imagecopyresized($thumb,$source,0,0,0,0,$size['width'],$size['height'],$width,$height);
$picNewName=$picFileName.'_thumb.'.$picExt;
imagejpeg($thumb,$path.$picNewName);
$picinfo['where']=$picWhereTo;
$picinfo['name']=$picNewName;
return $picinfo;
}
else return false;
}
else return false;
}
else return false;
}
}
}
?>
I've ran into a similar problem like this. This has to do with png's with transparency.
Give this a shot after you create $thumb using imagecreatetruecolor();
imagealphablending($thumb, false);
I'm not entirely certain this is the solution - but I think its along the right track. Your true color supports alpha blending - and it is blending in the background from the jpeg - and it might be confused by the lack of information.
If this doesn't work, please describe the exact image format you are uploading so we can try it out and see what happens.
Change your
$source = imagecreatefromjpeg($file);
to
$source = imagecreatefromjpeg($picWhereTo);
And this is how you call the function
$objoflclass->image($_FILES['img']['name'],$_FILES['img']['tmp_name'],'');
where $_FILES['img'] is the name of the image upload field and i believe from this u can understand what was the problem

PHP if image exceeds 1000px using getimagesize()

I'm using the remote method used in jQuery Validation.
I'm referring to a PHP file shown below:
<?php
$title = mysql_real_escape_string($right_form_url);
$size = getimagesize($title);
$size[3] = $width;
if ($width > 1000) {
$output = false;
} else {
$output = true;
}
echo json_encode($output);
?>
It never returns anything no matter how I put the $output variables. I've tried other PHP files that I know work in validation, so I think it has something to do with my IF statement, although I'm fairly certain the width is being declared correctly.
You code is invalid. You are setting $size[3] = $width; which sould be $width = $size[0];
Two mistakes:
1. You were setting $size[3] to $width, but should set $width to $size[3]
2. $size[3] containts string valu t use with html image tag(height="yyy" width="xxx"), $size[0] conatins numeric value of width
I think i know your problem, here, the json_enconde function only supports data with UTF-8 encoding, then if your site uses another encoding, the function will return NULL, so try this:
<?php
$title = mysql_real_escape_string($right_form_url);
$size = getimagesize($title);
$size[3] = $width;
$output = true;
if ($width > 1000) {
$output = false;
}
echo json_encode(base64_encode($output));
?>

Check image dimensions (height and width) before uploading image using PHP

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.

Categories