我在javascript中使用$ .get函数来获取php文件的输出。
如何使用此函数从php文件中获取创建的图像并以html格式显示?
在html文件中(似乎无法将图像设置为“span”):
<span id="box1"></span>
在javascript中:
$.get('here.php', function(data) {
document.getElementById('box1').innerHTML=data;
});
在php中:
//Set content-type header
header("Content-type: image/png");
//Include phpMyGraph5.0.php
include_once('phpMyGraph5.0.php');
这是一个小的空方格。
答案 0 :(得分:2)
将您的html设为此
<img id="box1" src="here.php" />
然后当你想要刷新图像时,只需在点击或任何其他事件的jQuery中执行此操作
var d = new Date();
$('#box1').attr('src', 'here.php?' + d.getTime());
答案 1 :(得分:0)
如果您的php脚本返回原始图像数据,那么您可以通过src链接到它,浏览器会将其识别为图像(因为图像标题也是如此),尽管扩展名为.php ex:
<img src="http://www.test.com/myImageScript.php">
另一种方法是,如果您对图像的内容进行编码并返回没有任何标题的base64编码字符串。来自旧项目的一些代码可能有所帮助。
<?php
$outputs = array('raw','base_64');
if(isset($_GET['source']) && strlen($_GET['source']) > 0 && isset($_GET['w']) && is_numeric($_GET['w']) && isset($_GET['h']) && is_numeric($_GET['h']) && isset($_GET['out']) && in_array($_GET['out'], $outputs))
{
$imgPath = trim(urldecode($_GET['source']));
if(file_exists($imgPath))
{
include 'simpleImage.php';
$w = $_GET['w'];
$h = $_GET['h'];
$out = $_GET['out'];
processImage($imgPath, $w, $h, $out);
}
}
function processImage($img, $w, $h, $out)
{
thumb($img, $w, $h, $out);
}
/*
* BASE_64 image data
*/
function data_uri($contents, $mime)
{
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
/*
* Get mime type of file
*/
function getMIME($filename)
{
if(function_exists('mime_content_type') && $mode==0)
{
$mimetype = mime_content_type($filename);
return $mimetype;
}
elseif(function_exists('finfo_open') && $mode==0)
{
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
}
/*
* Create image
*/
function thumb($data, $w, $h, $out = 'raw')
{
$image = imagecreatefromstring(file_get_contents($data));
$thumb_width = $w;
$thumb_height = $h;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 10, // 2 = Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($out == 'raw')
{
header('Content-Type: image/jpeg');
imagejpeg($thumb);
}
elseif($out == 'base_64')
{
ob_start();
imagejpeg($thumb);
$thumbImageData = ob_get_contents();
$thumbImageDataLength = ob_get_length();
ob_end_clean();
echo '<img src="' . data_uri($thumbImageData, getMIME($data)) . '">';
}
}
?>