Setting a hard limit for image size using PHP - php

I have this script for displaying a slideshow for a client.
I'm looking for a quick way of making the "img" not go over a certain size.
This is my original code:
<script type="text/javascript">
$(function() {
$('#test2').crossSlide({
speed: 15,
fade: 1
}, [
<?php
$directory = "photos/";
$images = glob("" . $directory . "*.jpg");
$arrLength = count($images);
foreach($images as $key=>$image){
echo("{src: '$image', dir: '$quotes[$random]'}");
if($key < $arrLength - 1){ echo ", "; }
}
?>
]);
});
</script>
Prehaps I could use some sort of external file?
Link it like.. image.php?img=foo.jpg (with the max script in there?)
Any help would be great,
Thanks!

getimagesize() is a start.
if( array_product(getimagesize($image)) < 2500 ) { // Check area
// do stuff
}
list($width, $height) = getimagesize($image);
if( $width < 500 && $height < 400 ) { // Check dimensions
// do stuff
}
In the future, do a quick Google. PHP is a language that supports a lot out of the box. Often times, you'll be able to find something in the docs.

Provided that images are uploaded to the website, you should not allow images to be uploaded that are over a certain size of megabytes.
If you're talking about dimensions, you can use the max-width: and max-height CSS attributes to make sure images don't go over a certain size.
If you're looking to scale images (or anything else) proportionately, to fit the size of their container, you can use the JQuery image resize plugin for that.

Related

PHP after image loaded from directory - wrong orientation

Actually i'm using a simple PHP snippet to iterate through a directory to grab images and insert them into the html markup.
Now im facing the problem that all images are oriented in landscape. So also portrait images are oriented as landscape images.
Here's my snippet:
<?php
$projectpath = 'Projects';
$projects = glob($projectpath . '/*' , GLOB_ONLYDIR);
foreach($projects as $key=>$value): ?>
<section class="project">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="project-images">
<?php
$handle = opendir(dirname(realpath(__FILE__)).'/'.$value);
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img class="img-responsive" alt="'. $file .'" src="'. $value .'/'. $file .'"/>';
}
}
?>
</div>
</div>
</div>
</div>
</section>
<?php endforeach; ?>
So what do i'm missing here? Any suggestions?
I doubt those images really have different orientations. More likely all images are in landscape layout (greater width than height), so the visualization is correct from a technical point of view.
I guess you usually look at the images with some viewer on your PC which auto rotates the images based on some orientation flag stored inside the images meta data. But such flag does not change the real, technical orientation (or better resolution). Instead such flag is only a hint for visualization of the images. Your project does not consult that flag, that is why your images appear to be rotated, whilst in reality they are not.
So the solution is one of two options:
rotate the images prior to using them inside your project, so that their real, technical orientation is correct and the images only have to be displayed without any additional rotation.
use js or php or whatever to detect that orientation flag and evaluate it. Based on the outcome you can set some css class which results in a css based rotation of those images that need to be rotated for visualization.
Here is simple PHP example to check if the image is portrait or landscape:
<?php
$imagePath = 'images/imagename.png';
$imageSize = getimagesize($imagePath); //returns an array
$imageWidth = $imageSize[0]; // array key 0 is width
$imageHeight = $imageSize[1]; // array key 1 is height
if($imageWidth < $imageHeight){
echo '<img class="ROTATE">'//add the rotate class
} elseif($imageWidth > $imageHeight){
echo '<img>'//do not add the rotate class
} else {
echo '<img>'//do not add the rotate class
?>
Take in mind that this is only an example and that you'll have to tweak the script to work properly for you.

one single image url for an avatar to display random image from a folder (server-side php script)

a long time ago i once did found a php script that contained only about 6 short lines of it if i remember correctly. Yet no luck, i couldn't find anything like that anymore, so i am gonna ask for help from you.
It was only one file "rotate.php" and a folder that contained all by myself chosen images, the script was supporting different dimensions and with different extensions (jpg, png, gif) as i remember.
Script generated one single url that could be used as an image url for an avatar or between [img] tags on forums with bbcode support.
Respectively, when someone visits my forums profile or sees my comment on forums, per every visit/refresh it always shows a random image as my avatar.
There seems to be many simple variations to create a random image slideshow for my own websites logo or something, but i can't figure a way to make it work for external sites like with previously mentioned single url.
Give me some hope, thanks.
Hope it helps, you can use PHP inbuilt function called opendir($path) to open the folder in path and read the directory.
<?php
function getImagesFromDir($path) {
$images = array();
if ( $img_dir = #opendir($path) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {
// checks for gif, jpg, png
if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}
function getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
$num = array_rand($ar);
return $ar[$num];
}
$path = 'imagesfolder/';
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);
?>
IN HTML:
<img src="<?php echo $path . $img; ?>" alt="" />
Ref: http://www.dyn-web.com/code/basics/random_image/random_img_php.php

Display actual image size within existing PHP code

I am building a Wordpress website. Please don't mind that I'm not working on a local or testing server, or my code. It's messy at the moment while I try to figure out this programming bit. By going to my website, you will see a row of images along the top, which is within a jcarousel.
It works, but if you hit next until you get to the "portrait" photo, there is a gap. The gap is because I have to set a width in pixels within my HTML or CSS for the carousel to work correctly. If set to auto, the carousel collapses. Makes sense to me, but it's frustrating that I cannot work around that. I want the "landscape" and "portrait" photos to have an identical height of 427, but the width I want it to self-adjust to the actual image size.
So I think I understand this bit after playing around for 3 days - I cannot tell you how many carousel codes I've used. Originally I thought that was the problem, and some were. I found out, widths of each image slide are set within the JavaScript, so if I gave it a width of 640, I would get the same result as I am getting now.
My first question is this:
I'm calling my images from a directory on my server, written specifically for Wordpress (author). Here is the code:
<?php
$uploads = wp_upload_dir();
if ($dir = opendir($uploads['basedir'].'/picture-atlantic')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
echo '<ul>';
foreach($images as $image) {
echo '<li><img src="';
echo $uploads['baseurl'].'/picture-atlantic/'.$image;
echo '" alt="" width="auto" height="auto" /></li>';
}
echo '</ul>';
?>
As you can see, it's calling from the picture-atlantic directory and displaying it within an unordered list, which is required for some reason with my jcarousel.
Finally: how can I use this same code to get my images, but also display them at their actual sizes? In the code above, if I define the width and height, it does it for all the images. However, as I mentioned before, I have portrait pictures that use different dimensions. I found this code: erikastokes.com/php/how-to-get-image-size-with-php.php, but I'm not sure how to implement it in my existing code.
Could someone please help me rewrite it?
You could set the width of the image to 100% and add a style to reposition portrait images at top: -50%;, but you will not be able to see the entire image if it is in landscape.
<?php
$uploads = wp_upload_dir();
if ($dir = opendir($uploads['basedir'].'/picture-atlantic')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
echo '<ul>';
foreach($images as $image) {
$myimage = $uploads['baseurl'].'/picture-atlantic/'.$image;
$size = getimagesize($myimage);
$top_50 = '';
if($size[1] > $size[0]) {
$top_50 = 'style="position: realative; top: -50%;"';
}
echo '<li><img src="';
echo $uploads['baseurl'].'/picture-atlantic/'.$image;
echo '" alt="" width="100%" height="auto" '.$top_50.'/></li>';
}
echo '</ul>';
?>
Welp, I read that I cannot use getimagesize if I'm already using php to dynamically display my images. I ended up settling with uploading images through Wordpress, within an unordered list, and placing my carousel markup in the post loop. It works just fine now.
Oh, I read on http://www.css-tricks.com that Wordpress adds the image attributes automatically, and that is what solved the image width problem while displaying landscape and portrait style photos at 100% across the screen.
To those who are trying to do a similar task, don't use jj nexgen gallery for inserting your images. jj nexgen gallery is a great plugin, along with the others associated with it. It just won't work for what I was trying to do because it doesn't add the attributes to the image. I would download their wordpress plugins if you aren't trying to do this, so I'm guessing the majority of you.
Thanks again for the replies.

Code for displaying thumbnail images

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);
}
}
?>

Slow getimagesize

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.

Categories