jQuery 和 php 图像旋转拼图

发布于 2024-08-17 02:44:14 字数 2435 浏览 7 评论 0 原文

Jquery puzzle

我有一个 php 脚本,它从文件夹中返回随机 jpg 图像的名称。这很好,因为我根本不需要重命名图像;我只需将它们放入文件夹中,随机发生器就可以工作。现在,我这样调用脚本 - http://mydomain.com/images/rotate.php< /a> - 在简单的网页重新加载时,它会交换图像。

但我想让它与 jQuery 一起工作,因为我希望每隔十秒左右将图像交换到新图像中,并且淡入和淡出它们。

编辑 1/23/10:

这通过交换 spacer.gif 来实现。可能有一个更优雅的解决方案,但这对我有用。蒙克通过 MidnightLightning 的想法弄清楚了这一点:

function swapImage(){
  var time = new Date();
  $('#image').fadeOut(1000)
   .attr('src', 'http://mydomain.com/spacer.gif')
   .attr('src', 'http://mydomain.com/images/rotate.php?'+time.getTime())
   .fadeIn(1000);
}

var imageInterval = setInterval('swapImage()',10*1000); 

这就是rotate.php:

<?php

$folder = '.';


    $extList = array();
    $extList['gif'] = 'image/gif';
    $extList['jpg'] = 'image/jpeg';
    $extList['jpeg'] = 'image/jpeg';
    $extList['png'] = 'image/png';


$img = null;

if (substr($folder,-1) != '/') {
    $folder = $folder.'/';
}

if (isset($_GET['img'])) {
    $imageInfo = pathinfo($_GET['img']);
    if (
        isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
        file_exists( $folder.$imageInfo['basename'] )
    ) {
        $img = $folder.$imageInfo['basename'];
    }
} else {
    $fileList = array();
    $handle = opendir($folder);
    while ( false !== ( $file = readdir($handle) ) ) {
        $file_info = pathinfo($file);
        if (
            isset( $extList[ strtolower( $file_info['extension'] ) ] )
        ) {
            $fileList[] = $file;
        }
    }
    closedir($handle);

    if (count($fileList) > 0) {
        $imageNumber = time() % count($fileList);
        $img = $folder.$fileList[$imageNumber];
    }
}

if ($img!=null) {
    $imageInfo = pathinfo($img);
    $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
    header ($contentType);
    readfile($img);
} else {
    if ( function_exists('imagecreate') ) {
        header ("Content-type: image/png");
        $im = @imagecreate (100, 100)
            or die ("Cannot initialize new GD image stream");
        $background_color = imagecolorallocate ($im, 255, 255, 255);
        $text_color = imagecolorallocate ($im, 0,0,0);
        imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
        imagepng ($im);
        imagedestroy($im);
    }
}

?>

Jquery puzzle

I've got a php script that returns the name of random jpg image from a folder. It's nice because I don't have to rename the images at all; I just drop them in the folder and the randomizer works. Right now, I call the script like this - http://mydomain.com/images/rotate.php - and on a simple web page reload, it swaps the images.

But I'd like to have it work with jQuery in that I'd like to have the image swap in a new image on an interval of ten seconds or so, and also fade them in and fade them out.

Edit 1/23/10:

This works by swapping in a spacer.gif. There might be a more elegant solution, but this works for me. Munch figured it out, by way of an idea by MidnightLightning:

function swapImage(){
  var time = new Date();
  $('#image').fadeOut(1000)
   .attr('src', 'http://mydomain.com/spacer.gif')
   .attr('src', 'http://mydomain.com/images/rotate.php?'+time.getTime())
   .fadeIn(1000);
}

var imageInterval = setInterval('swapImage()',10*1000); 

And this is rotate.php:

<?php

$folder = '.';


    $extList = array();
    $extList['gif'] = 'image/gif';
    $extList['jpg'] = 'image/jpeg';
    $extList['jpeg'] = 'image/jpeg';
    $extList['png'] = 'image/png';


$img = null;

if (substr($folder,-1) != '/') {
    $folder = $folder.'/';
}

if (isset($_GET['img'])) {
    $imageInfo = pathinfo($_GET['img']);
    if (
        isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
        file_exists( $folder.$imageInfo['basename'] )
    ) {
        $img = $folder.$imageInfo['basename'];
    }
} else {
    $fileList = array();
    $handle = opendir($folder);
    while ( false !== ( $file = readdir($handle) ) ) {
        $file_info = pathinfo($file);
        if (
            isset( $extList[ strtolower( $file_info['extension'] ) ] )
        ) {
            $fileList[] = $file;
        }
    }
    closedir($handle);

    if (count($fileList) > 0) {
        $imageNumber = time() % count($fileList);
        $img = $folder.$fileList[$imageNumber];
    }
}

if ($img!=null) {
    $imageInfo = pathinfo($img);
    $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
    header ($contentType);
    readfile($img);
} else {
    if ( function_exists('imagecreate') ) {
        header ("Content-type: image/png");
        $im = @imagecreate (100, 100)
            or die ("Cannot initialize new GD image stream");
        $background_color = imagecolorallocate ($im, 255, 255, 255);
        $text_color = imagecolorallocate ($im, 0,0,0);
        imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
        imagepng ($im);
        imagedestroy($im);
    }
}

?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

烧了回忆取暖 2024-08-24 02:44:14

我认为这样做的缺点是新图像会有一个加载期,因此动画可能会有点古怪。该文件有两个部分可能是有益的,其中如果 $_GET 值等于一件事,则返回路径;如果 $_GET 值未设置或等于其他值,则返回图像。这样您就可以预加载一系列图像,并且图像之间会有更流畅的动画。

话虽如此,在我看来,这样的事情应该有效。

$(document).ready(function(){
   function swapImage(){
      var time = new Date();
      $('#image').fadeOut(1000)
       .attr('src', 'http://mydomain.com/images/rotate.php?'+time.getTime())
       .fadeIn(1000);
   }

   var imageInterval = setInterval('swapImage()',10*1000); 
});

时间到了,浏览器就会认为它正在获取新图像。

Spacer.gif

要使用黑色间隔符执行此操作,我建议将图像包装在 div 中,并为该 div 指定 #000 背景颜色以匹配间隔符:

#image-wrap{background-color:#000;}

这将使图像实际上淡入黑色,而不是淡入当前背景颜色,更改为黑色,然后淡入。js 与上面的非常相似:

function swapImage(){
  var time = new Date();
  $('#image').fadeOut(1000)
   .attr('src', 'http://mydomain.com/spacer.gif')
   .attr('src', 'http://mydomain.com/images/rotate.php?'+time.getTime())
   .fadeIn(1000);
}

var imageInterval = setInterval('swapImage()',10*1000); 

将时间保留在那里可能没有必要,但是嘿,这是另一个安全-防止浏览器缓存“图像”。

The downside I see to doing it like this is that there will be a load period for the new image and the animation may be a little quirky because of it. It may be beneficial to have two parts to that file where a path is returned if a $_GET value is equal to one thing, and the image is returned if that $_GET value is not set or it equals something else. That way you could preload a series of images and there would be a smoother animation between images.

Having said that, it seems to me that something like this should work.

$(document).ready(function(){
   function swapImage(){
      var time = new Date();
      $('#image').fadeOut(1000)
       .attr('src', 'http://mydomain.com/images/rotate.php?'+time.getTime())
       .fadeIn(1000);
   }

   var imageInterval = setInterval('swapImage()',10*1000); 
});

The time makes it so the browser think it's getting a new image.

Spacer.gif

To do this with a black spacer, I'd recommend wrapping your image in a div and giving the div a #000 background color to match the spacer:

#image-wrap{background-color:#000;}

It would make it so the image actually faded to black, rather than fading to your current background color, changing to black, and fading back in. The js would be very similar to the above:

function swapImage(){
  var time = new Date();
  $('#image').fadeOut(1000)
   .attr('src', 'http://mydomain.com/spacer.gif')
   .attr('src', 'http://mydomain.com/images/rotate.php?'+time.getTime())
   .fadeIn(1000);
}

var imageInterval = setInterval('swapImage()',10*1000); 

Keeping the time in there probably isn't necessary, but hey, it's another safe-guard against the browser caching the "image".

感情废物 2024-08-24 02:44:14

由于您的 php 脚本返回新图像的源,因此您最好避免使用 load() 并使用简单的 ajax 调用来交换图像的源。

var img=$('#image');//cache the element

function refreshNotification(){
  $.ajax({
    url: 'http://mydomain.com/images/rotate.php',
    success: function(src){
      img.attr({src: src});
    }
  });
}

setInterval(refreshNotification, 10000);

Since your php script is returning the source of the new image, you might be best to avoid using load() and use a simple ajax call that swaps the image's source.

var img=$('#image');//cache the element

function refreshNotification(){
  $.ajax({
    url: 'http://mydomain.com/images/rotate.php',
    success: function(src){
      img.attr({src: src});
    }
  });
}

setInterval(refreshNotification, 10000);
旧人 2024-08-24 02:44:14

假设您的 PHP 脚本只是返回图像的 URL,这样的方法可能会起作用:

$(document).ready(function(){
    window.setInterval(switchImage, 10000);

    function switchImage() {
        var rn = Math.floor(Math.random() * 100000)
        $.get('http://mydomain.com/images/rotate.php', 
              { n: rn }, 
              receiveNewImage);
    }

    function receiveNewImage(src) {
        $('#image').fadeTo(1000, 0.0, function() { switchAndFadeIn(src); } );
    }
    function switchAndFadeIn(newSrc) {
        $('#image').attr('src', newSrc).fadeTo(1000, 1.0);
    }
});

编辑:添加了随机参数。

编辑:在你的PHP中,这样的东西有帮助吗?

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Expires data in the past

Something like this might work, assuming that your PHP script simply returns the URL of the image:

$(document).ready(function(){
    window.setInterval(switchImage, 10000);

    function switchImage() {
        var rn = Math.floor(Math.random() * 100000)
        $.get('http://mydomain.com/images/rotate.php', 
              { n: rn }, 
              receiveNewImage);
    }

    function receiveNewImage(src) {
        $('#image').fadeTo(1000, 0.0, function() { switchAndFadeIn(src); } );
    }
    function switchAndFadeIn(newSrc) {
        $('#image').attr('src', newSrc).fadeTo(1000, 1.0);
    }
});

EDIT: Added random parameter.

EDIT: In your PHP, does something like this help?

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Expires data in the past
季末如歌 2024-08-24 02:44:14

$(document).ready() 块之外定义 swapImage() 函数怎么样?

<script type="text/javascript" scr="path/to/jquery.js"></script>
<script type="text/javascript">
function swapImage(){
    var time = new Date();
    $('#rotate').fadeOut(1000)
     .attr('src', 'rotate.php?'+time.getTime())
     .fadeIn(1000);
}
$(document).ready(function(){
  var imageInterval = setInterval('swapImage()',5000);
});
</script>

<img src="rotate.php" id="rotate" />

How about defining the swapImage() function outside of the $(document).ready() block?

<script type="text/javascript" scr="path/to/jquery.js"></script>
<script type="text/javascript">
function swapImage(){
    var time = new Date();
    $('#rotate').fadeOut(1000)
     .attr('src', 'rotate.php?'+time.getTime())
     .fadeIn(1000);
}
$(document).ready(function(){
  var imageInterval = setInterval('swapImage()',5000);
});
</script>

<img src="rotate.php" id="rotate" />
撩起发的微风 2024-08-24 02:44:14
$("#image").each(function({
$(this).fadeOut(function() { 

$(this).attr("src", "http://mydomain.com/images/image.jpg"); 
$(this).load(function() { $(this).fadeIn(); }); // this should be on the bottom....
}); 
})

检查 JQ 上的每个函数每个

我都有更新了脚本我认为它应该可以工作,因为您正在等待图像加载,但它没有来源......
看看这个>
如果出现错误,则意味着源不存在。顺便说一句,如果您计划使用多个图像,则不应使用#image,因为您的 html 上可能有一个唯一的 id,否则您会遇到冲突,

希望这会有所帮助

$("#image").each(function({
$(this).fadeOut(function() { 

$(this).attr("src", "http://mydomain.com/images/image.jpg"); 
$(this).load(function() { $(this).fadeIn(); }); // this should be on the bottom....
}); 
})

Check each function on JQEach

I have updated the script i think it should work because you are waiting for an image to load, but it doesn't have a source...
check this out > <img onerror="alert('there was an error') />"
if you get the error it means that the source doesn't exist. btw you should not use the #image if you are planning to use multiple images as there can be one unique id on your html otherwise you will get conflicts

hope this helps

携余温的黄昏 2024-08-24 02:44:14

您的设置缺少告诉 jQuery 不要缓存 AJAX 请求的步骤。有一个 'cache' 参数,可以添加到 AJAX 调用中以强制执行它获取一个新副本:

$.ajax({
  url: 'http://mydomain.com/images/rotate.php',
  cache: false,
  success: function(src){
    img.attr({src: src});
  }
});

Your setup is missing the step of telling jQuery not to cache the AJAX request. There's a 'cache' parameter that can be added to an AJAX call to force it to grab a new copy:

$.ajax({
  url: 'http://mydomain.com/images/rotate.php',
  cache: false,
  success: function(src){
    img.attr({src: src});
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文