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.
Related
I need to get the height and width of an image in order to set stretch it according to the size of the div. I could have used max-width:100% and max-height:100% but there are some images that are smaller than the div so I decided I would just manually assign the width and height.
I prefer to get these dimensions in php imagesy() and imagesx().
<?php $h=imagesy($list['Image1']);
$ w = imagesy($list['Image1'])?>
<img src="<?php echo $list['Image1']; ?>"
<?php if($h>$w) echo"style='height:100%;'";
else echo"style='width:100%;'"; ?> />
PHP functions like getimagesize() will return the dimensions of an image. But you are first going to have the load the image into the function. In other words you're going to have to fetch the image first.
If you have allow_url_fopen enabled then you should be able to invoke it with an absolute URL:
$size = getimagesize("http://www.example.com/gifs/logo.gif");
Okay, I was able to read just now that getimagesize returns an array with the width at [0] and height at [1]. So I was still able to compare them directly, hence, dynamically resizing them to fit the div containing the image. ;)
<?php $h=(getimagesize($list['Image1']));?>
<img src="<?php echo $list['Image1']; ?>"
style="<?php
if($h[0]>$h[1])
{
echo'width:100%;margin:0 auto;';
}
else
{
echo'height:100%;vertical-alignment:auto;';
} ?>"
alt="<?php echo $list['Image1']; ?>" />
on my mission to use ckEditor as a BBCode editor i am faced with an issue directly for my site.
I have user submitted content that can contain [img] tags.
I really want the images to have a width of 100%, which is fine. I convert any [img] tags to html and apply a class which is styled as i wish.
function basicbbcode($text) {
$text = str_replace("[IMG]", "<img class='buildimage' src='", "$text");
$text = str_replace("[/IMG]", "'>", "$text");
$text = str_replace("[img]", "<img class='buildimage' src='", "$text");
$text = str_replace("[/img]", "'>", "$text");
}
The issue is when someone uses a small / low res image. I dont wish to stretch that image because its going to look horrible.
My aim was to find a threshold, so if the image is more than 800px wide, give it the class of buildimage. If its smaller, give it a class of buildimage-small.
I would then just keep the natural size of that image. I am trying to promote the users providing high quality images but at the same time want to keep the site looking great and no having poorly stretched images because there is res is small.
So, is there a way to check the image size when it is out from the database as the $text variable and then act accordingly. Ideally with php, but maybe jquery?
No idea on this one, possible?
You can use getimagesize():
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.
<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
?>
Source: http://us3.php.net/getimagesize
To do it in jQuery it could be as simple as:
var box = $("#boxWithImageInside"),
img = box.find("img.buildimage");
if (img.width() > box.width()) {
img.width("100%");
img.height("auto");
}
The code was not tested, so you may have to adjust it to to what you need.
If you want to solve your problem on client side maybe this helps : FIDDLE
$(function () {
isImgLargerThan800px = function (src) {
var img = new Image();
img.onload = function () {
if (this.width < 800) {
alert('this image need SMALL class')
} else {
alert('this image need LARGE class')
}
};
img.src = src;
};
//TEST
$('a').on('click', function () {
isImgLargerThan800px($(this).text());
alert('Now checking for image size of URL : ' + $(this).text())
})
});
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 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;
I am building a custom wordpress theme and have a slideshow on the front page displaying images from blog posts.
Now if the image is over 300px in height I want to force its widthand center it vertically. So my question is:
Is there a way, in php or javascript to get the height of an image by only using the URL of the image?
EDIT: I tried this: <?php list($height) = getimagesize(echo catch_that_image()); echo "<p>$height</p>"; ?> where catch_that_image() returns the URL, but somehow this doesn't work (I think the first echo breaks it). Any ideas?
Thank you for your help.
image by only using the URL of the image?
var img = new Image();
img.onload = function() {
alert('The size is ' + this.width + 'x' + this.height);
};
img.src = 'some image URL';
Try it
http://jsfiddle.net/NPSMN/
ps:
I tried this: ... where
catch_that_image() returns the URL, but somehow this doesn't work (I
think the first echo breaks it). Any ideas?
did you look closer at your code? echo outputs to the browser, not to the argument of the function.
<?php
list(,$height) = getimagesize(catch_that_image());
echo "<p>$height</p>";
?>
See getimagesize() in PHP. That will do what you're looking for.
http://php.net/manual/en/function.getimagesize.php
<?php
$url = "http://www.example.com/image.jpg";
list($width, $height) = getimagesize($url);
echo "Width: $width<br />Height: $height";
?>