Node.js/PHP获取Bing每日壁纸

Github:https://github.com/mcc108/bing-wallpaper

Node.js

bing.js

var http = require('http');  
http.createServer(function(req, response) {  
    var today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);
    var tomorrow = new Date();
    tomorrow.setTime(today.getTime()+(24*3600*1000));
    response.writeHead(200, {
        'Expires': tomorrow.toUTCString(),
        'Cache-Control': 'public, max-age=3600',
        'Last-Modified': today.toUTCString(),
        'Content-Type': 'image/jpeg'
    });
    http.get('http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1', function(bing_res){
        var bing_body = [], bing_data = {};
        bing_res.on('data', function(chunk){
            bing_body.push(chunk);
        });
        bing_res.on('end', function(){
            bing_body = Buffer.concat(bing_body);
            bing_data = JSON.parse(bing_body.toString());
            http.get(bing_data.images[0].url, function(img_res){
                var img_body = [];
                img_res.on('data', function(chunk){
                    img_body.push(chunk);
                });
                img_res.on('end', function(){
                    img_body = Buffer.concat(img_body);
                    response.write(img_body, 'binary');
                    response.end();
                });
            });
        });
    });
}).listen(8129);
$ node bing.js

PHP

bing.php

<?php  
    $str = file_get_contents('http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1');
    $data = json_decode($str);
    $imgurl = $data -> {"images"}[0] -> {"url"};
    if($imgurl){
        $img = imagecreatefromjpeg($imgurl);
        header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime(date('Y-m-d', strtotime('+1 day')))) . ' GMT'); 
        header('Cache-Control: public, max-age=3600');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', strtotime(date('Y-m-d'))) . ' GMT'); 
        header('Content-Type: image/jpeg');
        imageinterlace($img, 1);
        imagejpeg($img);
        imagedestroy($img);
        exit();
    }else{
        exit('error');
    }
?>

利用NodeJS/PHP就可以获取每日更新的Bing壁纸来作网页背景啦:

以上都是bing每日壁纸做背景的例子的,网页瞬间变得高端起来。


更新记录:

  • 新增Node.js版本(2016.9.28)
  • 修改Bing官方xml API到json API(2016.4.12)
  • 新增http缓存机制(2016.4.6)
  • PHP版本使用imageinterlace处理图片(2015.11.25)