2015-09-17 59 views
0

HTML:一個圖像(jpg)和一個畫布。設置爲適當的尺寸。不顯示將服務器上的畫布從angularjs保存到php

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

AngularJS:繪製圖像中的畫布,並添加文本到畫布上。 POST到PHP文件

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:刪除 '數據:圖像/ PNG; BASE64,',由 '+' 替換空間,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"; 
?> 

錯誤:
文件被保存在服務器上,但它是空

可能出現的問題:
- 圖片:MIME類型爲JPG,保存爲PNG CA nvas並保存爲PNG文件。
- 圖片:不顯示在html
- AngularJS config:Headers!?
- PHP:刪除數據:圖像/ PNG; BASE64,
- PHP:由+符號

+0

1)你爲什麼傳遞$數據file_put_contents替換空間?不應該是$ img? 2)試試這個$ img = base64_decode(preg_replace('#^ data:image/\ w +; base64,#i','',$ img));而不是str_replace行 – stackg91

+0

我先固定並嘗試第二次沒有成功 – gr3g

+0

是文件是空的還是圖像黑色或白色? – stackg91

回答

1
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; 
?> 
相關問題