I am writing down a function and it takes an argument which is the physical path of an image on server. I was wondering if it is possible in any way to obtain its original size in pixels.
In one variable I would like to store its width and in other variable its height. The challenge that made me ask this is because I have to obtain it on server-side thus any client-side solution would not help.
Try to use something like this:
<?php
$size = getimagesize ("img.jpg");
echo "<img src=\"img.jpg\" {$size[3]}>";
?>
An example will help you to get image height and width parameter in their separate variables like $width and $height.
list($width, $height, $type, $attr) = getimagesize('image/testimage.jpg', $info);
echo $width;
echo $height;
Related
Im working on a template for a website that has already more than 50,000 articles and images assigned to every article.
Before now the article image was visible only inside every article, but now I would like to use thumbnails.
I don't have access to modify the upload image form, so the solution should be something like virtual thumbs created from the original images...
What will be the best approach in this case?
Using Mr. Thumb like I advised a simple script to get it working would be
<?php
include './mrthumb.class.php';
// The image you are resizing. Can be a local path as well.
$image = $_GET['i'];
$quality = 100; // percent
// In this example we are resizing the image in proportionate sizes.
// Below we are specifying the MAX width and height.
$width = 100; // Pixels
$height = 130; // Pixels
// Start Mr. Thumb v1.0
$mrthumb = new MrThumb();
// Render the image
$mrthumb->render( $image );
// Resize the image proportionately
// $mrthumb->constrain( $width, $height );
$mrthumb->proportion( $width, $height );
// Finally, output the image to the browser!
// Optionally we can save the image to a destination
// $mrthumb->saveto( $destination, $filename, $quality );
$mrthumb->output( $quality );
// Clean up after you are done! ;)
$mrthumb->clear_cache();
?>
Then save that to your web server along with the mrthumb class and call a thumbnail in your webpage like
<img src="./mrthumb.php?i=images/myimage.jpg" alt="My Image" />
I'm looking to reduce image sizes using PHP on page load. I'm not really to sure how to achieve this, i've gotten as far as to obtain the dimensions but how would I reduce the sizes of these using only PHP?Here is my current code:
<?php
$stmt = $db->query('SELECT * FROM img_gallery ORDER BY list');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
$image = $row['url'];
list($width, $height) = getimagesize($image); //grab the image dimensions here
?>
<img src="" width="<?=$width ?>px" height="<?=$height ?>px" /> //image here
So the dimensions are reduced by a few hundred pixels each?
try php imagejpeg
imagejpeg (resource $image [,string $filename [,int $quality ] ] );
For more info click here,
You need to create a new canvas with the desired size and copy the resampled canvas there:
$newcanvas = imagecreatetruecolor($width,$height);
$oldcanvas = imagecreatefromjpeg($imagePath);
imagecopyresampled($newcanvas,$oldcanvas,0,0,0,0,$width, $height,$originalwidth,$originalheight);
I scored my website on gtmetrix.com.
It recommends adding image dimensions to all my images. The thing is, I need some way of adding these automatically, so if the image changes, the dimentions are updated.
What I have
<img src="bla.png">
What I'd like to have
<img src="bla.png" width="{width of image}" height="{height of img}">
Is there a php way or a jquery way to do this?
For a wordpress site.
PHP:
<?php
list($width, $height) = getimagesize("bla.png");
echo "<img src='bla.png' width='$width' height='$height'>";
?>
You can use image onload event to calculate the dimensions of image. Pure javascript approach, something like ;
var image = new Image();
image.onload = function()
{
//after load complete you will get the image dimensions here from
//image.width and image.height
}
image.src = 'image url';
In php it's getimagesize($file) if you are outputting images dynamically.
You should do it with PHP not with javascript. If you add it with jQuery / javascript, the width and height would be added after loading. The main reason of specifying width and height is to let the engine render the page faster. It would not be of any help if it as added after loading.
You can use the index 3 of the returned array from getimagesize() directly in the image tag. It contains a string with height="yyy" width="xxx" an can be used directly in an IMG tag.
<?php
list($width, $height, $type, $attr) = getimagesize("file.png");
echo "<img src='file.png' $attr />";
?>
You can visit http://php.net/manual/en/function.getimagesize.php for more details on this function.
I have a simple PHP script that enables users to upload images on a server. I am after some help in displaying these images as thumbnails in an HTMl page and then letting the user click on these thumbnails and then the original picture is displayed in a new page.
Can I use straight HTML for this? Or do I need some combination of javascript or PHP variant?
I know that there are many questions about this on stackoverflow, and I have tried them, but nothing is what I am after.
I would prefferably like the thumbnails be created on the 'fly' rather than me personally having to create each thumbnal when a user uploads an image.
So basically what language should I use to do this? And also can I have some source code if possible?
thanks
Creating thumbnails every time they are requested is a very bad idea - it takes a lot of processing power, which would be easily saved by keeping them around the first time you create them. I would suggest putting the thumbnail creation in the php script that processes the file upload, so that you save the image and its thumbnail to disk at the same time. You can also keep the thumbnail in memory, or wait until the first time it's requested to create it, but either way you cannot re-generate it every time it is requested.
It is possible to use html to change an image's size, by simply setting the width and/or height properties:
<img src='foo.jpg' alt='foo' width='500' height='300'/>
However, this is a bad idea if you aren't certain that the user will later want to view the full-sized image. The reason is that a thumbnail has a smaller filesize than the full image: if the client only wants to view the thumbnail, then you don't want to waste bandwidth (= your money and the client's time) sending them the full image.
As for your interface, you don't need javascript to accomplish that, just html. However, you will need a server-side script to create the thumbnails that your html page links to.
There are plenty of php thumbnail scripts out there.
Either you use a rewriter to still show the original path, but server a php thumbnail version. Or you have to have the url change to something like:
<img src="thumb.php?file=path/to/picture.jpg&size=128" />
Mighty Stuff
phpThumb
Are just such two. Best configured to utilize the cached folder. I use a modified version of the first script at work.
Here's a PHP script you can build appon only works with jpg images.
It will scan through a directory, normalize the image to a decent dimension and also make a thumb on the fly, then on next refresh it wont need to reprocess the image as its already present in the thumbs dir. Hope it helps...
Script placement
Root>
thisscript.php
/images/
someimage.jpg
someimage2.jpg
thisscript.php
<?php
// config section
$path = "./images/";
$thpath = $path."thumbs/";
// end configration
// Open the directory
$do = dir($path);
// now check if the thumb dir is available if not, create it!!
if (!is_dir($thpath)){
mkdir($thpath);
}
$output = '<div>';
while (($file = $do->read()) !== false){
if (is_dir($path.$file)){
continue;
}else{
$info = pathinfo($path.$file);
$fileext = $info['extension'];
if (strtolower($fileext) == 'jpg'){
if (!is_file($thpath.$file)){
//Normalize Super lrg Image to 750x550
thumb_it($path, $file, $path,750,550,99);
//Make Thumb 200x125
thumb_it($path, $file, $thpath,200,125,99);
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}else{
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}
}
}
}
$output .='</div>';
echo $output;
//Functions
function thumb_it($dirn, $file, $thumbdir,$rwidth,$rheight,$quality){
set_time_limit(0);
$filename = $dirn.$file;
$thfilename = $thumbdir.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $file);
// get the filename and the thumbernail directory
if (is_file($filename)){
// create the thumbernail from the original picture
$im = #ImageCreateFromJPEG($filename);
if($im==false){return false;}
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
if (($width < $rwidth) && ($height < $rheight)){
$n_height = $height;
$n_width = $width;
}else{
// saveing the aspect ratio
$aspect_x = $width / $rwidth;
$aspect_y = $height / $rheight;
if ($aspect_x > $aspect_y){
$n_width = $rwidth;
$n_height = $height / $aspect_x;
}else{
$n_height = $rheight;
$n_width = $width / $aspect_y;
}
}
$newimage = imagecreatetruecolor($n_width, $n_height);
// resizing the picture
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
// writing to file the thumbnail
if(file_exists($thfilename)){chmod($thfilename, 0777);}
Imagejpeg($newimage, $thfilename, $quality);
imagedestroy($newimage);
imagedestroy($im);
}
}
?>
I need to show multiple posts on my website. These posts are combined of internal and external posts. The external posts are periodically imported and saved in my DB using a cronjob.
Before showing the posts I extract the text from all HTML. In addition I try to locate the first image contained in the post, continuing until I find an image which height & width meets my requirements. (I only show a small version of the text, and one picture from the post as a teaser)
For the purpose of finding the most suitable picture, I use getimagesize, but unfortunately this often creates PHP Execution time of several seconds!
How can I speed up my function below? I'm desperate for tips and good tweaking methods!!
Thanks in advance
//extract text without tags from blog post
$content = str_get_html("".$post_text."")->plaintext;
$max_width = 475;
$picture_id = 0;
//fetch images from blog post
foreach($html->find('img') as $e) {
//get picture attributes
list($width, $height, $type, $attr) = getimagesize((is_absolute_url($e->src) ? $e->src : $_SERVER['DOCUMENT_ROOT'].$e->src));
//adjust image width & height, so it's the size of the page
$new_width = $max_width;
$new_height = $new_width / $width * $height;
//find percentage of current width versus max width
$percentage = ($width / $max_width) * 100;
//select picture for display and resizing if the picture is large enough (we don't want to stretch it too much)
if($percentage >= 60) {
$e->width = $new_width;
$e->height = $new_height;
$picture = array('src' => $e->src, 'width' => $e->width, 'height' => $e->height);
//stop after first picture is found :: we only need one per post
if (++$picture_id == 1) break;
}
}
Reason: It is a very well known issue that getimagesize works slow on remote files.
Solution: It is advised to store the files on your local server (temporarily) and then do getimagesize on it.
When you pass a url as a parameter to getimagesize, it gets the image through HTTP, what is a slow process.
You should get its size only the first time and save it in a database for the future.