I have the following code in my image.php file
<?php
if ($_GET['id'] == 1)
echo '<img src="Koala.jpg">';
?>
How can I get image size in kilobytes if I only know URL: http://localhost/test/image.php?id=1
You can use filesize() to get the image's file size.
Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.
$filename = "Koala.jpg";
$size = filesize($filename) . ' B';
$size = number_format($size / 1024, 2) . ' KB';
This will return the file size of the image in kilobytes.
If you only know the URL, you can use get_headers():
function remote_file_size($url){
$data = get_headers($url, true);
if (isset($data['Content-Length']))
return (int) $data['Content-Length'];
}
echo remote_file_size('http://example.com/image.png');
Method referenced from http://www.w3bees.com/2013/03/get-remote-file-size-using-php.html.
Related
I am using the following code to save an image from a URL but sometimes the image URL is bad and there is no image there, OR there is an issue with the image and it saves a zero size file.
<?php
file_put_contents ("/var/www/html/images/" . $character . ".jpg",
file_get_contents($image));
I need to try and find a way to stop this happening as this creates a problem (saving zero size files).
I have tried this, but it still seems to be happening:
$filesize = file_put_contents ("/var/www/html/images/" . $character . ".jpg",
file_get_contents($image));
if (($filesize < 10) || ($filesize == "")) {
echo "Error";
}
Could anyone recommend a more reliable way to do this?
Imagick package has methods for doing this
Imagick::getImageGeometry() - returns width and height of an image, or throws an exception.
function isValidImage($filename)
{
if (!fileexists($filename) return false;
if (filesize($filename) == 0) return false;
$image = new imagick($filename);
$img=$image->getImageGeometry();
return ($img['width'] > 0 && $img['height'] > 0);
}
EDIT: I have updated my answer with more checks
I have tried to get an image size by URL. I have get_headers() function to get the image size. Here is an example which is given below:
function checkImageSize($imageUrl){
if(!empty($imageUrl)){
$file_headers = #get_headers($imageUrl, 1); // it gives all header values .
// for image size, we use **Content-Length** for size.
$sizeInKB = round($file_headers['Content-Length'] / 1024, 2));
return $sizeInKB;
} else {
return 0;
}
}
$imageSize =checkImageSize($imageUrl);
if($imageSize<=$conditionalSize){
// upload code
} else {
// error msg
}
I have a php script to use file_get_contents to download remote images to server, but sometime it is corrupted
$contents = file_get_contents($url);
list($width,$height) = getimagesizefromstring( $contents );
if($width <= 300 ){
$contents = base64_decode('isdfafasfgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=');
$downloadlog->log( "ignore file width below 300 : " . $url );
}
$aws->writeToAWS( $target_path , $contents );
$contents = null;
Are there any ways to ensure the images are downloaded correctly without any corruption or a way to validate the images against remote url?
You can validate using getimagesize
Note:
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.
On failure, FALSE is returned.
edited:
for example
<?php
$array = getimagesize('https://dl.dropboxusercontent.com/u/22492671/not_an_image.jpg');
if( $array ){
echo '<pre>';
print_r($array);
echo '</pre>';
} else {
echo 'image broken';
}
?>
getimagesize() return false when image is broken.
I'm trying to upload files in php using the following function :
public function fileUpload($FILES){
$num_of_uploads = 1;
$max_file_size = 1048576; //can't be larger than 1 MB
$T = array ();
foreach($_FILES["file"]["error"] as $key=>$value){
if($_FILES["file"]["name"][$key] != ""){
if($value == UPLOAD_ERR_OK){
$v = array ();
$origfilename = $_FILES["file"]["name"][$key];
$filename = explode(".", $_FILES["file"]["name"][$key]);
$filenameext = $filename[count($filename) - 1];
$v['name'] = $filename[0];
$v['extension'] = $filename[1];
$v['type'] = $_FILES["file"]["type"][$key];
unset($filename[count($filename) - 1]);
$filename = implode(".", $filename);
$filename = "file__" . time() . "." . $filenameext;
if($_FILES["file"]["size"][$key] < $max_file_size){
$v['content'] = file_get_contents($_FILES["file"]["tmp_name"][$key]);
$T[] = $v;
}else{
throw new Exception($origfilename . " file size inaccepted!<br />");
}
}else{
throw new Exception($origfilename . " Error of upload <br />");
}
}
}
return $T;
}
This function works great with txt types, but when I'm testing pdf, or gif or jpg, it returns a damaged file.
As far as I know, file_get_contents() works well on text/html types.
However, for other file types you should parse their text content first to use it in further processing. Try opening any .pdf in Notepad to see it's text content.
For uploading purposes, use move_uploaded_file() in your cycle, like this:
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $filename);
Of course, without trying to get text content from uploaded file.
For downloading the file, you need to set headers. So, at the starting of function try setting any of below header for png or jpeg files:
//For png file
header("Content-Type: image/png");
//For jpeg file
header("Content-Type: image/jpeg");
How can i preview an image on the run time?I have the uploader script and re size functionality.But image is not showing at the run time.I dont want to save iamge.Just resize and show at the run time.Image must show from memory not from directory .I was trying something like this :
if ($_FILES['myfile']['error'] == 0)
{
$theImageToResize=$_FILES['myfile']['name'];
$afterResize=Resize($theImageToResize);
echo $theImageToResize.'---->image after resize';
}
[just want to show image from the memory.Not from Directory];
Server Side Code :
$savefolder = 'images'; //upload dir
$max_size = 35000; //in bytes
// image types
$allowtype = array('bmp', 'gif', 'jpg', 'jpeg', 'gif', 'png');
$res = '';
// if is received a valid file
if (isset ($_FILES['myfile'])) {
$type = end(explode(".", strtolower($_FILES['myfile']['name'])));
if (in_array($type, $allowtype)) {
if ($_FILES['myfile']['size']<=$max_size*1000) {
if ($_FILES['myfile']['error'] == 0) {
$thefile = $savefolder . "/" . $_FILES['myfile']['name'];
$theImageToResize=$_FILES['myfile']['name'];
header('Content-type: image/jpeg');
$res = '<img src="'.$theImageToResize.'" />';
}
}
else { $res = 'The file <b>'. $_FILES['myfile']['name']. '</b> exceeds max Size <i>'. $max_size. 'KB</i>'; }
}
else { $res = 'The file <b>'. $_FILES['myfile']['name']. '</b> has not an allowed File Tyle..'; }
}
$res = urlencode($res);
echo '<body onload="parent.doneloading(\''.$res.'\')"></body>';
If you have the binary data that comprises the image in hand, you can use a data URI to echo an <img> tag with the image embedded, like this:
$imageData = /* binary image data */
$mimeType = 'image/jpg'; // or image/gif or image/png, must be accurate
printf('<img src="data:%s;base64,%s" alt="resized image" />',
$mimeType, base64_encode($imageData));
This allows you to output the resized image as part of a web page. If you want to display just the image, you can simply output a suitable header and then echo the binary data:
header('Content-type: image/jpg');
echo $imageData;
die;
$_FILES['myfile']['name']
contains file name, not location, use
$_FILES['myfile']['tmpname']
instead.
To resize read about imagecopyresampled PHP function - theres lot's of tutorials about PHP image resizing. To output the image use imagejpeg or imagepng function - this functions will output your image to browser. Do not forget about proper headers, such as
header('Content-type: image/jpeg');
php how to get web image size in kb?
getimagesize only get the width and height.
and filesize caused waring.
$imgsize=filesize("http://static.adzerk.net/Advertisers/2564.jpg");
echo $imgsize;
Warning: filesize() [function.filesize]: stat failed for http://static.adzerk.net/Advertisers/2564.jpg
Is there any other way to get a web image size in kb?
Short of doing a complete HTTP request, there is no easy way:
$img = get_headers("http://static.adzerk.net/Advertisers/2564.jpg", 1);
print $img["Content-Length"];
You can likely utilize cURL however to send a lighter HEAD request instead.
<?php
$file_size = filesize($_SERVER['DOCUMENT_ROOT']."/Advertisers/2564.jpg"); // Get file size in bytes
$file_size = $file_size / 1024; // Get file size in KB
echo $file_size; // Echo file size
?>
Not sure about using filesize() for remote files, but there are good snippets on php.net though about using cURL.
http://www.php.net/manual/en/function.filesize.php#92462
That sounds like a permissions issue because filesize() should work just fine.
Here is an example:
php > echo filesize("./9832712.jpg");
1433719
Make sure the permissions are set correctly on the image and that the path is also correct. You will need to apply some math to convert from bytes to KB but after doing that you should be in good shape!
Here is a good link regarding filesize()
You cannot use filesize() to retrieve remote file information. It must first be downloaded or determined by another method
Using Curl here is a good method:
Tutorial
You can use also this function
<?php
$filesize=file_get_size($dir.'/'.$ff);
$filesize=$filesize/1024;// to convert in KB
echo $filesize;
function file_get_size($file) {
//open file
$fh = fopen($file, "r");
//declare some variables
$size = "0";
$char = "";
//set file pointer to 0; I'm a little bit paranoid, you can remove this
fseek($fh, 0, SEEK_SET);
//set multiplicator to zero
$count = 0;
while (true) {
//jump 1 MB forward in file
fseek($fh, 1048576, SEEK_CUR);
//check if we actually left the file
if (($char = fgetc($fh)) !== false) {
//if not, go on
$count ++;
} else {
//else jump back where we were before leaving and exit loop
fseek($fh, -1048576, SEEK_CUR);
break;
}
}
//we could make $count jumps, so the file is at least $count * 1.000001 MB large
//1048577 because we jump 1 MB and fgetc goes 1 B forward too
$size = bcmul("1048577", $count);
//now count the last few bytes; they're always less than 1048576 so it's quite fast
$fine = 0;
while(false !== ($char = fgetc($fh))) {
$fine ++;
}
//and add them
$size = bcadd($size, $fine);
fclose($fh);
return $size;
}
?>
You can get the file size by using the get_headers() function. Use below code:
$image = get_headers($url, 1);
$bytes = $image["Content-Length"];
$mb = $bytes/(1024 * 1024);
echo number_format($mb,2) . " MB";