convert base64 to sound file in php tone sound is rustle - php

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));

Related

Flutter web file upload

void _uploadFile(Event event) async {
print("called");
final files = uploadInput.files;
final file = files![0];
_fileNameController.text = file.name;
// Get the file contents as a List<int>
final reader = new FileReader();
reader.readAsArrayBuffer(file);
await reader.onLoad.first;
final contents = reader.result as List<int>;
// Encode the file contents as a base64 string
final encodedFile = base64Encode(contents);
var response = await http.post(Uri.parse("http://url/img_test/img.php"),
body: jsonEncode(<String, String>{
'file': encodedFile,
})
);
print(response.body);
if (response.statusCode == 200) {
// Handle the success case
print("ok");
} else {
// Handle the error case
print("try");
}
}
I all ready set as file in body but till it shows
Error shows in flutter
Warning: Undefined array key "file" in M:\WEB\htdocs\img_test\img.php on line 7
PHP API:
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
?>
your request post not send file, this string value, you can try decode in your php file like this
$base64string = "data:image/jpeg;base64,".$POST['file'];
list($type, $base64string) = explode(';', $base64string);
list(,$extension) = explode('/',$type);
list(,$base64string) = explode(',', $base64string);
$fileName = uniqid()'.'.$extension;
$imageFile = base64_decode($base64string);
file_put_contents($path.$fileName, $imageFile);

React-Native Base 64 Data to FileSystem issue

I have a very simple PHP file that returns my image as BASE64 data
<?php
require_once 'database_connections.php';
$data = json_decode(file_get_contents("php://input"));
$id = mysqli_real_escape_string($con, $data->id);
$page = mysqli_real_escape_string($con, $data->page);
$path = "../../images/" . $id . '/' . $page . '.jpg';
$imagedata = file_get_contents($path);
$base64 = base64_encode($imagedata);
echo($base64);
?>
In my react app, I am fetching this data like below
export const getImage = async () => {
try {
const response = await axios.post(
url,
{
id: '11bb2c1b-c262-4171-b614-d8af46898efb',
page: '001',
}
);
return response.data;
} catch (error) {
// handle error
console.error(error.message);
}
};
my base64 response like below:
/9j/2wCEAAEBAQEBAQEBAQECAQEBAgICAQECAgICAgICAgIDAgMDAw...
and finally my FileSystem code is like below:
const image = await getImage();
const filename = FileSystem.documentDirectory + 'imagetest.jpg';
await FileSystem.writeAsStringAsync(filename, image, {
encoding: FileSystem.EncodingType.Base64,
});
I'm not getting any error but my file is not being saved as I try. I have been working on this for hours but didn't solve my issue.
any advice would be appreciated!
Edit: I can show the base64 image in an Image component.
you wont be able to see your saved image file in FileSystem.documentDirectory , you need to
FileSystem.readDirectoryAsync(FileSystem.documentDirectory).then(data => {
data.forEach(filename_ => {
console.log("=cached image==***===" + filename_)
})
to check if it is there. FileSystem.documentDirectory is only "pragmatically accessible"

Sending image using sockets with base 64 format by JSON

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;
}
}
}

I want to decode base64 encoded data which is image/gif? How can I do that in php?

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.

Decode Base64 string in PHP recieved from JSON post

I'm working on a project where i can select an image (simple file select) and send it via JSON to a PHP MySQL insert page.
Upload page looks like this:
if (input.files && input.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
$('#img').attr("src", e.target.result);
var Naam = $('input[type=file]').val();
$('#base').text(e.target.result);
var Foto = e.target.result;
var Barcode = $('#barcode').val();
obj['Barcode'] = Barcode;
obj['Naam'] = Naam;
obj['Foto'] = Foto;
//execute ajax send
$.ajax({
url : 'insert.php',
type : 'POST',
data : obj,
dataType : 'json',
success : function(msg) {
alert("msg");
}
});
//$.post("insert.php", obj, function (data) {}, "json");
//alert("msg");
};
FR.readAsDataURL(input.files[0]);
and my PHP page:
$Barcode = $_POST["Barcode"];
$Naam = $_POST["Naam"];
$Name = preg_replace('/^.+[\\\\\\/]/', '', $Naam);
$Foto = base64_decode($_POST["Foto"]);
$query = "INSERT INTO voorraad_foto (barbody, location, foto) VALUES ('$Barcode','$Name','{$Foto}')";
$results = mysqli_query($db,$query);
And my table field is a BLOB.
But when it execute this, everything works fine except that it doesn't insert it as a blob, but pure string
I've tried with removing the
preg_replace('#data:image/[^;]+;base64,#', '', $Foto)
but doesn't make any difference, same when trying to add headers, but nothing..
What am i doing wrong, or is there something obvious that i'm not getting?
Thx.
I solved it in some kind of way:
I wrote a function that gets the Base64 string, decodes it and writes it to a Temp file.
Then i read that file again and upload that to my databse.
When success, delete the file.
It may not be the most effecient way, but it works!
function WriteToImageAndGetData($base64_string, $File) {
//Write to file
$ifp = fopen($File, "wb");
$data = explode(',', $base64_string); //Split Base64 string
fwrite($ifp, base64_decode($data[1])); //Decode Base64 string
fclose($ifp);
//Read from file
$fp = fopen($File, 'r');
$data = fread($fp, filesize($File)); //Read file contents
$data = addslashes($data);
fclose($fp);
return $data;
}

Categories