-1

我正在使用 php GD 库创建图像,它工作正常,但是当我在其中使用一些 ajax 时,它会出现一些问题,例如 ajax 响应是不可读的文本。基本上我想使用ajax获取图像。我的代码如下:

html代码:

<textarea name="txt" id="txt"></textarea>

Jquery Ajax code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
  <script type="text/javascript">
$(document).ready(function() {

    $("#txt").change(function() {
        var txt = $("#txt");
        //alert(txt.val());

         var myData = 'txt='+ txt.val(); //build a post data structure


            jQuery.ajax({
            type: "POST", // Post / Get method
            url: "create.php", //Where form data is sent on submission
            //contentType: "image/png",
            dataType:"text", // Data type, HTML, json etc.
            data:myData, //Form variables
            success:function(response){
                //alert(response);
                var result = response;

            /*$("#socialline").hide();
            $("#msgline").show();*/

             document.getElementById('img').innerHTML = response;

                //$('.loading').remove();
            },
            error:function (xhr, ajaxOptions, thrownError){
                //On error, we alert user
                alert(thrownError);
            }
            });
    });

    });
    </script>

Php file (create.php) code

<?php  
$txt = $_POST['txt'];
    $im = @imagecreate(400, 300) or die("Cannot Initialize new GD image stream");
    $background_color = imagecolorallocate($im, 0, 0, 0);
    $text_color = imagecolorallocate($im, 233, 14, 91);
    imagestring($im, 55, 55, 55,  $txt, $text_color);
    header("Content-Type: image/png");
    imagepng($im);
    imagedestroy($im);

    //echo '<img src="image.jpg" />';

    //echo $txt;
    //echo $abc;


?>

The output is something like that

�PNG  IHDR�,�yw�PLTE�[an��IDATh���1 �0��@�@(�C!ࢇi�^@p�Щ���W�x�B����3�H]D��"���?����_ӭ*��Y��?I��d�}g��T''2���U��;���� =%'�N��3}��L8���҇���{��E�-�X�\���7%8o��`IEND�B`�
4

2 回答 2

1
<?php
header("Content-Type: image/png");
$im = @imagecreate(110, 20)
    or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>
于 2013-06-04T13:46:50.523 回答
0

您想要做的(另见@Pekka 的评论)是将 url (create.php) 作为图像文件的源传递。

基本上:

<img src="create.php?txt=some%20text" />

文件创建.php:

<?php  
$txt = $_GET['txt'];
$im = @imagecreate(400, 300) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 55, 55, 55,  $txt, $text_color);
header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);
?>

请注意,我将 POST 更改为 GET(您不能在 img 中发布,但可以使用查询参数)。所以想想后果(url编码示例中参数中的文本)。

于 2013-06-04T13:33:44.800 回答