douqi2571 2012-10-01 10:31 采纳率: 0%
浏览 72
已采纳

通过JSON将base64'd映像发送到PHP GD库

So I send the base64 image text to the php file with jquery/javascript like this:

//Upload picture
$('#uploadPictureBtnHtml').click(function(){
    OpenLoader();
   var baseEncPicData = $('#chosenPictureData').val();
    $.ajax({
        type:'POST', url:'upload_picture.php',  dataType:"json",  data:{ PicFile: baseEncPicData },
        success:function (upload_pic_data) {
            if (upload_pic_data[0] == 'true') {
                    alert("it worked!");
                    CloseLoader();
            }
            else{
                    //upload_pic_data[1] will return PHP errors
                    alert("Why it didnt work: "+upload_pic_data[1]+" ");
                    CloseLoader();
            }
        }
        });
});

I know this works fine because if I take the baseEncPicData variable and output it like this:

$('#some_div').html('<img src="data:image/jpeg;base64,'+baseEncPicData+'" />');

It works just great and the image shows without an issue.

When I send this to the PHP file, I decode and "reassemble" it like this:

$dataUno = htmlspecialchars(trim(urldecode($_POST['PicFile'])));
$dataDos = base64_decode($dataUno);
$data = imagecreatefromstring($dataDos);
$the_new_png = imagepng($data, $the_directory);

The error I receive is only in PHP which is:

 imagecreatefromstring() [function.imagecreatefromstring]: Empty string or invalid image
 imagepng() expects parameter 1 to be resource

Which leads me to believe that it's not decoding the JSON correctly because there are characters being stripped that are part of the base64'd image. This is just an assumption. Not exactly sure what I'm doing wrong. Any help would be awesome. Thanks for taking your time to read this.

  • 写回答

1条回答 默认 最新

  • douguai4653 2012-10-01 10:55
    关注

    Remove this string:

    htmlspecialchars(trim(urldecode($_POST['PicFile'])));

    ... and process just $_POST['PicFile'] instead. With that preprocessing you turn all + characters (allowed in Base64) into spaces (), effectively broking the binary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题