我正试图从angularJS中获取一个php中的64base编码字符串,但我不太确定我做错了什么。我已经对php运行的makegray.exe写入服务器的图像进行了编码。现在,我正试图获取该图像,并将其返回给angularJS,然后angularJS将其显示给用户。这似乎是一个简单的问题,但我对如何做到这一点感到困惑。
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(){
// some magic code here that grabs the $base64 variable from php
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
php
<?php
$imgname = $_POST["FileName"];
$inputDir = "../../uploads/" . $imgname;
$outputDir = "../../processed/" . $imgname;
$MakeGray = "./makegray " . $inputDir . " " . $outputDir;
$runExec = exec($MakeGray, $out);
$type = pathinfo($outputDir, PATHINFO_EXTENSION);
$data = file_get_contents($outputDir);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "$base64";
?>
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(response){
//response object should hold your base64 image data.
//you can change src of an img tag with ng-src and let the browser render your image.
},function(response){});
}
else{
alert("Please upload an image");
}
}
首先使用.then()
来代替不推荐使用的函数.success()
和.error()
则也如上述代码中那样捕获CCD_ 4。
您可以通过将base64图像作为img
标记的src
来轻松地渲染它。ng-src
应该对此有所帮助。
如果您希望图像为字符串,则应改为选中response
对象。
好的,我开始工作了。。。
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(data){
$scope.data = data;
base64 = data;
$("#img2").prop("src", base64);
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
希望这能帮助其他试图使用base64编码字符串从php向JS显示图像的人!