I'm trying to send an image taken from the camera and converted to base 64 format to be converted into a JSON format. Everything is working fine except when I use the function of json.dump in python it adds \n to the image_64 base format, where in the server, it can't decode the picture properly- It's giving a blank image .
Python code to send the image :
import socket
import datetime
import json
import base64 , urllib
from cam import *
Signal = "200"
Date = datetime.datetime.now()
captureImage()
del(camera)
facechop('test_image.png')
image ='test_image.png'
image_64 = base64.encodestring(open(image,"rb").read())
print "----------------------------------------------"
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('X.X.X.X', 20001))
code = json.dumps({"number": Signal, "date" : "{:%m/%d/%Y}".format(Date), "image" : image_64}).encode('utf8')
client_socket.sendall(code)
receive = client_socket.recv(5012)
print receive
except Exception as e:
print("ERROR: "+str(e))
& the server code is :
function checkMessageRecieved(){
foreach ($this->changed as $key => $socket) {
$buffer = null;
while(socket_recv($socket, $buffer, 10240000, 0) >= 1) {
$n = trim($buffer);
$decodeJSON = json_decode($n, true);
$number = $decodeJSON['number'];
$date = $decodeJSON['date'];
$image = $decodeJSON['image'];
echo $number;
echo $date;
echo $image;
$image=str_replace("\n", "" , $image);
$img = str_replace('data:image/png;base64,', '', $image);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = __DIR__ . "/../photos/public/" . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
$this->sendMessage(trim("Successfully done...") . PHP_EOL);
unset($this->changed[$key]);
break;
}
}
}
Related
I'm trying to check download images and store locally in my assets folder.
Before start downloading, I want to check and make sure the link is still live.
I only want to start my download if the link is live 200 Ok.
Try #1
public function handle()
{
$skills = Skill::all();
if($skills != null){
foreach($skills as $i=>$skill){
if (strpos($skill->img_path, 'http') !== false) {
if(!isset($exception)) {
//update the path in DB
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$uploadSuccess = file_put_contents($path, file_get_contents($skill->img_path));
// dd($uploadSuccess);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
}
}
}
$skill->save();
}
}
}
I seems to get so many issues
One of them is
curl: (6) Could not resolve host: thumbsplus.tutsplus.com
Another one is
file_get_contents(https://assets-cdn.github.com/images/modules/logos_page/Octocat.png): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
What is the cleaner way ? Please suggest, I will try now.
Try #2
public function handle()
{
$skills = Skill::all();
if($skills != null){
foreach($skills as $i=>$skill){
if (strpos($skill->img_path, 'http') !== false) {
$file_headers = #get_headers($skill->img_path);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
if(!isset($exception)) {
//update the path in DB
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$uploadSuccess = file_put_contents($path, file_get_contents($skill->img_path));
// dd($uploadSuccess);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
}
}
}
}
$skill->save();
}
}
}
Try #3
public function handle()
{
$skills = Skill::all();
$failCount = 0;
$successCount = 0;
$failList = [];
if($skills != null){
foreach($skills as $i=>$skill){
if (strpos($skill->img_path, 'http') !== false) {
$file_headers = #get_headers($skill->img_path);
if(!$file_headers || strpos($file_headers[0], '404') !== false) {
$exists = false;
$failCount++;
array_push($failList,$skill->name);
// break;
}
else {
$exists = true;
$successCount++;
//DEBUG
// dd($file_headers[0]);
if(strpos($file_headers[0], '200')) {
//update the path in DB
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$uploadSuccess = file_put_contents($path, file_get_contents($skill->img_path));
// dd($uploadSuccess);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
}
}
}
}
$skill->save();
echo ".";
}
}
echo "\r\n";
$this->info('=========================');
$this->info('Success :'. $successCount);
$this->info('=========================');
$this->info('Fail :'. $failCount);
$this->info('List :'. print_r($failList));
$this->info('=========================');
}
seems to work
but it hang, sometimes more than 1 minute, at a certain dot
⚡️ php artisan skillIcons:download
..............................................................................................................................
=========================
Success :12
=========================
Fail :7
Array
(
[0] => GitHub
[1] => Geolocation API
[2] => Xcode
[3] => Protractor
[4] => Sketch
[5] => Amazon ECR
[6] => WinSCP
)
List :1
=========================
All images seems to be downloaded successfully
⚡️ ls public/assets/fe/img/skill/
AWS Console.png Digital Ocean.png Javascript.png PayPal.png Terminal.png
AWS.png Disqus.png Jest.png Photoshop.png TextMate.png
Alimofire.png Divvy.png Jira.png Pod.png TextWrangler.png
Amazon ECS.png Docker.png Kamar.png PostgreSQL.png Transmit.png
Amazon RDS.png Duet.png LESS.png PyCharm.png Twitter.png
Angular.png EC2.png Laravel Elixir.png Python.png Ubuntu.png
AngularJS.png Evernote .png Laravel.png QuickBooks.png VMWare Fusion .png
Apache.png Express.png Linode.png React Native.png VS Code.png
Atom.png Facebook.png Mac OS X.png Realm.png Vagrant.png
Bash.png Final Cut.png Markdown.png Redis.png Virtual Machine.png
BitBucket.png FusionCharts.png MobaXTerm.png RequireJS.png Virtualbox.png
Bower.png GitLab.png Mocha.png S3.png Webpack.png
CKEditor.png Go Daddy.png MySQL.png SAML 2.0.png Windows.png
CSS.png Google Chart.png NPM.png Salesforce.png Wireshark.png
Camtasia.png Google Map.png Navicat Premium.png Sass.png Word.png
Cent OS.png Google Translation.png Nginx.png Secure Shell.png Yarn.png
Chai.png Gulp.png Node.png Selenium.png iMovie.png
Chat.io.png HTML.png Noteability.png Shopify.png iOS.png
Coda.png Heroku.png OAuth 2.0.png SinonJS.png jQuery.png
CodeBox.png Illustrator.png Open Stack.png Siteground.png
Composer .png Instagram.png OpenID Connect.png Sublime Text.png
Confluence .png J Player.png PHP.png Swagger.png
3 seconds
How do I decrease the wait time to only 3 seconds ?
You have to handle error in some way.
You can try
try {
...
} catch () {
...
}
But I prefer doing things this way
public function handle()
{
Skill::get()->map(function($skill){
if(strpos($skill->img_path, 'http')) return;
$img = $this->getImageFromUrl($skill->img_path)
if(!$img == null) return;
$image_path = '/assets/fe/img/skill/';
$img_name = $skill->name.'.png';
$path = public_path() . $image_path . $img_name;
$fp = fopen($path,'x');
fwrite($fp, $img);
fclose($fp);
if($uploadSuccess) {
$skill->img_path = $image_path . $img_name;
$skill->save();
}
});
}
public function getImageFromUrl($url){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); // The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_TIMEOUT, 2); // The maximum number of seconds to allow cURL functions to execute
$img = curl_exec($ch);
$err = curl_error($ch);
if($err) {
echo $err;
return null;
}
curl_close($ch);
return $img;
}
I refactored some code and if you prefer this keep it if not get only logic and do it as you prefer
Hope this helps
You may use active_url validation rule to check if the given URL is alive. According to the docs:
The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.
if (validator([$skill->img_path], ['active_url'])->fails()) {
// URL is not valid/active
}
else {
// URL is valid/active
}
it's my first time doing signing of cert using openssl. Keep hitting the above error and tried realpath() and appending file:// but still can't get openssl to sign the profile. I don't understand how this works. Any insights would be appreciated.
Edit1: I'm not sure which file is the problematic one. The error messages wasn't specific enough. Is there a way to tell?
Code and screenshots below:
function signProfile()
{
$filename = "./template.mobileconfig";
$filename = realpath($filename);
$outFilename = $filename . ".tmp";
$pkey = dirname(__FILE__) . "/PteKey.key";
$pkey = realpath($pkey);
$certFile = dirname(__FILE__) . "/CertToSign.crt";
$certFile = realpath($certFile);
// try signing the plain XML profile
if (openssl_pkcs7_sign($filename, $outFilename, 'file://'.$certFile, array('file://'.$pkey, ""), array(), 0, ""))
{
// get the data back from the filesystem
$signedString = file_get_contents($outFilename);
// trim the fat
$trimmedString = preg_replace('/(.+\n)+\n/', '', $signedString, 1);
// convert to binary (DER)
$decodedString = base64_decode($trimmedString);
// write the file back to the filesystem (using the filename originally given)
$fh = fopen($filename, 'w');
fwrite($fh, $decodedString);
fclose($fh);
// delete the temporary file
unlink($outFilename);
return TRUE;
}
else
{
return FALSE;
}
}
Remove unwanted fields if not used in
openssl_pkcs7_sign($mobileConfig, $tmpMobileConfig, $certFile, array($pkey, ""), array());
Make sure file paths are correctly supplied.
require_once('variables.php'); //stores abs path to $tmpMobileConfig/$pteKeyPath/$CertToSignPath
$prepend = "file://";
$mobileConfig = realpath("./template.mobileconfig");
$pkey = $prepend . $pteKeyPath;
$pkey = str_replace('\\', '/', $pkey);
$certFile = $prepend . $CertToSignPath;
$certFile = str_replace('\\', '/', $certFile);
$isSignedCert = openssl_pkcs7_sign($mobileConfig, $tmpMobileConfig, $certFile, array($pkey, ""), array());
I Convert Base64 string in php to mp3 sound file but produced file wav Corrupted
Before convert tone sound is rustle
Such as voice files that convert :
http://vocaroo.com/i/s1Dlol5Wu3Zo
php code :
<?php
if(isset($_POST['audio'])){
$data = str_replace('data:audio/wav;base64,', '', $_POST['audio']);
$data = base64_decode($data);
$track_name = get_random_string(mt_rand(6,10)) . ".mp3";
$upl_dir = "../up/" . $track_name;
if( !file_put_contents($upl_dir, $data) ){
$response['status'] = 1;
$response['message'] = "File could not be uploaded. Try again >later.";
echo $data;
echo "E1";
}
echo $data;
}
I test sound before convert And was right.
Base64 Code :
https://ufile.io/174101
js code base64 creator:
function base641()
{
Fr.voice.export(function(url){
// console.log("Here is the base64 URL : " + url);
base = url;
ejem2 = 1;
// alert("Check the web console for the URL");
// $("<a href='"+ url +"' target='_blank'></a>")[0].click();
}, "base64");
};
try this :
file_put_contents('audio.mp3', base64_decode($data));
I am using the below code from the library
https://github.com/antimatter15/jsgif.
I tried to convert the code given below to a gif image file but could not achieve it.
var encoder = new GIFEncoder();
encoder.setRepeat(0);
encoder.start();
var st = '|100:167.1,D,Pencil,3,#000|100:167.1,U|100:167.1,D|102:163.1,M|135:125.1|206:97.1|289:99.1|323:134.1|3\
16:252.1|205:331.1|234:260.1|504:102.1|581:92.1|631:95.1|635:132.1|512:209.1,U|385:29.1,D,,,#66c|384:29.1,M|384:40.1|378:84.\
1|365:168.1|360:215.1|354:269.1|354:300.1|357:313.1|405:319.1|450:314.1|507:291.1|546:260.1|534:223.1|487:171.1|418:119.1|29\
0:131.1|220:201.1|168:284.1|157:339.1|170:353.1|256:308.1|348:212.1|390:118.1|399:77.1|397:68.1|298:82.1|176:168.1|90:265.1|\
70:290.1|70:292.1|250:150.1|465:14.1|594:-42.9|606:-39.9|550:29.1|442:170.1|335:322.1|258:430.1|258:430.1,U';
var frames_array = st.split('|');
$.each(frames_array,function(index,value) {
encoder.addFrame(value);
});
encoder.finish();
var binary_gif = encoder.stream().getData();
var data_url = 'data:image/gif;base64,'+encode64(binary_gif);
What I get for data_url is as given below
data:image/gif;base64,fDEwMDoxNjcuMSxELFBlbmNpbCwzLCMwMDB8MTAwOjE2Ny4xLFV8MTAwOjE2Ny4xLER8MTAyOjE2My4xLE18MTM1OjEyNS4xfDIwNjo5Ny4xfDI4OTo5OS4xfDMyMzoxMzQuMXwzMTY6MjUyLjF8MjA1OjMzMS4xfDIzNDoyNjAuMXw1MDQ6MTAyLjF8NTgxOjkyLjF8NjMxOjk1LjF8NjM1OjEzMi4xfDUxMjoyMDkuMSxVfDM4NToyOS4xLEQsLCwjNjZjfDM4NDoyOS4xLE18Mzg0OjQwLjF8Mzc4Ojg0LjF8MzY1OjE2OC4xfDM2MDoyMTUuMXwzNTQ6MjY5LjF8MzU0OjMwMC4xfDM1NzozMTMuMXw0MDU6MzE5LjF8NDUwOjMxNC4xfDUwNzoyOTEuMXw1NDY6MjYwLjF8NTM0OjIyMy4xfDQ4NzoxNzEuMXw0MTg6MTE5LjF8MjkwOjEzMS4xfDIyMDoyMDEuMXwxNjg6Mjg0LjF8MTU3OjMzOS4xfDE3MDozNTMuMXwyNTY6MzA4LjF8MzQ4OjIxMi4xfDM5MDoxMTguMXwzOTk6NzcuMXwzOTc6NjguMXwyOTg6ODIuMXwxNzY6MTY4LjF8OTA6MjY1LjF8NzA6MjkwLjF8NzA6MjkyLjF8MjUwOjE1MC4xfDQ2NToxNC4xfDU5NDotNDIuOXw2MDY6LTM5Ljl8NTUwOjI5LjF8NDQyOjE3MC4xfDMzNTozMjIuMXwyNTg6NDMwLjF8MjU4OjQzMC4xLFU=
I need to convert this encoded code to an gif image file. How can I achieve it further
try this , may this will help you
<?php
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
?>
Use this (PHP pseudo-code): http://php.net/manual/en/function.imagecreatefromstring.php
function imagegif_from_base64($base64)
{
return imagecreatefromstring(base64_decode(substr($base64, 22) /* remove the "data:image/gif;base64," string */));
}
related get image from base64 string
AS you are using jsgif library you You can do like this to decode image
$imgstr = 'data:image/gif;base64,fDEwMDoxNjcuMSxELFBlbmNpbCwzLCMwMDB8MTAwOjE2Ny4xLFV8MTAwOjE2Ny4xLER8MTAyOjE2My4xLE18MTM1OjEyNS4xfDIwNjo5Ny4xfDI4OTo5OS4xfDMyMzoxMzQuMXwzMTY6MjUyLjF8MjA1OjMzMS4xfDIzNDoyNjAuMXw1MDQ6MTAyLjF8NTgxOjkyLjF8NjMxOjk1LjF8NjM1OjEzMi4xfDUxMjoyMDkuMSxVfDM4NToyOS4xLEQsLCwjNjZjfDM4NDoyOS4xLE18Mzg0OjQwLjF8Mzc4Ojg0LjF8MzY1OjE2OC4xfDM2MDoyMTUuMXwzNTQ6MjY5LjF8MzU0OjMwMC4xfDM1NzozMTMuMXw0MDU6MzE5LjF8NDUwOjMxNC4xfDUwNzoyOTEuMXw1NDY6MjYwLjF8NTM0OjIyMy4xfDQ4NzoxNzEuMXw0MTg6MTE5LjF8MjkwOjEzMS4xfDIyMDoyMDEuMXwxNjg6Mjg0LjF8MTU3OjMzOS4xfDE3MDozNTMuMXwyNTY6MzA4LjF8MzQ4OjIxMi4xfDM5MDoxMTguMXwzOTk6NzcuMXwzOTc6NjguMXwyOTg6ODIuMXwxNzY6MTY4LjF8OTA6MjY1LjF8NzA6MjkwLjF8NzA6MjkyLjF8MjUwOjE1MC4xfDQ2NToxNC4xfDU5NDotNDIuOXw2MDY6LTM5Ljl8NTUwOjI5LjF8NDQyOjE3MC4xfDMzNTozMjIuMXwyNTg6NDMwLjF8MjU4OjQzMC4xLFU=';
$new_data=explode(";",$imgstr);
$type=$new_data[0];
$imgdata=explode(",",$new_data[1]);
$imgstr = base64_decode($imgdata[1]);
// or choose any name instead sample.gif
file_put_contents("sample.gif", base64_decode($imgstr));
If you just wanna use PHP try this:
$str = 'data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAA...';
$data = str_replace('data:image/gif;base64,', '', $str);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data); // base64 decoded image data
$source_img = imagecreatefromstring($data);
$file = uniqid() .'.gif';
$success = file_put_contents($file, $data);
This will save the .gif image in the same folder the php file is located.
I want to know how to get the duration, dimension and size of uploaded video file in PHP. The file can be in any video format.
getID3 supports video formats. See: http://getid3.sourceforge.net/
Edit: So, in code format, that'd be like:
include_once('pathto/getid3.php');
$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");
Note: You must include the getID3 classes before this will work! See the above link.
Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See: http://ffmpeg-php.sourceforge.net/
If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP function filesize() to get the size.
$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!
if (file_exists($vid)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $vid); // check mime type
finfo_close($finfo);
if (preg_match('/video\/*/', $mime_type)) {
$video_attributes = _get_video_attributes($vid, $ffmpeg_path);
print_r('Codec: ' . $video_attributes['codec'] . '<br/>');
print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');
print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
. $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');
print_r('Size: ' . _human_filesize(filesize($vid)));
} else {
print_r('File is not a video.');
}
} else {
print_r('File does not exist.');
}
function _get_video_attributes($video, $ffmpeg) {
$command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
$output = shell_exec($command);
$regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from #1owk3y)
if (preg_match($regex_sizes, $output, $regs)) {
$codec = $regs [1] ? $regs [1] : null;
$width = $regs [3] ? $regs [3] : null;
$height = $regs [4] ? $regs [4] : null;
}
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$ms = $regs [4] ? $regs [4] : null;
}
return array('codec' => $codec,
'width' => $width,
'height' => $height,
'hours' => $hours,
'mins' => $mins,
'secs' => $secs,
'ms' => $ms
);
}
function _human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$sz[$factor];
}
If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):
wp_get_attachment_metadata($videoID);
helped me a lot.
thats why i'm posting it, although its just for wordpress users.
https://github.com/JamesHeinrich/getID3
download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...
<?php
require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
$getID3 = new getID3();
$filename="/fire/My Documents/video/ferrari1.mpg";
$fileinfo = $getID3->analyze($filename);
$width=$fileinfo['video']['resolution_x'];
$height=$fileinfo['video']['resolution_y'];
echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
echo '<pre>';print_r($fileinfo);echo '</pre>';
?>