I am working with php,I am getting Base64 image in api,And i want to save/store
into database and want to upload image into server,how can i do this ?
I tried with following code but getting following error
"failed to open content, Http writer doest not support writetable connections"
function imageupload()
{
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode($files);
$image_name = md5(uniqid(rand(), true));
$filename = $image_name . '.' . 'png';
$path = base_url().'upload/blog/';
file_put_contents($path . $filename, $image);
}
Remove base_url() from path.
OR
Check this out
jQuery :
$(document).on('click', '#upload', function () {
let form_data = new FormData();
let data_url = document.getElementById('my_image').toDataURL('image/png');
data_url = data_url.replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
form_data.append('uploaded_image', data_url);
$.ajax({
url: 'upload-avatar',
method: 'post',
data: form_data,
dataType: 'json',
contentType: false,
async: true,
processData: false,
cache: false
});
});
PHP :
$img = $this->request->getPost('uploaded_image'); // for ci4
$img = $this->input->post('uploaded_image'); // for ci3
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$file_data = base64_decode($img);
file_put_contents(/* my_path and my_file_name */, $file_data);
Related
I need your help.
I try to generate image like this with canvas (two images and text):
This i want
But after I save canvas file via php to png image all images disappear (text is OK)
Where is the problem with images ? I try this two day's but I can do this. I post here my code maybe some one find what I can do.
INDEX index.php
<canvas id="myCanvas" width="500" height="400"></canvas>
<img id="canvasImg"/>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function loadImages(sources, callback){
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources){
numImages++;
}
for(var src in sources){
images[src] = new Image();
images[src].onload = function(){
if(++loadedImages >= numImages){
callback(images);
}
};
images[src].src = sources[src];
}
}
var sources = {
arnold : "arnold.jpg",
silvester : "silvester.jpg"
};
loadImages(sources, function(images){
context.drawImage(images.arnold, 20, 20);
context.drawImage(images.silvester, 280, 20);
});
context.font = "15pt Calibri";
context.fillText("Arnold Schwarzenegger", 30, 300);
context.font = "15pt Calibri";
context.fillText("Silvester Stalonne", 310, 300);
var dataURL = canvas.toDataURL();
document.getElementById('canvasImg').src = dataURL;
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: dataURL
}
}).done(function(response) {
console.log('saved: ' + response);
});
</script>
PHP test.php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
//send request to ocr
print $success ? $file : 'Unable to save the file.';
I am trying to store Canvas image to server through PHP I can see the file but it shows 0 bytes. Can you please help me to fix this issue.
Here is my code below:
HTML:
<img id="image" src="data:image/png;base64,iVBORw0K..." />
JQUERY:
$('.submit').unbind().click(function(){
var dataURL = $('#img').attr('src');
$.ajax({
type: "POST",
url: "saveimage.php",
dataType: 'json',
cache: false,
data: {
imgBase64: dataURL
}
});
});
PHP:
$upload_dir = "../images/";
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
file_put_contents($file, $data);
It should be $img = $_POST['imgBase64']
not $img = $_POST['data'] in your php
as your data object 's key name is imgBase64 when sending the ajax post request
I am trying to save the captured image in my server as jpg/png,I decoded the string as base64 and uploaded it but when i open the image it says 'the file cant open'. I don't understand why this is happening or i just missed any code.
jquery
navigator.camera.getPicture(onSuccess, onFail, { quality: 100,destinationType: Camera.DestinationType.DATA_URL });
function onSuccess(imageURI) {
var image = document.getElementById('dr_preview');
image.src = imageURI;
snapSrc = imageURI;
}
var img = document.getElementById('dr_preview');
var src = $('#dr_preview').attr('src');
console.log(src);
var dataparam = 'type=3&dr='+dr_value+'&image='+src;
$.ajax({
type: 'POST',
dataType: 'json',
async: true,
url: 'http://localhost/v_2/dr-getDrDetails.php',
data: dataparam,
cache: true,
success: function(data)
{
}
});
php
$data = $_POST['image'];
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
$filePath = $_SERVER['DOCUMENT_ROOT']. '/v_2/scanedDR/'.$dr.'.PNG';
$file = fopen($filePath, 'w');
fwrite($file, $data);
fclose($file);
You can use, this function that convert base64 to image.
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
Hi I am just trying to upload image using navajcrop in yii extension. which upload image using ajax call. I am able to upload image. but problem is that uploaded image can not be view.when i view uploaded image it display below error:- Error interpreting JPEG image file (Not a JPEG file: starts with 0x75 0xab)
controller code:-
public function actionUpload(){
$model = new Register();
if(isset($_POST)){
$rnd = rand(0, 9999);
$img = $_POST['image'];
if($img != '/img/noimage.png' && $img != $model->image){
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = Yii::app()->basePath . '/../themes/front/assets/img/photo/' . $rnd.'.jpg';
file_put_contents($file, $data);
}
}
}
JS code :-
function doSomething(obj,res){ //the 'obj' is IMG tag, 'res' is base64image
$.ajax({
cache: false,
type: 'post',
//url: <?php echo Yii::app()->createUrl('site/upload');?>,
url: baseUrl+"/admin/ajax/Upload",
data: 'image='+res,
success: function(){
obj.attr('src',res);
}
});
}
view code:-
<?php $this->widget('ext.NavaJcrop.ImageJcrop', array(
'config' => array(
'title'=>$model->image,
'image'=>$model->image,//required, all field below are not required.
'id'=>'nava-jcrop',
//'unique'=>true,
'buttons'=>array(
'cancel'=>array(
'name'=>'Cancel',
'class'=>'button-crop',
'style'=>'margin-left: 5px;',
),
/*'edit'=>array(
'name'=>'Edit',
'class'=>'button-crop',
'style'=>'margin-left: 5px;',
),*/
'crop'=>array(
'name'=>'Crop',
'class'=>'button-crop',
'style'=>'margin-left: 5px;',
)
),
'options'=>array(
'imageWidth'=>150,
'imageHeight'=>175,
'resultStyle'=>'position: fixed;top: 400px;max-width:350px;max-height:350px;z-index: 9999;',
'resultMaxWidth'=>350,
'resultMinWidth'=>350,
),
'callBack'=> array(
'success'=>"function(obj,res){doSomething(obj,res);}",
'error'=>"function(){alert('error');}",
)
)
)); ?>
Please help to solve this erro.
Hi I have solved my question it was bug in below syntax.
in controller action :- edit
$img = str_replace('data:image/png;base64,', '', $img);
$file = Yii::app()->basePath . '/../themes/front/assets/img/photo/' . $rnd.'.png';
This question already has answers here:
Pass Blob through ajax to generate a file
(2 answers)
Closed 8 years ago.
I'm trying to upload an image to a php server from a mobile app, converting file to blob and then uploading the blob with ajax. I get the image url after taking the photo with mobile. The uploaded file is empty. I think that should be an error while reading the file and converting to blob.
Client
var blob;
function get(){
var image = document.getElementById('image');
var file=image.src;
var oReq = new XMLHttpRequest();
oReq.open("GET", file, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
blob = new Blob([oReq.response], {type: "image/jpg"});
};
oReq.send();
var fd = new FormData();
fd.append("file", blob, "filename.jpg");
$.ajax({
type: 'POST',
url: 'http://site/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
alert(data);
});
}
Server
<?php
$dir="uploads";
file_put_contents($dir."/image.jpg",$_POST['data']);
echo "Done";
?>
Solved using base64 image with that
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';