I am trying to understand why GLOB is skipping the first image in whatever folder I direct it too. I work around it by placing a dummy image named so it is listed first but I would like to solve this irk in a more efficient way. Here is my code.
<?php
// This retrieves images from a selected folder - anchor with a data-xx-xx attribute
// via jQuery - click - the data-xx-x value is put into a hidden field : foldpath
// It all works fine BUT, it always fails to return the first image in a folder
// I get around it by placing within each folder a dummy image called aa.jpg
// which hopefully will always be the first image but it is not really a
// satisfactory solution.
if($_POST && isset($_POST["foldsub"]) && isset($_POST["foldpath"]) ){
// hidden field $_POST["foldpath"];
//A typical path might be :
// ../images/products/CLIENTS_images/bridal_whatnots/bridal_belts
//the ../ prefix is reoved via php when the page is displayed and replaced by DIR
// for testing between admin folders and the main root folders I use the relative paths.
$fp = $_POST["foldpath"];
$files = glob($fp ."/" ."*.*");
//this is a pop up page which needs to stay open after the selection has been made
echo "<script> $(\"#imgstuff\").css({\"display\":\"block\"});</script>";
//the form closed on whgen the close x is selected
}else
{
//default
$files = glob("../images/bannerImgs/*.*");
}
for ($i=0; $i<count($files); $i++)
{
$image = $files[$i];
$supported_file = array(
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
// print $image ."<br />";
$path = $image;
$path1 = DIR;
if (strpos($path, $path1) !== false) {
$path2 = $path;
}else{
$path2 = str_replace('../', '', $path);
$path2 = $path1.$path2;
}
$fn = basename($path);
$fn = basename($path, PATHINFO_EXTENSION);
if($fn!="aa.jpg"){
echo '<p class="imgdet">';
// echo '<span class="imglongpath">' . $path2 .'</span>';
echo '<img src="'.$image .'" alt="Random image" />';
echo '<span class="imgname">' . $fn .'</span>';
// echo '<span class="imgmesg">Now click Confirm / Set Choice</span>';
// "<br /><br />";
echo "</p>";
}
} else {
continue;
}
}
?>
Related
I'm using Ghostscript 9.50 and ImageMagick 7.0.9 to generate first page thumbnail from uploaded PDF documents.
Here's my code I've got from http://www.rainbodesign.com/pub/image-tools/pdf-to-jpg.html then I use it as a function in my Ebook controller
function thumbnail(){
$pdfPath = $_SERVER['DOCUMENT_ROOT'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']); // Path to PDF files on the server
$imagesPath = $_SERVER['DOCUMENT_ROOT'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']) . 'ebooks/'; // Path to your images directory on the server
$thumbsPath = $imagesPath . 'thumbnails/'; // Path to image thumbnails directory
$thumbsize = 250; // Width of thumbnail images (set to 0 for full size)
$pageNo = 0; // Page # from PDF to convert (ordinal!)
// Constants and Defaults
// ----------------------
$theWMType = 'jpg:';
$extension = '.jpg';
$pdf = '';
$error = '';
// Fetch user settings and default overrides via query string
if (isset($_GET['src'])) { $pdf = $_GET['src']; }
if (isset($_GET['path'])) { $pdfPath = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['path']; }
if (isset($_GET['width'])) { $thumbsize = $_GET['width']; }
if (isset($_GET['page'])) { $pageNo = $_GET['page'] - 1; } // Page # is ordinal in ImageMagick!
if ($pdf == '') { $error .= "Source Image Not Specified.<br>\n"; }
$original = $pdfPath . $pdf; // Add file path to PDF file name
$originalBase = basename($pdf,'.pdf'); // Extract PDF file name basename w/o extension
$thumbnail = $thumbsPath . $originalBase . $extension; // Use basename for the thumbnail .jpg file name
if (!file_exists($original)) { // Make sure PDF file exists
$error .= "Source PDF Document Not Found<br>\n" . $original . "<br>\n";
}
// Fix file name(s) to select 1st page of PDF and enquote $original if it/they contain <space>s.
if (strpos($original, ' ') !== false) {
$original = "\"" . $original . "[$pageNo]\""; // Enclose file name in quotes and add Page #
$thumbnail = str_replace(' ', '_', $thumbnail); // Replace <space>s with underscores
} else {
$original = $original . "[$pageNo]"; // Just add Page # to PDF $original
}
// Check to see if the thumbnail already exists in the "cache"
if (!file_exists($thumbnail)) {
// No! Convert PDF to JPG with ImageMagick/GhostScript now!
if ($error == '') {
$wmCmd = "convert $original";
if ($thumbsize != 0) { $wmCmd .= " -resize " . $thumbsize . "x"; }
$wmCmd .= " $theWMType$thumbnail";
$result = exec($wmCmd);
} // endif $error == ''
// A little error-checking overkill
if (!file_exists($thumbnail)) {
$error .= "Convert Failed! Can't find $thumbnail<br>\n";
$error .= $result . "<br>\n" . $original . "<br>\n" . $thumbnail . "<br>\n";
} // endif !file_exists
} // endif !file_exists($thumbnail)
if ($error != '') { // Did we see an error?
header("Content-type: text/html\n"); // Yes! Send MIME-type header for HTML files
echo($error);
} else {
header("Content-type: image/jpeg\n"); // No. OK, send MIME-type header for JPEG files
echo(file_get_contents($thumbnail)); // Fetch image file contents and send it!
} // endif $error
exit;
}
But when I want to display the thumbnail there:
<img src="<?= base_url('ebook/thumbnail?src=ebooks/' . $e->file) ?>" width="100" alt="pdf document">
The image can't displayed and when load the URL from the img tag 'src' in my browser to check, I get this error :
Convert Failed! Can't find D:/htdocs/halokes_library/ebooks/thumbnails/XML_Bible.jpg
D:/htdocs/halokes_library/ebooks/XML_Bible.pdf[0]
D:/htdocs/halokes_library/ebooks/thumbnails/XML_Bible.jpg
Any thoughts?
I had the exact same error using the exact same code from rainbodesign.com. I set the files/directory the code writes its thumbnail to 777 permissions and still the code is not writing to the thumbs directory. So I checked what is actually passing to the pdf2jpg.php program from rainbodesign and found the path to the pdf was not "from" the root directory, but included it. I made adjustments to what variables are being passed to pdf2jpg.php, along w/the permission adjustment and it now works!
example src call:
/pdf2jpg/pdf2jpg.php?src=/7751/Scan_200512.pdf&mdir=7751
I am trying to make an image gallery system with keywords.
Each image has a .php file with a few variables:
$keywords = 'Keywords that describe the image';
$src = 'directory path leading to the image';
$other = 'any specific remarks about the image';
the files of each image are stored in a directory called imageinfo.
How can I get all the images listed in the files in the directory imageinfo to display in one .phpfile? They all have the same variable names. Can I make a search engine system to search the files?
This is very hard to explain, and I understand if you don't understand - feel free to grab a diet coke and come and write your problems in the comments!
Try this:
(you have to fille the right imageinfo folder in)
<?php
// Folder with all the Info PHP files
$infodir = __DIR__ .'/imageinfo/';
// read Folder contens
$files = scandir( $infodir );
// Array to store all image infos
$allimages = array();
// loop, file for file
foreach ($files as $file) {
// . and .. are in the array of files, but we don't need them
if( $file != '..' && $file != '.' ){
//path to actual Image Info file
$thisfile = $infodir.'/'.$file;
//Check if file exists
if( is_file( $thisfile ) ){
//parse file
include( $thisfile );
//add vars to Array
$allimages[] = array(
'keywords' => $keywords,
'src' => $src,
'other '=> $other
);
}
}
}
//Output Data of all files
echo '<pre>';
print_r( $allimages );
echo '<pre>';
//show images in browser
foreach ($allimages as $image ) {
echo '<div class="img">';
echo '<img src="'.$image['src'].'" title="" alt="" >';
echo '<br />';
echo $image['keywords'];
echo '<br />';
echo $image['other'];
echo '</div>';
}
?>
I have a form that uploads data to the DB and this includes the path to the directory where images are uploaded. Everything works, except for the fact that the image won't display.
Viewing the source in my browser tells me that the image is found but I keep getting the broken image icon.
Here's my code:
$dir = "../uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
if (count($fileArray) > 0) {
$image = $fileArray[0];
echo "<img src='$image' width='300px'>";
}
In the form you can upload multiple files. In the DB, the files get a random prefix then file name, like 3456456745654_imageName.jpg.
If multiple files are uploaded, they are split with an asterisk (*), which is why I'm exploding.
Then, to print only one image, I'm checking for the number of images relevant to a specific record then displaying only the first one.
PS. This code works for displaying all the images relevant to a selected image:
$dir = "uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
foreach ($fileArray as $file) {
if (file_exists($dir . $file)) {
echo "<img class='images' src='$dir/$file' width='300px;'>";
}
}
But that's for a different page that displays a selected vehicle's information, including all images.
I need to show only one image per vehicle on the landing page that lists all vehicles.
Had to use the directory:
$dir = "../uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
if (count($fileArray) > 0) {
$image = $fileArray[0];
if (file_exists($dir . $image)) {
echo "<img class='images' src='$dir/$image' width='300px;'>";
}
}
I found a useful php code which displays the photos in a folder directory as a image preview. The issue is my host provider blocks one of the script commands, "Shell_exec()", so the php code doesn't work.
Any way of getting the code to run without using shell_exec?
<?PHP
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif");
?>
<?PHP
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
?>
<?PHP
// fetch image details
$images = getImages("images");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
You can get the mime type of a file using the PHP function mime_content_type(). This way you can get rid of the shell_execute used to detect the mime type in your code.
I'm trying to improve the administrator panel of my website. I need to preview the images in the thumbnails folder so that when i'm using thumbnails for news I dont have to upload the image for the second time. I found a great script, but I get failed to read the directory error. Here is the script:
<?php
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif", "image/png");
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
// fetch image details
$images = getImages("../images/thumbnails");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
I really appreciate if someone could help..
EDIT:
<div style=" height: 200px; width: 600px; overflow: auto;">
<?PHP
foreach(glob("../thumbnail/".'*') as $filename){
echo "<div style=\"display:inline-table; font-size:10px; font-family:'Tahoma'; margin:5px;\">";
echo "<img width=\"100px\" height=\"100px\" src=\"../thumbnail/$filename\"/>";
echo "<br>".basename($filename) . "<br>";
echo "</div>";
}
?>
</div>
This method works perfect. No need to use complicated scripts.
Anyway, can somebody please tell me how to check images less than 100px x 100px displayed?
<?PHP
foreach(glob("../thumbnail/".'*') as $filename){
list($width, $height, $type, $attr) = getimagesize("../thumbnail/".$filename);
if($width>=100 || $height >=100) continue;
$rest = substr($filename, 3);
?>
That should do it..