Laravel - How can i show images with specified name from public folder? - php

I want to display all images with specified id.
Ex: i just wanna display all images with same id before underscore.
how i do that?
I have this,
Route::get('images/{filename}', function ($filename)
{
$path = public_path('uploads') . '/' . $filename;
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
But i want to change, instead of filename i want an id, and i wanna show all images start with that id
Note:Sorry, new here!
image from folder

Php has a function named "glob" that can handle that.
$files = glob("uploads/".$id."_"."*.{jpg,png,gif,bmp}", GLOB_BRACE);
foreach ($files as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}

Related

file_put_contents() or similar to create new photo

I receive a string of base64 and am able to decode it and put it into a file. The problem is, I would like to create a new image file each time to put this base64 into.
Currently I have a basic code which is able to put contents into the file that is pre-existing but the current code does not create a non-existent file.
$data = base64_decode($data);
$path = 'abc';
var_dump(is_dir($path));
if ( ! is_dir($path)) {
if(mkdir($path, 0777)) {
echo "created dir";
}
}
file_put_contents('tmp.png', $data);
Base64 function to decode
function base64ToFile($base64String, $outputFile) {
$file = fopen($outputFile, "wb");
$data = explode(',', $base64String);
fwrite($file, base64_decode($data[1]));
fclose($file);
return $outputFile;
}
Check this the function will return you the unique name after uploading your image in a directory
$imageBase64=$_POST['image_converted_base64'];//get base64 of image from client end
$unique_name =uploadSingleImage($imageBase64);//function call
//function to upload image and get an unique name to store in db
function uploadSingleImage($base64) {
$uniname = uniqid() . date("Y-m-d-H-i-s") . ".png";
$new_image_url = "../../image/" . $uniname;
$base64 = 'data:image/jpeg;base64,' . $base64;
$base64 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64));
file_put_contents($new_image_url, $base64);
return $uniname;
}

how to update and remove (unlink) multiple old images in json format

this is still related to my post in here How to remove and unlink multiple images in json format
i can store and delete all multiple images. but i have still problem when update and remove old image. my code still not remove the oldimage when update the new image.
my update controller, i use handlerequest method to store images, where oldImage is variable in database that will be compared with new images. if not same then remove old images.
public function update(Requests\UpdatePostRequest $request, $id)
{
$post = Post::findOrFail($id);
$oldImage = $post->image;
$data = $this->handleRequest($request);
$post->update($data);
if($oldImage != $post->image)
{
foreach (json_decode($post->image, true) as $oldImage) {
$this->removeImage($oldImage);
}
}
if($request->submitbutton =='Publish')
{
Alert::success('Your post was updated successfully')->persistent('Close');
return redirect(route('admins-blogpost.index'));
}
if($request->submitbutton =='Save Draft')
{
Alert::success('Your draft was updated successfully')->persistent('Close');
return redirect(route('admins-blogpost.index'));
}
}
my handlerequest method to store multiple image, this method is working using store method. so this problem not here.
private function handleRequest($request)
{
$data = $request->all();
if($request->hasFile('image'))
{
$images = $request->file('image');
foreach($images as $key=>$image){
$fileName = $image->getClientOriginalName();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
if($successUploaded)
{
$width = config('cms_blog.image.thumbnail.width');
$height = config('cms_blog.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make($destination . '/' . $fileName)
->resize($width,$height)
->save($destination . '/' . $thumbnail);
$datax[] = $fileName;
}
$data['image'] = json_encode($datax);
}
}
return $data;
}
and delete method
public function removeImage($image)
{
if( ! empty($image))
{
$imagePath = $this->uploadPath . '/' . $image;
$ext = substr(strrchr($image, '.'), 1);
$thumbnail = str_replace(".{$ext}", "_thumb.{$ext}", $image);
$thumbnailPath = $this->uploadPath . '/' . $thumbnail;
if(file_exists($imagePath) ) unlink($imagePath);
if(file_exists($thumbnailPath) ) unlink($thumbnailPath);
}
}
how to fix my problem so i can remove old images when their not same with new image?
In the for loop where you delete the images, I believe you wanted to iterate over $oldImage, not over $post->image:
foreach (json_decode($oldImage, true) as $item) {
$this->removeImage($item);
}
Storing multiple images name on a single column, which is not a good idea. I suggested you create another table post_images or something else.
And create hasMany relation from posts table with post_images table. Then you have lot's of flexibility here. Also, you can create a Polymorphic Relationship to use the same image model with multiple Models.

How to check Image name in folder and rename it?

I have a csv file with image name and Prefix for image and I want to add prefix in that image name and rename it and move it to another directory.
<?php
$fullpath = '/var/www/html/john/Source/01-00228.jpg';
$additional = '3D_Perception_';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/' . $additional
. $info['filename']
. '.' . $info['extension'];
echo $fullpath ;
}
?>
Here Image file is store in Source Directory I want to rename it with some prefix and move it other directory like Destination
Please help me out to find solution for this.
<?php
$source_directory = '/var/www/html/john/Source/';
$dest_directory = '/var/www/html/john/Source/'; // Assuming you'll change it
$filename = '01-00228.jpg';
$prefix = '3D_Perception_';
$file = $source_directory . $filename;
$dest_file = $dest_directory . $prefix . $filename;
if (file_exists($file)) {
if (copy($file, $dest_file)) {
unlink($file); // Deleting source file.
var_dump(pathinfo($dest_file)); // Dump dest file infos, replace it with wathever you want to do.
} else {
// if copy doesn't work, do something.
}
}
?>
Try this, and take care about my comments. ;)

PHP renaming/chaning featured picture

I'm trying to make a PHP script that changes the featured picture of some item.
The general principle is that it when $_POST['featured'] is set, it renames that picture to featured.jpg and renames all other pictures to their hash_file value. However, it works well the first time when there is no featured picture set, but when I try to change it from one featured picture to another, the previous featured picture gets removed and the new one doesn't get renamed to featured.jpg. All pictures are in the same folder.
Here is the relevant code:
if (isset($_POST['featured'])) {
$id = $_POST['id'];
$slike = glob('../img/uploads/'.$id.'/*.{jpg,png}', GLOB_BRACE);
if ($slike != null) {
foreach ($slike as $slika) {
$path = realpath($slika);
$name = basename($path);
if($name == basename($_POST['featured'])){
if(!file_exists(dirname($path) . '/featured.jpg')){
rename($path, dirname($path) . '/featured.jpg');
}else{
rename(dirname($path) . '/featured.jpg', dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
rename($path, dirname($path) . '/featured.jpg');
}
}else{
rename ($path, dirname($path) . '/' . hash_file('md5', $path) . '.jpg');
}
}
}
}

Adding an image to a JSON WebService -PHP

Is there any way that I can send images via my JSON Webservice?
Here is my code which looks for new images in a specific folder and return some data including (path, id which is the name of image file and the creation time of the file):
function getAllNewPhotos($lastCHK) {
$dirPath = 'c:\my_images';
$files1 = scandir($dirPath);
$files = array_diff($files1, array('.', '..'));
$newFiles = array();
foreach ($files as $file) {
$createTime = filectime($dirPath . '/' . $file);
$path_data = pathinfo($dirPath . '/' . $file);
if ($createTime > $lastCHK) {
$newFiles[] = array(
'path' => $dirPath . '\\' . $file,
'ID' => $path_data['filename'],
'dateImagAdded' => date('Y-m-d H:i:s', $createTime),
);
}
}
return ($newFiles);
}
Is there any way to send the real image along with the other data which I have already passed?
If you need more clarification, please let me know which part you need more clarification.
Thanks
You can use base64 to encode your image
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

Categories