i am trying to convert ico format file to png format
$media_url ="https://static.licdn.com/scds/common/u/images/logos/favicons/v1/favicon.ico"
$filePath = public_path('media_downloads').'/pnff.png';
file_put_contents($filePath, file_get_contents($media_url));
$s3 = \Storage::disk('s3');
$res = $s3->put($filePath, file_get_contents($img), 'public');
$downloadUrl = \Storage::disk('s3')->url($filePath);
i got s3 url but the file is not opening i think it is corrupted how can i change the image content type while saving to a folder also in s3
i have done ico to png convertion by using Imagick Thanks #aynber #Chris Haas for the guidance
use Imagick;
$file = $media_url;
$extension = pathinfo(parse_url($file, PHP_URL_PATH), PATHINFO_EXTENSION);
$filename = 'linkedin_thumbnail' . time() . '.' . $extension;
$local_file_path = public_path('media_downloads') . '/' . $filename;
$contents = file_get_contents($file);
file_put_contents($local_file_path, $contents);
$image = new Imagick();
$image->readImage($local_file_path);
$image->cropThumbnailImage(100,100);
$image->setImageFormat("png");
header("Content-type: image/png");
$filePath2 = public_path('media_downloads').'/'.date('ymdhis').'.png';
$image->writeImage( $filePath2 );
$media_url = $filePath2;
unlink($local_file_path);
unlink($filePath2);
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";
}
Here is how I get my image:
$coverurl = 'https://api.someurl/api/v1/img/' . $somenumber . '/l';
//$iheaders contains: 'Content-type' => 'image/jpeg'
$iresponse = wp_remote_get($coverurl, $iheaders);
$img = $iresponse['body'];
$testimg = base64_encode($img);
When I echo $testimg with an img-tag, everything works fine.
echo '<img class="attachment-shop_single size-shop_single wp-post-image" src="data:image/jpeg;base64,'.$testimg.'" width="274" />';
Since I need to convert the string into a jpg and save it to my uploads folder, I tried to use imagecreatefromstring().
$imgx = imagecreatefromstring($testimg);
if ($imgx !== false) {
header('Content-Type: image/jpeg');
imagejpeg($imgx);
imagedestroy($imgx);
} else {
echo 'An error occurred.';
}
But I never get to the point of saving anything, because of the following warning:
Warning: imagecreatefromstring(): Data is not in a recognized format in /etc.
When I echo $testimg I get:
/9j/4AAQSkZJRgABAQAAAQABAAD ...Many number and characters.. Ggm2JUsEvfqnxAhGFDP/9k=
What must I do to make createimagefromstring work? Do I have to modify the $testimg string? Thanks for your interest.
The method imagecreatefromstring does not take a base_64 encoded string. Try this instead:
$imgx = imagecreatefromstring($img); // Contents of $iresponse['body']
You can see this in the topmost comment in the documentation page (linked above):
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
After looking at the codex https://codex.wordpress.org/Function_Reference/wp_insert_attachment, I found the solution:
//get the image from internet
$coverurl = 'https://api.someurl/api/v1/img/' . $somenumber . '/l';
$iresponse = wp_remote_get($coverurl, $iheaders);
$img = $iresponse['body'];
$directory = "/".date('Y')."/".date('m')."/";
$wp_upload_dir = wp_upload_dir();
//encode $img as with html image tag
$imgdata = base64_encode($img);
$filename = "gtb_". $isbnraw.".jpg";
$fileurl = "../wp-content/uploads".$directory.$filename;
$filetype = wp_check_filetype( basename($fileurl), null);
file_put_contents($fileurl, $img);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $fileurl ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($fileurl)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $fileurl, $post_id);
require_once('../wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $fileurl);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($post_id, $attach_id);
//add media_category
wp_set_object_terms($attach_id, $mediacat, 'media_category');
This converts a base64 into a jpg and imports it into Wordpress plus attaches it to the post/product. It seems to work well. Thanks for your interest.
I want to change image name with current time stamp in php.
My code are below :
$logo = basename($_FILES['file']['name']);
$logo = image1.jpg
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $_FILES['file']['name']);
i get image name in $logo. But Actually i want
$logo = 1484900616.jpg
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $_FILES['file']['name']);
file name may be dynamic. its may be jpg , png, jpeg. Also want to move file with new name.
Use move_uploaded_file function.
Example:
$file_path = "uploads/";
$newfile = date('m-d-Y_H:i:s')'.jpg';
$filename = $file_path.$newfile;
if(!file_exists($filename))
{
if(move_uploaded_file($_FILES['file']['tmp_name'],$filename))
{
// Other codes
}
}
else
{
echo 'file already exists';
}
Try this.
$path = $_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$logo = time().'.'.$ext;
And to use the new name. put this.
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $logo);
I would like all images dropped in a directory to be copied into a separate directory as thumbnails that i can then view on my site. Right now i'm researching phpthumb, but have also downloaded wideimage and zen photo.
Thanks if you can find an exact duplicate to this, near matches may also be helpful.
Here is the script that only copies a single files:
require_once '../ThumbLib.inc.php';
//include the thumb library
$thumb = PhpThumbFactory::create('test.jpg');
//create a new image from the targeted jpegs
$thumb->adaptiveResize(100, 100);
//resize
$thumb->save('test.png', 'png');
//save as 'test' with the file type png
//echo "<img src='$thumb' class='thumb'>";
$thumb->show();
//print the thumbnail to the screen
Try
$dir = "photos" ;
$destination = "thumb" ;
$images = scandir($dir);
foreach ( $images as $image ) {
if(is_file($image))
{
$ext = pathinfo ( $dir . DIRECTORY_SEPARATOR . $image, PATHINFO_EXTENSION );
$thumb = PhpThumbFactory::create ( $dir . DIRECTORY_SEPARATOR . $image );
$thumb->adaptiveResize ( 100, 100 );
$thumb->save ( $destination . DIRECTORY_SEPARATOR . $image, $ext );
$thumb->show ();
}
}