我正在使用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`�
答案 0 :(得分:0)
你想要做什么(另见@ Pekka的评论)是将url(create.php)作为图像文件的来源传递。
基本上:
<img src="create.php?txt=some%20text" />
文件create.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在示例中对参数中的文本进行编码)。
答案 1 :(得分:0)
<?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);
?>
答案 2 :(得分:-1)
只需从php中返回一个base64编码的img:
$image = base64_encode($imageGDRender);
echo json_encode(array('image'=>$image));
然后执行你的ajax请求并将结果加载到你的img:
的src中 var base64Image = data.image;
$('#image').attr('src','data:image...'+base64Image);
像:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA......." />
Ajax and returning image created by PHP GD
- 或 -
将GD图像保存在本地文件中并返回路径。