I have a website where users upload document files. I want to display thumbnails of these documents. How can I display the first page of a document file as an image using codeigniter?
Below is the controller code:
public function do_upload()
{
require_once APPPATH . "php_include/authenticate.php";
$path = "uploads/file_attachment/";
if($_FILES['userfile']['name'] != ''){
$image = $_FILES['userfile']['name'];
$ext = pathinfo($image, PATHINFO_EXTENSION);
$filename = basename($image,'.'.$ext);
$filename = preg_replace("/[^a-zA-Z0-9]+/", "-", $filename);
$image = $filename.'.'.$ext;
move_uploaded_file($_FILES["userfile"]["tmp_name"],$path.$image);
$data = array(
'user_id' => $user_id,
'file' => $image,
);
$this->signupmodel->addfile($data);
}
}
This may be a bit of overkill for you but I described a bulletproof way to upload images. There are all kinds of ways where the extension (.jpg, .gif) does not match the image. Browsers have to do similar testing before rendering an image.
This code also chooses the most efficient image type to save it as and scales the image to multiple dimensions.
Stackoverflow: Scaling Images
Related
I'm dealing with a few issues regarding multiple images uploads. My project deals with a form the user inputs multiple images that save to a database, but first temporarily stores the images in a directory to show a preview of sorts. In my class, which deals with the uploading of the image I am trying to rename the images as seen below.
I uploaded seven images on the dropdown.
I see that all its images were stored in the database by one.
While it had to be stored under different names.
Controller
public function store(Product $product, Request $request)
{
$path = null;
if ($request->hasFile('file'))
{
$file = $request->file('file');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs($this->path, $fileName, 'public');
}
$gallery = Gallery::create([
'product_id' => $product->id,
'image' => $path,
]);
return response()->json($gallery);
}
$file = $request->file('file');
$name = date('YmdHi');
$extension = $name.$file->getClientOriginalExtension();
In controller , just replace it.
i want to resize uploaded image and store in folder.then show in web.
i used enctype="multipart/form-data" on form in blade.php.
file successfully show in web without resize.
when try to resize image i got error
controller.php
public function dili(Request $request)
{
$di = new diligent;
$di->jobtype = $request->jobtype;
$di->jobC = $request->jobC;
$di->details = $request->details;
$image = $request->file('image');
$path = $image->getClientOriginalName();
$destinationPath = public_path('img');
Image::make($image)->resize(300, 100)->save($image);
$a = $image->move($destinationPath, $path);
$di->image = $path;
$di->save();
$de = diligent::all();
return view('admin')->with('dw', $de);
}
Error Message
Encoding format (tmp) is not supported.
1) use getRealPath() inside Image::make()
2) save image in particular path. try like this.
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300, 100);
$image_resize->save(public_path('img/' .$filename));
}
Make sure you installed Image intervention library.
The Intervention image save() method requires a filename so it knows what file format (jpg, png, etc..) to save your image in.
The reason you are getting the error is it does not know what encoding to save the temporary image object (tmp) in.
Here is an example
->save('my-image.jpg', 90)
There is also a optional second parameter that controls the quality output. The above outputs at 90% quality.
http://image.intervention.io/api/save
I'm making a images gallery website where users can upload any image and they will be displayed on frontend. I need to compress images without effecting it's quality to reduce there size so that page load speed should not effect that much. I'm using following code to upload image:
$rules = array('file' => 'required');
$destinationPath = 'assets/images/pages'
$validator = Validator::make(array('file' => $file), $rules);
if ($validator->passes()) {
$filename = time() . $uploadcount . '.' . $file->getClientOriginalExtension();
$file->move($destinationPath, $filename);
return $filename;
} else {
return '';
}
The best and easiest way to compress images before uploading to the server, I found here:-
https://github.com/spatie/laravel-image-optimizer
You need to optimize the image for web usage as user may upload images that are way to large (Either in size or resolution). You may also want to remove the meta data from the images to decrease the size even more. Intervention Image perfect for resizing/optimizing images for web usage in Laravel. You need to optimize the image before it is saved so that the optimized version is used when loading the web page.
Intervention Image
https://tinypng.com provides an API service for compressing images. All you need to do is install their PHP library in Laravel, get a developer key from their website. After that by the adding the below code, you can compress your uploaded image. In the code, I am assuming you have stored your file under 'storage' directory.
$filepath = public_path('storage/profile_images/'.$filename);
\Tinify\setKey("YOUR_API_KEY");
$source = \Tinify\fromFile($filepath);
$source->toFile($filepath);
Here is the link to a blog which explains how to upload and compress images in Laravel http://artisansweb.net/guide-upload-compress-images-laravel
**Using core php **
function compress($source_image, $compress_image)
{
$image_info = getimagesize($source_image);
if ($image_info['mime'] == 'image/jpeg') {
$source_image = imagecreatefromjpeg($source_image);
imagejpeg($source_image, $compress_image, 20); //for jpeg or gif, it should be 0-100
} elseif ($image_info['mime'] == 'image/png') {
$source_image = imagecreatefrompng($source_image);
imagepng($source_image, $compress_image, 3);
}
return $compress_image;
}
public function store(Request $request)
{
$image_name = $_FILES['image']['name'];
$tmp_name = $_FILES['image']['tmp_name'];
$directory_name = public_path('/upload/image/');
$file_name = $directory_name . $image_name;
move_uploaded_file($tmp_name, $file_name);
$compress_file = "compress_" . $image_name;
$compressed_img = $directory_name . $compress_file;
$compress_image = $this->compress($file_name, $compressed_img);
unlink($file_name);
}
I have a certain code for image upload .I found this on the internet and there was no explanation of the code either.What i can understand from the code is that php upload a certain file makes it a temporary file and then moves the temporary file to the original location
Code Looks something like this
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
What happens now is that when i try to provide an unique name to the image when it is being moved using the move_uploaded_file then a file does come up inside the folder but it says an invalid file and with the extension type of file.
My code for trying to achieve the same but with an unique name/id for the uploaded image.
$uniquesavename=time().uniqid(rand());
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $imagePath . $uniquesavename);
How to achieve the same as before and could you please explain me the previous code as well?
Sample code:
// Get file path from post data by using $_FILES
$filename = $_FILES["img"]["tmp_name"];
// Make sure that it's a valid image which can get width and height
list($width, $height) = getimagesize( $filename );
// Call php function move_uploaded_file to move uploaded file
move_uploaded_file($filename, $imagePath . $_FILES["img"]["name"]);
Please try this one:
// Make sure this imagePath is end with slash
$imagePath = '/root/path/to/image/folder/';
$uniquesavename=time().uniqid(rand());
$destFile = $imagePath . $uniquesavename . '.jpg';
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize( $filename );
move_uploaded_file($filename, $destFile);
Edit 1:
To get image type in two ways:
Get the file type from upload file name.
Use php function as below
CODE
// Get details of image
list($width, $height, $typeCode) = getimagesize($filename);
$imageType = ($typeCode == 1 ? "gif" : ($typeCode == 2 ? "jpeg" : ($typeCode == 3 ? "png" : FALSE)));
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "uploads/";
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
sleep(rand(1,5));
$new_name = $location.time()."-".rand(1000, 9999)."-".$name;
if (move_uploaded_file($tmp_name, $new_name)){
echo "uploaded";
}
else{
echo"failed, better luck next time";
}
}
here, location is folder inside directory, i mainly create folder "uploads"
time() adds timestamp , which is always unique, until two person upload at same time, which is rare.
moreover, adding 4 digit random number to it , making combination rarest
after that adding actual file name , to making combination unique.
why i use it :
u can extract timestamp later if u need to know when image was uploaded.
u can extract actual filename too.
Lets, say our so unique combination somehow fails,
then, php instance will wait for 1 to 5 second whatever random number is generated. and rename with latest timestamp and regenerated random number.
It's the best u can think of without being resource hog.
you can use
$strtotime = strtotime("now");
$filename = $strtotime.'_'.$_FILES['file']['name'];
All the files in a certain directory are scanned using scandir() for example. How then do I go through the files in that directory and create a small image (thumbnail) or whatever so that I can display that next to the name.
I will probably check the files one by one, and lets say it is another directory, the image will be default folder image. For PDF's maybe also. But then for video's and images and anything else like it, the image should be like a preview.
<?php
$data = array();
$files = array();
$allFiles = scandir($_REQUEST['dir_name']);
$files = array_diff($allFiles, array('.', '..'));
foreach($files as $key=>$file){
$data[$key]['name'] = $file;
if(is_dir(_REQUEST['dir_name'].'/'.$file)){
//Get small image of folder here and store that in $data[$key]['preview']
$data[$key]['type'] = 'dir';
}
else{
$extension = substr(strrchr($filename, "."));
$data[$key]['type'] = $extension;
switch ()$extension) {
case 'jpeg' : {
//Get small thumbnail of jpeg image here and store that in $data[$key]['preview'];
}
case 'png' : {
//Get small thumbnail of png image here and store that in $data[$key]['preview'];
}
case 'pdf' : {
//Get small thumbnail of pdf here and store that in $data[$key]['preview'];
}
case 'rar' : {
//Get small thumbnail of default .rar image here and store that in $data[$key]['preview'];
}
}
}
}
echo json_encode($data);
?>
I am prepared to do quite a few extensions, and maybe find a default later on for extensions not explicitly covered. I just need to know some of the different methods on generating a thumbnail from images, videos and documents as I suspect they are completely different.