0
votes

HTML: One image (jpg) and a canvas. Set to proper dimensions. Not displayed

<img src="images/facebook.jpg" id="facebook-image" style="display: none;"/>
<canvas width="2000" height="1047" id="canvas" style="display: none;" ></canvas>

AngularJS: Draw the image in the canvas and add text to the canvas. POST to php file

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = document.getElementById("facebook-image");
context.drawImage(image,0,0);
context.fillText('Hello world', 1300, 580);
var dataURL = canvas.toDataURL("image/png");

var config = {
    method : 'POST',
    url: 'save-image.php',
    headers : {
        'Content-Type' : 'application/upload'
    },
    data: { image: dataURL }
};

$http(config)
    .then(function result(res){
       //Goes in here and 
    }, function error(er){

    });

PHP: Delete 'data:image/png;base64,', Replace spaces by '+', SAVE

<?php

$img = $_POST['image'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$file = "images/image_name.png";
$success = file_put_contents($file, $img);
echo "ok";
?>

Error :
The file is saved on the server, but it is empty

Possible problems:
- Image: Mime type is jpg, saved as png canvas and saved as png file.
- Image: not displayed in html
- AngularJS config: Headers!?
- php : Delete data:image/png;base64,
- php : Replace spaces by + sign

1
1.) why are you passing $data to file_put_contents? shouldnt it be $img? 2.) try this $img = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $img)); instead of the str_replace lines - stackg91
I fixed first and tried 2nd without success - gr3g
is the file empty or is the image black or white? - stackg91
The file is empty. Still no success... - gr3g
maybe its because the size of the base64 is to large? that is the only possibility but when you echo your $img in php it is there the problem is the file_put_contents? right? - stackg91

1 Answers

1
votes
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = document.getElementById("facebook-image");
context.drawImage(image,0,0);
context.fillText('Hello world', 1300, 580);
var dataURL = canvas.toDataURL("image/png");

var config = {
    method : 'POST',
    url: 'save-image.php',
    data: { image: dataURL }
};

$http(config)
    .then(function result(res){
       //Goes in here and 
    }, function error(er){

    });

php

<?php
$postdata = file_get_contents("php://input");

$request = json_decode($postdata);
$img = $request->image;
$name = $request->name;
$img = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $img)); 
$file = "images/fb/my-file.png";
$success = file_put_contents($file, $img);
echo $success;
?>