Generate thumbnail from video using ffmpeg and add to mysql database - php

Im a noobie in php but still im trying :) Im making bulk video uploader/importer to database. Looking ideas how to extract thumbnails from videos on upload and add those thumbnails to mysql database for each video... :/ Im trying using ffmpeg, but i dont found the way how to implement it to my code...
<?php
// Database
include 'config/database.php';
if(isset($_POST['submit'])){
$url = "localhost/";
$uploadsDir = "uploads/";
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $title=>$val){
// Get files upload path
$fileName = $_FILES['fileUpload']['name'][$title];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$title];
$targetFilePath = $uploadsDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
if(in_array($fileType, $allowedExts)){
if(move_uploaded_file($tempLocation, $targetFilePath)){
$sqlVal = $withOutExtension;
$sqlVal2 = $url . $uploadsDir . $fileName;
$sqlVal3 = null;
$randomID = rand(1000, 999999);
$sqlVal4 = ('<p><video controls="" src="/' . $sqlVal2 . '" width="640" height="360" class="note-video-clip"></video><br></p>');
$slug = str_replace(' ', '-', $withOutExtension);;
$file = $uploadsDir . $fileName;
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024 / 1024, 1);
} else {
$response = array(
"status" => "alert-danger",
"message" => "File coud not be uploaded."
);
}
} else {
$response = array(
"status" => "alert-danger",
"message" => "I want mp4 file."
);
}
// Add into MySQL database
if(!empty($sqlVal)) {
$insert = $conn->query("INSERT INTO applications (id, title, description, custom_description, details, image, slug, file_size, license, developer, url, buy_url, type, votes, screenshots, total_votes, counter, hits, category, platform, must_have, featured, pinned, editors_choice, created_at, updated_at) VALUES ('$randomID', '$sqlVal', 'Video .mp4 Live Wallpaper. Animated wallpaper is a cross between a screensaver and desktop wallpaper. Like a normal wallpaper, an animated wallpaper serves as the background on your desktop, which is visible to you only when your workspace is empty, i.e. no program windows block it from view.', '$sqlVal3', '$sqlVal4', '99999.jpg', '$slug', '$filesize MB', 'free', 'n/a', '$sqlVal2', '$sqlVal3', '1', '0.00', '', '0', '0', '1', '22', '6', '1', '1', '0', '1', '2021-11-11 16:55:36', '2021-11-11 16:55:36')");
if($insert) {
$response = array(
"status" => "alert-success",
"message" => "Files successfully uploaded."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Files coudn't be uploaded due to database error."
);
}
}
}
} else {
// Error
$response = array(
"status" => "alert-danger",
"message" => "Please select a file to upload."
);
}
}
?>

Concerning the FFMpeg part, I think a good way to start is to actually use the PHP-FFMpeg library. The Basic Usage section in the documentation contains an example on how to generate a frame for a given video:
require 'vendor/autoload.php';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
->save('frame.jpg');
A simplified process would be as follows:
The user uploads a video, after which the video gets moved to a different
directory.
Now you can use the snippet above, with the frame method to get a thumbnail for your video.
After the image saving is done, you just need to add it to your database.
If the thumbnails refer to the image column in your table, you can get away with just inserting the filename, frame.jpg (or even the complete filepath, /public/path/to/frame.jpg).
If the thumbnails refer to the screenshots column in your table, and you want to have multiple thumbnails for your video, then you should consider creating a new table with a one-to-many relationship (from your video/application to a new table, e.g. thumbnails)
Then when the user gets to a page where the image should be displayed, just select it from the table and display it with an <img> tag (with the public filepath).
I would also strongly recommend not to save the complete <video> tag into your database, but instead add it to the page where you actually want to show your video.
Example:
<?php
$result = $conn->query('SELECT ...');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<video src="<?php echo $row['video-column-path']; ?>"</video>
<?php
}
} else {
?>
No videos here
<?php
}
$conn->close();
?>

Found solution, now need to understand how to import generated thumbnail url to database field for video...
// Velidate if files exist
if (!empty(array_filter($_FILES['fileUpload']['name']))) {
// Loop through file items
foreach($_FILES['fileUpload']['name'] as $title=>$val){
// Get files upload path
$fileName = $_FILES['fileUpload']['name'][$title];
$tempLocation = $_FILES['fileUpload']['tmp_name'][$title];
$targetFilePath = $uploadsDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
$uploadDate = date('Y-m-d H:i:s');
$uploadOk = 1;
$randomID = rand(1000, 999999);
//Get one thumbnail from the video
$ffmpeg = "C:\\ffmpeg\\bin\\ffmpeg";
//echo $ffmpeg;
$imageFile = 'pic/thumb_'.time().'_'.$randomID.'.jpg';
$size = "120x90";
$getFromSecond = 1;
echo $cmd = "$ffmpeg -i $tempLocation -an -ss $getFromSecond -s $size $imageFile";
echo "<br>";
if(!shell_exec($cmd)){
echo "Thumbnail Created!";
}else{
echo "Error creating Thumbnail";
}

Related

Generate thumbnail image from video in codeigniter

i want to generate the thumbnail image from the uploaded video but the problem is that the thumbnail image is not generating. The uploaded video goes to the uploads folder but at this place the image is not generating..Please look at the code, and tell me where i am wrong.
public function add_video() { // move_upload_file code
if(!empty($_FILES['video']['name'])){
$tmp_name_array = $_FILES['video']['tmp_name'];
$n_array = $_FILES['video']['name'];
$exp = explode('.', $n_array);
$newnme = date('his').rand().'.'.end($exp);
$raw_name = explode('.', $newnme);
$full_path = base_url('uploads').'/'.$newnme;
$new_path = base_url('uploads').'/';
if(move_uploaded_file($tmp_name_array, "uploads/".$newnme))
{
$full_path = base_url('uploads').'/'.$newnme;
$new_path = base_url('uploads').'/';
print_r(exec("ffmpeg -i ".$full_path." ".$new_path.$raw_name[0].".jpg"));
echo "uploaded Successfully";
}
}else{
echo "not selected any file";
}
}

How to save converted JPG image from PDF using Imagemagick to database

loading pdf file from php form
$name = $_FILES['file']['name'];
$fileName = substr($_FILES['file']['tmp_name'], 5).".".$ext;
date_default_timezone_set('UTC');
$fileDate = date('d.m.Y');
$fileSize = $_FILES['file']['size'];
$folder = $_POST['folder'];
$target_dir="$media_dir/";
$target_file= $target_dir . basename($_FILES["file"]["name"]);
Move file from tmp to media path
move_uploaded_file($_FILES['file']['tmp_name'], $target_file);
converting pdf to jpg using Imagick
$imagick = new imagick();
$imagick->readImage($target_file);
$imagick->setImageFormat('jpg');
$image= basename($target_file,".pdf");
foreach($imagick as $i=>$imagick)
{
$imagick->writeImage($target_dir . $image . ($i+1) ." of ". $pages.".jpg");
} $imagick->clear();
How can I save the converted image to a database. Currently, it is just uploading the original pdf image to the database.
$id_object = _addMediaFile($name, $fileName, 2, $fileSize, $folder);
$ret = array("ID" => $id_object, "name" => $name, "fileName" => $fileName, "fileSize" => $fileSize, "fileDate" => $fileDate, "fileType" => 4, "folder" => $folder);
echo json_encode($ret);
}
Consider converting the image directly into a blob that you directly save into a database column of blob type. For instance, with $a = $image->getImageBlob(); you would save $a into the database. Reference: http://php.net/manual/en/imagick.getimageblob.php

Files with specific extensions are not getting attached

I'm creating a form where I've a place for attaching files. But, files with specific extensions like .xls, .sql etc., are not getting attached. But, other files like .docx, .pdf etc., are getting attached. This is how I tried:
function file_upload($control_id, $target_directory) {
if(isset_file($control_id)) {
if(file_exists($target_directory) == false) {
mkdir($target_directory, 0777, true); //to be create the directory recursively
}
$file_name = basename($_FILES[$control_id]["name"]); //to be get file name
write_log($file_name);
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION); //to be get file extension
write_log($file_extension);
$file_size = $_FILES[$control_id]["size"]; //to be get file size in bytes
write_log($file_size);
$target_file_name = round(microtime(true) * 1000).".".$file_extension; //to be get target file name
$target_file_path = $target_directory.$target_file_name; //to be get target file
if(file_exists($target_file_path) == true) {
chmod($target_file_path, 0755); //Change the file permissions if allowed
unlink($target_file_path); //remove the file
}
if (move_uploaded_file($_FILES[$control_id]["tmp_name"], $target_file_path) == true) {
$arr = array(
"status" => true,
"message" => "The file ".$file_name." has been uploaded.",
"file_name" => $file_name,
"file_extension" => $file_extension,
"file_size" => $file_size,
"uploaded_file_name" => $target_file_name,
"uploaded_file_path" => $target_file_path
);
} else {
$arr = array(
"status" => false,
"message" => "Sorry, there was an error uploading your file."
);
}
} else {
$arr = array(
"status" => false,
"message" => "Please select file"
);
}
//echo json_encode($arr);
return $arr;
}
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["id"]));
$upload_directory = "uploads/attachments/";
$result = file_upload("contract_attachment", "../".$upload_directory);
if($result[status] == true) {
$query = "insert into `attachments`
(
`id`,
`file_name`,
`file_extension`,
`file_size`,
`uploaded_file_name`,
`uploaded_file_path`
)
values
(
'id',
'".addslashes($result['file_name'])."',
'".$result[file_extension]."',
'".$result[file_size]."',
'".$result[uploaded_file_name]."',
'".$upload_directory.$result[uploaded_file_name]."'
)";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
}
echo json_encode(array("message" => "Record submitted successfully"));
exit;
The problem is, when ever I try to attach a file with extension .xls or .sql, the $file_name, $file_extension, $file_size will get a value. For example, if the file I'm attaching is format.xls, it showed $file_name = format, $file_extension = .xls and $file_size = 0. Since the file size it's taking is zero, the condition "$result[status]" fails. So, the file is not getting attached.
If I attach files like .pdf or .docx I get the correct values. For example, if I attach file like format.pdf, it showed $file_name = format, $file_extension = .pdf, $file_size = 9824. And the file is also getting attached.
But, I don't know what's wrong with this code, since files with extensions .xls and .sql are not getting attached. Can someone correct this and tell whats wrong with this?

PHP Mysql - Image not displaying on browser (broken image)

I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';

Cannot display blob image from database using PHP

I am not able to get my broswer to display an image from the database(stored as blob). I have tried
header("Content-type: image/jpeg");
echo '';
But it is still not able to display on the browser.
getImage.php
<?php
require_once 'php-activerecord/ActiveRecord.php';
ActiveRecord\Config::initialize(function($cfg) {
$cfg->set_model_directory('models');
$cfg->set_connections(array(
'development' => 'mysql://root:mysql#localhost/BondingTogether'));
});
$id = addslashes($_REQUEST['id']);
$row = food::find_by_foodid($id);
$image = $row->image;
//$image = ""
//header("Content-Type: image/jpg");
header("Content-type: image/jpeg");
//echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
echo $image;
//echo base64_decode($image);
Adding to the database
<?php
require_once 'php-activerecord/ActiveRecord.php';
ActiveRecord\Config::initialize(function($cfg) {
$cfg->set_model_directory('models');
$cfg->set_connections(array(
'development' => 'mysql://root:mysql#localhost/BondingTogether'));
});
//files
$file = $_FILES['foodimage']['tmp_name'];
if (!isset($file)) {
}
else {
//$image = addslashes(file_get_contents($_FILES['foodimage']['tmp_name']));
$image_name = addslashes($_FILES['foodimage']['tmp_name']);
$image_size = getimagesize($_FILES['foodimage']['tmp_name']);
if ($image_size == FALSE) {
die('Please select an image file');
} else {
}
}
$image = addslashes(file_get_contents($_FILES['foodimage']['tmp_name']));
//$image = chunk_split(base64_encode(file_get_contents("image.jpg")));
Food::create(array(
'xcoord' => $_POST['XCoord']
, 'ycoord' => $_POST['YCoord']
, 'title' => $_POST['title']
, 'category' => $_POST['cat']
, 'description' => $_POST['desc']
, 'image' => $image
));
You should not be using addslashes() when storing image data in your DB. A better alternative is to insert the image data with base64_encode(), and base64_decode() it when you output it. A simple search will find plenty of good answers to this and similar questions

Categories