PHP - 使用jQuery ajax进行图像编辑无法正常工作

时间:2016-01-19 09:14:27

标签: php jquery ajax php-gd

我正在尝试使用jQuery ajax在我的图像上添加一些文本,但是在ajax响应中获取了一些奇怪的文本而没有获得正确的图像。

enter image description here

jQuery Ajax代码:

$(document.body).on('click', '.certificate_tab .tab-content li a' ,function(){
    var data_did = $(this).attr("data-diplomaidx");
    if(data_did != ""){
        $.ajax({
            url: "diploma/certificate",
            type: 'POST',
            data: "id=" + data_did,
            success: function (html){
                if(html != ""){
                    $("#CertificateModel .modal-content").append(html);
                    $('#CertificateModel').modal('show');
                }else{

                }
            }
        });
        return false;
    }
});

并在ajax上调用此函数:

public function certificate()
{
    if (Auth::check()) {
        $ScratchProject = new ScratchProject();

        $GetMyDiploma = $ScratchProject->GetMyDiploma();

        $ImagePath = url().'/public/upload/certificate/'.$GetMyDiploma[0]->CertificateTemplate;

        $text = "Hello Admin";
        $source_file = $ImagePath;
        //saveImageWithText("",  $image_filepath);

        //Set the Content Type
        header('Content-type: image/jpeg');

        // Copy and resample the imag
        list($width, $height) = getimagesize($source_file);
        $image_p = imagecreatetruecolor($width, $height);
        $image = imagecreatefromjpeg($source_file);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

        // Prepare font size and colors
        $text_color = imagecolorallocate($image_p, 0, 0, 0);
        $bg_color = imagecolorallocate($image_p, 255, 255, 255);
        $font = 'resources/assets/front/fonts/FontAwesome.otf';
        $font_size = 12;

        // Set the offset x and y for the text position
        $offset_x = 0;
        $offset_y = 20;

        // Get the size of the text area
        $dims = imagettfbbox($font_size, 0, $font, $text);
        $text_width = $dims[4] - $dims[6] + $offset_x;
        $text_height = $dims[3] - $dims[5] + $offset_y;

        // Add text background
        imagefilledrectangle($image_p, 0, 0, $text_width, $text_height, $bg_color);

        // Add text
        //imagettftext($image_p, $font_size, 0, $offset_x, $offset_y, $text_color, $font, $text);
        imagettftext($image_p, 20, 0, 100, 220, $text_color, $font, $text);

        // Save the picture
        imagejpeg($image_p);

        // Clear
        imagedestroy($image);
        imagedestroy($image_p);
    }
}

知道我的代码有什么问题吗?

感谢。

1 个答案:

答案 0 :(得分:1)

首先,您无需在响应中发送图像 ,只需发送图像URI,然后使用js将其加载/附加到前端。

接下来,如果您仍希望继续,则需要发送json_encoded()对象内编码的图像base64。然后使用img设置更新src,如下所示。

<img src="data:image/png;base64,<encoded image data goes here>" alt="Red dot">