I wrote a tiny script to create previews of all JPG images in a directory and save them into another directory. But the file extension .jpg is always missing. I really do not understand why.
foreach( glob(dirname(__FILE__)."/../../img/plakate/full/*.jpg") as $img ){
// key
$key = basename($img,'.jpg').PHP_EOL;
// save preview
$thumb = new Imagick($img);
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(10);
$thumb->resizeImage(50,0,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage("lib/img/plakate/preview/{$key}.jpg");
$thumb->destroy();
}
I also tried this which results in the same:
foreach( glob(dirname(__FILE__)."/../../img/plakate/full/*.jpg") as $img ){
// key
$key = basename($img,'.jpg').PHP_EOL;
// save preview
$thumb = new Imagick($img);
$thumb->setImageCompression(Imagick::COMPRESSION_JPEG);
$thumb->setImageCompressionQuality(10);
$thumb->resizeImage(50,0,Imagick::FILTER_LANCZOS,1);
$thumb->setImageFormat('jpeg');
file_put_contents ("lib/img/plakate/preview/{$key}.jpg", $thumb);
$thumb->destroy();
}
As I see everything works fine – only the file extension is missing. :(
Your code $key = basename($img,'.jpg').PHP_EOL; has a PHP_EOL at the end, saying that the line ends here, "discarding" anything after it when assembling your filename.
Change $key = basename($img,'.jpg').PHP_EOL; to $key = basename($img,'.jpg'); to have your file extension appended.
you can simply use it instead of basename,
$explodedPath = explode(DIRECTORY_SEPARATOR, $img);
$fileName = $explodedPath[count($explodedPath) - 1];
or pathinfo
$pathParts = pathinfo($img);
$fileName = "{$pathParts['filename]}{$pathParts['extension']}"
Related
I had base64 encoded data.
Look my code, please.
First of all, see my code.
$data = "data:image/png;base64,iVBORw0KGgoAAAA..........";
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = uniqid().time().".png";
I want to set an extension .png to complete my file so that I can count this file extension by laravel method $image->getClientOriginalExtension() and others laravel file methods.
sorry for miss spell of language.
Hope I make you understand.
This works, although I cannot say if it's the best way to go about it. It's a full working example with a 1x1 black pixel png image. This assumes you already removed the data:image/png;base64, portion from the image data.
$data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR
42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=');
// Create a temp file and write the decoded image.
$temp = tmpfile();
fwrite($temp, $data);
// Get the path of the temp file.
$tempPath = stream_get_meta_data($temp)['uri'];
// Initialize the UploadedFile.
$imageName = uniqid().time().".png";
$file = new \Illuminate\Http\UploadedFile($tempPath, $imageName, null, null, true);
// Test if the UploadedFile works normally.
echo $file->getClientOriginalExtension(); // Shows 'png'
$file->storeAs('images', 'test.png'); // Creates image in '\storage\app\images'.
// Delete the temp file.
fclose($temp);
I'm having a script that checks remote server for a file, and if it is already available locally it should use that one. If it isn't available locally, then download the image to the server. However, I'm struggling with the script overwriting images that I already have locally. If it's already available locally, the script shouldn't do anything with the file - just display it.
In some cases, the script tries to download a image that I already have - and the filesize for the file it overwrites becomes 0kb even though the file worked perfectly earlier.
What am I doing wrong here?
<?php
$url = "http://www.myserver.com/image123.jpg";
$filename = basename($url);
if(!file_exists(images/$filename))
{
// File doesn't exsist, download it!
$image = file_get_contents("$url");
file_put_contents("images/$filename", $image);
$image = "images/$filename";
} else {
// We already got this file, display it!
$image = "images/$filename";
}
echo $image;
?>
<?php
$url = "http://www.myserver.com/image123.jpg";
$filename = basename($url);
$path = "images/$filename";
if( !file_exists($path) ) {
$image = file_get_contents($url);
file_put_contents($path, $image);
}
echo $path;
?>
The file name is known but the file extension is unknown. The images in thier folders do have an extension but in the database their names do not.
Example:
$ImagePath = "../images/2015/03/06/"; (Folders are based on date)
$ImageName = "lake-sunset_3";
Does not work - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath))->getExtension();
echo $Ext;
Does not work either - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath.$ImageName))->getExtension();
echo $Ext;
Does not work either - $Ext is still empty:
$Ext = (new SplFileInfo($ImagePath,$ImageName))->getExtension();
echo $Ext;
$Ext should produce ".jpg" or ".jpeg" or ".png" etc.
So my question is simple: What am I doing wrong?
Now, this is a bit of an ugly solution but it should work. Make sure that all your files have unique names else you'll have several of the same file, which could lead to your program obtaining the wrong one.
<?php
$dir = scandir($imagePath);
$length = strlen($ImageName);
$true_filename = '';
foreach ($dir as $k => $filename) {
$path = pathinfo($filename);
if ($ImageName === $path['filename']) {
break;
}
}
$Ext = $path['extension'];
?>
Maybe this might help you (another brute and ugly solution)-
$dir = '/path/to/your/dir';
$found = array();
$filename = 'your_desired_file';
$files = scandir($dir);
if( !empty( $files ) ){
foreach( $files as $file ){
if( $file == '.' || $file == '..' || $file == '' ){
continue;
}
$info = pathinfo( $file );
if( $info['filename'] == $filename ){
$found = $info;
break;
}
}
}
// if file name is matched, $found variable will contain the path, basename, filename and the extension of the file you are looking for
EDIT
If you just want the uri of your image then you need to take care of 2 things. First directory path and directory uri are not the same thing. If you need to work with file then you must use directory path. And to serve static files such as images then you must use directory uri. That means if you need to check files exists or what then you must use /absolute/path/to/your/image and in case of image [site_uri]/path/to/your/image/filename. See the differences? The $found variable form the example above is an array-
$found = array(
'dirname' => 'path/to/your/file',
'basename' => 'yourfilename.extension',
'filename' => 'yourfilename',
'extension' => 'fileextension'
);
// to retrieve the uri from the path.. if you use a CMS then you don't need to worry about that, just get the uri of that directory.
function path2url( $file, $Protocol='http://' ) {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
$image_url = path2url( $found['dirname'] . $found['basename'] ); // you should get the correct image url at this moment.
You are calling a file named lake-sunset_3. It has no extension.
SplFileInfo::getExtension() is not designed to do what you are requesting it to do.
From the php site:
Returns a string containing the file extension, or an empty string if the file has no extension.
http://php.net/manual/en/splfileinfo.getextension.php
Instead you can do something like this:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
getExtension() only returns the extension from the given path, which in your case of course doesn't have one.
In general, this is not possible. What if there is a file lake-sunset_3.jpg and a file lake-sunset_3.png?
The only thing you can do is scan the directory and look for a file with that name but any extension.
You're trying to call an incomplete path. You could try Digit's hack of looking through the directory for for a file that matches the name, or you could try looking for the file by adding the extensions to it, ie:
$basePath = $ImagePath . $ImageName;
if(file_exists($basePath . '.jpg'))
$Ext = '.jpg';
else if(file_exists($basePath . '.gif'))
$Ext = '.gif';
else if(file_exists($basePath . 'png'))
$Ext = '.png';
else
$Ext = false;
Ugly hacks aside, the question begging to be asked is why are you storing them without the extensions? It would be easier to strip off the extension if you need to than it is try and find the file without the extension
I am creating a variable from an XML file ($image) and I need to create a new variable that combines $image with '.jpg'. I've tried:
$image = $record->getElementsByTagName( "name_id" );
echo $image.".jpg";
$image = $image->item(0)->nodeValue;
But this doesn't add .jpg to the variable in the script. The reason I need to do this is the XML file doesn't have the jpg file extension only the image reference as a sequence of numbers. Any ideas?
If $image is a string, just concoct the strings together with ..
You can see this as an example:
<?php
$img = hello;
$imgfinal = $img . ".jpg";
echo $img;
?>
As expected the output is hello.jpg. Hope this helped.
Are you looking for:
$image = $record->getElementsByTagName( "name_id" );
$image = $image->item(0)->nodeValue;
$image = $image . ".jpg";
Now $image should contain the filename with the file extension
I am using this script to display random images from a folder. I have hundreds of images with significant filenames, So I’m looking for a way to display each image file name as an image caption. Is this possible?
this is the script Im using:
<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:
http://photomatt.net/scripts/randomimage
*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';
// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along
header('Location: '.$folder.$files[$rand]); // Voila!
?>
If all you want to do is continue to display a single random image then remove (or comment out so you can restore it if you later want to) the header line and at the end of the file add the following lines underneath it:
//header('Location: '.$folder.$files[$rand]); // Voila!
echo $files[$rand];
?>
<br />
<img src="<?php echo $folder.$files[$rand] ?>" />
You might want to add some css styling to set the display size of the image, and to format the caption above it.