上传的图像会导致PDF库出错

时间:2017-01-29 02:04:33

标签: php image ckeditor pdf-generation

我正在使用ckeditor来处理HTML文本。当我在其中粘贴图像时,ckeditor会上传图像。我使用了像pdf库的TCPDF和MPDF,我有两个不同的错误,每个库中有一个错误。

  

mPDF错误:图像错误( SOURCE-IMAGE ):解析临时错误   用GD库创建的文件图像对象,用于解析PNG图像

     

TCPDF错误:[图片]无法获得图片的大小:( SOURCE-IMAGE

我在ckeditor中粘贴时上传图片的代码如下:

<?php
session_start();

class image{

    private $save_path = 'uploads/';
    private $image_string = '';
    private $image_name = '';
    private $image;
    private $response = array();

    public $loaded = false;

    public function __construct(){
        $this->response = array(
            'error' => 1,
            'message' => 'unknown error.'
        );

        $this->image_string = filter_input(INPUT_POST, 'image');


        $ext = substr($this->image_string,11,3);
        $randomLetters = $rand = substr(md5(microtime()),rand(0,26),6);
        $imgnumber = count(scandir($this->save_path));

        $this->image_name = "$imgnumber$randomLetters.$ext";

        if(!empty($this->image_name) && !empty($this->image_string)){
            $this->loaded = true;
        }
    }

    public function save(){
        if(!empty($this->image_name) && !empty($this->image_string)){
            return $this->progress();
        }
        else{
            $this->response['message'] = 'Error. Not all required infor is given.';
            $this->response['error'] = 1;
            return $this->response;
        }
    }

    private function progress(){
        $imgarr = explode(',', $this->image_string);
        if(!isset($imgarr[1])){
            $this->response['message'] = 'Error on post data image. String is not the expected string.';
            $this->response['error'] = 1;
            return $this->response;
        }
        $this->image = base64_decode($imgarr[1]);
        if(!is_null($this->image)){
            $file = $this->save_path . $this->image_name;
            if(file_exists($file)){
                $this->response['message'] = 'Image already exists on server.';
                $this->response['error'] = 1;
                return $this->response;
            }
            if(file_put_contents($file, $this->image) !== false){
                $this->response['message'] = 'Image saved to server';
                $this->response['error'] = 0;
                $this->response['source'] = '../plugins/imageuploader/'.$file;
                return $this->response;
            }
            else{
                $this->response['error'] = 1;
                $this->response['message'] = 'Error writing file to disk';
                return $this->response;
            }
        }
        else{
            $this->response['message'] = 'Error decoding base64 string.';
            return $this->response;
        }
    }
}

$img = new image();
if($img->loaded){
    $result = $img->save();
    echo json_encode($result);
}
else{
    $result = array(
        'error' => 1,
        'message' => 'Not all post data given'
    );
    echo json_encode($result);
}
?>

什么可能导致此错误?

修改 ajax代码是ckeditor代码的一部分,部分就在这里,图像就像base64代码一样:

function h(a, d) {
        if (a && "function" === typeof a.getAsFile) { 
            var b = a.getAsFile(), c = new FileReader;
            c.onload = function (a) {
               var fd = new FormData();
                fd.append('image', a.target.result); //the base64 of image with format equals in src of tag img in html
                $.ajax({
                    type: 'POST',
                    url: '../plugins/imageuploader/ajaxupload.php',
                    data: fd,
                    processData: false,
                    contentType: false,
                    dataType: 'json'
                }).done(function(data) {
                    if((data.error == 0) && (typeof data.source != 'undefined')){
                        //alert(data.source);
                        var b = d.document.createElement("img", {attributes: {src: data.source}});
                        setTimeout(function () {
                            d.insertElement(b)
                        }, 10)
                    }else{
                        alert('Não foi possível carregar a imagem:\nErro - '+data.message);  // show the message error if it can't be uploaded.
                    }
                });
            };
            c.readAsDataURL(b);
        }
  }

2 个答案:

答案 0 :(得分:4)

在发送数据之前,您需要对base64的某些字符进行编码。例如,+和=将导致代码行为不同。 或者使用base64编码的十六进制值。

编辑: 取决于表格。但您可以使用此功能设置一个按钮来转换textarea:

function escapeChars(){
   var value = document.getElementById("myTextarea").value;
   value = value.replace("+", "%2b");
   value = value.replace("/", "%2f");
   value = value.replace("=", "%3d");
   document.getElementById("myTextarea").value = value;
}

或者如果你使用ajax,只需在发送之前使用该功能。

在php中,还原更改:

$this->image_string = str_replace(array("%2b", "%2f", "%3d"), array("+", "/", "="), $_POST['image']);

而不是$this->image_string = filter_input(INPUT_POST, 'image');

EDIT2 在php:

<?php
session_start();

class image{

    private $save_path = 'uploads/';
    private $image_string = '';
    private $image_name = '';
    private $image;
    private $response = array();

    public $loaded = false;

    public function __construct(){
        $this->response = array(
            'error' => 1,
            'message' => 'unknown error.'
        );

        $this->image_string = str_replace(array("%2b", "%2f", "%3d"), array("+", "/", "="), $_POST['image']);

        $imgarr = explode(',', $this->image_string);
        if(!isset($imgarr[1])){
            return;
        }
        $this->image_string = $imgarr[1];

        $namearray = explode('.', $imgarr[0]);
        $ext = end($namearray);
        if(!in_array($ext, array('jpg','png')))
            return false;

        $randomLetters = $rand = substr(md5(microtime()),rand(0,26),6);
        $imgnumber = count(scandir($this->save_path));

        $this->image_name = "$imgnumber$randomLetters.$ext";

        if(!empty($this->image_name) && !empty($this->image_string)){
            $this->loaded = true;
        }
    }

    public function save(){
        if(!empty($this->image_name) && !empty($this->image_string)){
            return $this->progress();
        }
        else{
            $this->response['message'] = 'Error. Not all required infor is given.';
            $this->response['error'] = 1;
            return $this->response;
        }
    }

    private function progress(){

        $this->image = base64_decode($this->image);
        if(!is_null($this->image)){
            $file = $this->save_path . $this->image_name;
            if(file_exists($file)){
                $this->response['message'] = 'Image already exists on server.';
                $this->response['error'] = 1;
                return $this->response;
            }
            if(file_put_contents($file, $this->image) !== false){
                $this->response['message'] = 'Image saved to server';
                $this->response['error'] = 0;
                $this->response['source'] = '../plugins/imageuploader/'.$file;
                return $this->response;
            }
            else{
                $this->response['error'] = 1;
                $this->response['message'] = 'Error writing file to disk';
                return $this->response;
            }
        }
        else{
            $this->response['message'] = 'Error decoding base64 string.';
            return $this->response;
        }
    }
}

$img = new image();
if($img->loaded){
    $result = $img->save();
    echo json_encode($result);
}
else{
    $result = array(
        'error' => 1,
        'message' => 'Not all post data given'
    );
    echo json_encode($result);
}
?>
发送ajax之前在Javascript中

function escapeChars(value){
   value = value.replace("+", "%2b");
   value = value.replace("/", "%2f");
   value = value.replace("=", "%3d");
   return value;
}

然后你可以在值中使用escapeChars。

答案 1 :(得分:1)

如果图像成功上传到服务器并且pdf库引发了错误。

这里可能的原因可能是pdf库无法读取图像文件,请确保图像文件的路径正确。

由于pdf库将html转换为pdf,因此必须预期相对路径 例如: -

 <img src="http://yourdomain/image_path">

我测试了tcpdf库,如果库无法找到图像,发现了同样的问题和相同的错误。