我正在尝试使用setInterval()
从给定路径重新加载图像。我有一些类似的代码来重新加载运行良好的日志文件:
var auto_refresh = setInterval(
function auto_refresh_log()
{
$('#log_output').load('refresh_log.php').fadeIn("slow");
}, 1000);
refresh_log.php:
<?php $file = "/var/www/html/mainLOG";
$contents = file($file);
$string = implode( $contents);
echo $string; ?>
现在,我只想做两个类似的改变:
- 我不想像refresh_log.php中那样使用固定路径,而是想将JS函数的路径传递到php文件。我该怎么做
- 我不想返回字符串,而是想返回一个图像,然后在我的html文档中使用它。我该怎么做
确切地说,我想做的是:我有一个index.php,用户可以在上面选择文件路径。在设置了一些进一步的参数后,一些计算将在后台开始。结果将保存为浏览器无法读取的TIFF文件。因此,我想使用带有imagemagick
的PHP脚本来转换它们(这很好),并将它们传递回JS。然后,图像应该显示在我的HTML <img id="image_id" ... >
上,并像日志文件一样每隔几秒钟刷新一次。
谢谢!
img
元素的src
属性。
当您更改img
元素的src
时,浏览器将下载资源。使用jQuery属性来执行此操作。您应该附加一个时间戳参数,这样浏览器就不会从本地浏览器缓存中获得缓存实例。
function loadImg(src) {
// append a parameter of "_" to the url
$("#myimg").attr("src", src + "?_=" + Date.now());
}
setInterval(loadImg("path/to/img"), 1000);
在PHP方面,你需要一个脚本,从你存储图像的地方以转换后的格式将图像服务器化。
我已经设法想出了一个使用$.post
而不是$.load
的解决方案。该函数通过以下方式调用:
setInterval(
function auto_refresh_img()
{
var img_path = document.getElementById("image_path").value;
$.post('refresh_img.php',
{path: img_path},
function(data) {
$('#my_div').html(data);}
);
}, 1000);
refresh_img.php
看起来像这样:
<?php $imagepath = $_REQUEST['path'];
if (file_exists($imagepath)) {
$img = new imagick($imagepath."[0]");
$img->setImageFormat('jpg');
$thumbnails0 = $img->getImageBlob();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnails0)."' id='reco_background' style='display:none' />";
}
else {
echo "Image does not exist.";
};
?>
返回的CCD_ 11然后可以用于任何目的。