Can I add a resize function to this script? - php

I am not really good in PHP but the images that will show on the webpage of mine will be the main resolution. I would like to downscale it but I have no clue how.
<?php
$images = glob('*.{gif,png,jpg,jpeg}', GLOB_BRACE); // Formats to look for
$num_of_files = 2; // Number of images to display
foreach ($images as $image) {
$num_of_files--;
if ($num_of_files > -1) // This made me laugh when I wrote it
{
echo "<b>" . $image . "</b><br>"
. "Created on " . date('D, d M y H:i:s', filemtime($image)) . "<br>"
. "<img src='" . $image . "'><br><br>";
} // Display images
else {
break;
}
}
?>

It seems like you just want to resize the image shown in the browser, right? In that case some simple styling would do the trick:
. "<img src='" . $image . "' style='width: 200px'><br><br>";
Change the 200px to whatever width you want, the height will scale proportionally.
You should also have a look on how to use CSS classes.
If you rather want to scale the actual image file (i.e. if it resides on your server), check out ImageMagick.

Related

Display images with different extension (PHP)

Below are coding that I currently use to display images from database :
$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect');
$query = mysqli_query($con,"SELECT * FROM images");
while($row=mysqli_fetch_assoc($query))
{
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
}
Problem with those coding : It only display images with .png extension because I am using echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />'; to display it.
What I am trying to do : I wanted to display images with extension .jpeg .png and .gif as well.
Is there anybody that can help me with other simple way of displaying images? Thank you.
Store the format in the database as well:
$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect');
$query = mysqli_query($con,"SELECT * FROM images");
while($row=mysqli_fetch_assoc($query))
{
echo '<img src="data:image/' . $row['format'] . ';base64,' . base64_encode($row['image']) . '" />';
}
Hi Just get the image extension and use it
$ext = pathinfo($row['image'], PATHINFO_EXTENSION);
echo '<img src="data:image/' . $ext . ';base64,' . base64_encode($row['image']) . '" />';
#FrankerZ already gave correct solution but if you have already stored base64 images on your database it will be problematic to add format column.
You can discover the mime type of image from base64 like that;
$img = $row['image']; // base64 of your image
$fileInfo = finfo_open(); // file info resource
$mimeType = finfo_buffer($fileInfo, $img, FILEINFO_MIME_TYPE);
If you have already existing records, do not apply this methodology on your each iteration. Simply add new column to your database, and fill/update these new colums using this methodology. After that, use #FrankerZ 's solution.

Resize copied image on upload as thumbnail

I am working on an uploader and slowly getting it working, I am uploading 3 images at once, and setting arrays for each one as keys, with an increment of ++1. I am wanting to resize the image before it gets copied to the thumbnail folder.
I have this code.
Everything works with it.
As you see, I started on getting the file info, but after that I am totally stuck on what to do after to resize the image proportionally with a maximum width of xpx and height to match it without looking distorted.
Any help would be really appreciated. Thank You.
EDIT --- I started working on it myself and wondering if this is the right approach to what i am doing.
<?php
if (isset($_POST['addpart'])) {
$image = $_FILES['images']['tmp_name'];
$name = $_POST['username'];
$i = 0;
foreach ($image as $key) {
$fileData = pathinfo(basename($_FILES["images"]["name"][$i]));
$fileName[] = $name . '_' . uniqid() . '.' . $fileData['extension'];
move_uploaded_file($key, "image/" . end($fileName));
copy("image/" . end($fileName), "image_thumbnail/" . end($fileName));
// START -- THE RESIZER THAT IS BEING WORKED ON
$source = "image_thumb/" . end($fileName);
$dest = "image_thumb/" . end($fileName);
$quality = 100;
$scale = 1 / 2;
$imsize = getimagesize($source);
$x = $scale * $imsize[0];
$y = $scale * $imsize[1];
$im = imagecreatefromjpeg($source);
$newim = imagecreatetruecolor($x, $y);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $x, $y, $imsize[0], $imsize[1]);
imagejpeg($newim, $dest, $quality);
// END -- THE RESIZER THAT IS BEING WORKED ON
$i++;
}
echo 'Uploaded<br>';
echo 'Main Image - ' . $fileName[0] . '<br>';
echo 'Extra Image 1 - ' . $fileName[1] . '<br>';
echo 'Extra Image 2 - ' . $fileName[2] . '<br>';
echo '<hr>';
}
?>
thanks
Use GD library.
Create input image object using imagecreatefromstring() for example: imagecreatefromstring(file_get_contents($_FILES['images']['tmp_name'][$i]))
It's the simplest way.
Another option is to detect file type and use functions like imagecreatefromjpeg (), imagecreatefrompng(), etc.
Create output empty image using imagecreate()
Use imagecopyresampled() or imagecopyresized() to resize image and copy+paste it from input image to output image
Save output image using function like imagejpeg()
Clean memory using imagedestroy()
The built-in image manipulation commands of PHP makes your code difficult to understand and to maintain. I suggest you to use a library which wraps it into a more productive way.
If you use Intervention/image, for example, your code will look like this:
<?php
// target file to manipulate
$filename = $_FILES['images']['tmp_name'];
// create image instance
$img = Image::make($filename);
// resize to width, height
$img->resize(320, 240);
// save it!
$img->save('thumbs/'. uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION));
Read the full documentation here: http://image.intervention.io/use/uploads

Place images from a folder into list with preview

I need to build a dynamic image gallery plugin for Joomla! that will go into a specific folder and pull out all images from the folder and show first of them as a large preview image and the rest in a list. Afterwards I will need to make the preview image open in a lightbox if clicked and in the lightbox I need to have the small thumbnails of listed images as well.
But know I need just php to go to the folder and pull out all the images from the folder specified. I have googled a bit and found some solution but this does not work for some reason I don't understand. Could someone tell me please, what is wrong with the code?
Thanks!
<div id="images">
<?php
$images_dir = 'images/';
$scan = scandir($images_dir);
echo '<img src="' . $images_dir . $scan[2] . '"alt="image" />';
?>
<ul id="smallimages">
<?php
for($i=0; $i<count($scan); $i++){
$ext = substr($scan[$i], strpos($scan[$i], '.'), strlen($scan[$i]-1));
$filetypes = array('.jpg', '.JPEG', '.jpeg');
if(in_array($ext, $filetypes)){
echo '<li><img src="' . $images_dir . $scan[$i] . '" alt="' . $scan[$i] . '"></li>';} }?></ul>
</div>
I think it's because you haven't defined the path correctly. Try using the following:
$images_dir = JUri::root() . 'plugins/content/plg_new/images';
JUri::root() is the root of your Joomla site so change the path from there on accordingly to where ever your images are located
Hope this helps
Does this work for you?
<?php
$image_directory="hrevert/images/";
$pictures = glob("$image_directory*.{gif,jpg,png}", GLOB_BRACE);
//displays the first image
$first_img=reset($pictures);
echo "<img src=\"".$first_img."\" width='20px' />";
//loops through other images and prints them
echo "<ul>";
foreach($pictures as $picture) {
echo "<a href='$picture'><img src=\"".$picture."\" width='20px' /></a>";
}
echo "</ul>"
?>

PHP imagick get all images from tiff

I am trying to load a tiff file and count the number or images and then then dispaly each image as a PNG thumbnail.
The count part is ok it counts 6 which is the correct number of pages in that tif, the code then lists 6 of the same image which is the the first page of the tiff. Cant workout if there is a problem with my loop or I am simply not using the imagick functions correctly.
Can anyone help
<?php
$image2 = new Imagick('http://mysite.org.uk/tiftest/2.tif');
/* Create the object */
$image = new Imagick('http://mysite.org.uk/tiftest/2.tif');
$count = $image->getNumberImages();
echo "<h3 style=\"font: bold 12pt Arial\">Total Number of Images Extracted ".
"from the TIF : ".$image->getNumberImages()."</h3>";
for ($x = 1;$x <= $image->getNumberImages();$x++) {
$image->pingImage( $image2 );
$image->readImageFile( $image2 );
$image->setImageFormat( 'png' );
$image->thumbnailImage(100, 0);
echo "<img id='" . $x . "' src='data:image/png;base64,".base64_encode($image)."' />"; } ?>
You will have to move to the previous image using $image->previousImage()
Iterate over the number of images backwards and move to the previous image to get all of them, might also be able to use while ($image->hasPreviousImage()) {} construct
Oh, and dont use readImageFile, you already have the image in-memory.
I sussed it !!
Here is the code to get all the sepearte pages out of the tif and display them as PNG's :
<?php
/* Create the object */
$image = new Imagick('http://mysite.o.uk/tiftest/1.tif');
$count = $image->getNumberImages();
echo "<h3 style=\"font: bold 12pt Arial\">Total Number of Images Extracted ".
"from the TIF : ".$image->getNumberImages()."</h3>";
$x =0;
foreach ( $image as $image ) {
$x++;
$image->setImageFormat( 'png' );
$image->thumbnailImage(150, 120);
echo "<img id='" . $x . "' src='data:image/png;base64,".base64_encode($image)."' />";
}
?>
However now I need to know how to display them as true PNG's without using base63 encoding, any ideas ???

Loop through directory

I'm trying to use PHP to bring in every image from a specific directory and turn them into HTML objects by wrapping some markup around them.
Right now I am just trying to get the images on the page. In the future I would also like to bring in a text file that has the same file name as the image(slide#4.jpg and slide#4.txt).
This is what I have so far.
<?php
$dir = "includes/pages/products/*.jpg";
$images = glob( $dir );
foreach( $images as $image ):
$file = basename($image);
$file = basename($image, ".jpg");
echo "<div class='"prod-cont"'>" . "<h4>" . $file . "</h4>" . "<img src'" . $image "' />" . "</div>";
endforeach;
?>
I'm not having much luck getting this going, any help is appreciated.
Remove the second $file = line, and make sure you're generating correct HTML.
echo "<div class='prod-cont'><h4>".$file."</h4><img src='".$image."' /></div>";

Categories