@blog.justoneplanet.info

JavaScript、PHP、MySQLを使ったり

Modernizrにjsを追記して簡単にHTML5やCSS3の対応を確認する

以下を先頭に書く。

javascript:

Modernizrのソースを次にペーストしたら以下のソースを書く。

(function(obj){
	var txt = '';
	for(var i in obj){
		txt += i + ' : ' + obj[i] + '\n';
	}
	alert(txt);
})(window.Modernizr);

そうするとHTML5への対応やCSS3への対応がアラートされる。

Modernizr

頻繁に対応状況が変わるわけでないので無駄な作業な気がした。(´_`。)

■参考

http://www.modernizr.com/

ブラウザから位置情報を取得する

Geolocation APIを利用して取得。実装していないブラウザの為にGoogle Gearsを使用しても取得できる。

■Gears

使う準備をする。以下を書くだけで良い。

<script type="text/javascript" src="http://code.google.com/intl/ja/apis/gears/gears_init.js"></script>

■ソースコード

if(navigator.geolocation) {
	alert('geolocation');
	navigator.geolocation.getCurrentPosition(
		function(position){
			alert(position.coords.latitude + ',' + position.coords.longitude)
		},
		function(error){
			switch(error.code){
				case error.PERMISSION_DENIED :
					alert('Forbidden to use the Geolocation API.');
					break;
				case error.POSITION_UNAVAILABLE :
					alert('Location providers reported an internal error.');
					break;
				case error.TIMEOUT :
					alert('Timeout.');
					break;
				case error.UNKNOWN_ERROR :
				default :
					alert('Failed due to an unknown error.');
					break;
			}
		}
	);
}
else if(typeof google != 'undefined' && typeof google.gears != 'undefined'){
	alert('gears');
	google.gears.factory.create('beta.geolocation').getCurrentPosition(
		function(position){
			alert(position.coords.latitude + ',' + position.coords.longitude)
		},
		function(error){
			alert('error : ' + error.message);
		}
	);
}
else{
	alert('sorry');
}

Chrome LiteはGearsを搭載しているのでandroidでも位置情報が取得できる。

PHPで画像を指定サイズにする

画像のアスペクト比を維持しながら指定のサイズに近づけた後、はみ出した部分を切り落とす感じだ。

$width  = 240;
$height = 320;
$filename = '0008.jpg';
$size = getimagesize($filename);
$image = new Imagick($filename);
$image->setCompressionQuality(30);
if($size[1] < $size[0] * ($height / $width)){
    $image->thumbnailImage(0, $height);
    $imageWidth = (int) (($height / $size[1]) * $size[0]);
    $image->chopImage(($imageWidth - $width) / 2 , 0, 0, 0);
    $image->chopImage(($imageWidth - $width) / 2 , 0, $width, 0);
    $image->chopImage($width , $height, $width, $height);
}
else{
    $image->thumbnailImage($width, 0);
    $imageHeight = (int) (($width / $size[0]) * $size[1]);
    $image->chopImage(0, ($imageHeight - $height) / 2, 0, 0);
    $image->chopImage(0 , ($imageHeight - $height) / 2, 0, $height);
    $image->chopImage($width , $height, $width, $height);
}
$image->writeImage('sample.jpg');

GDとImageMagickを使用。ホントはImageMagickだけで大丈夫なはずなんだが、サイズの取得が上手く出来なくて…

ImageMagickとswftoolsをインストールしよう

■ImageMagick

ImageMagickのインストールだ。

yum install ImageMagick
yum install ImageMagick-devel

今回はPHPから使うので、以下のコマンドを実行する。

pecl install imagick
vi /etc/php.d/imagick.ini

上述のimagick.iniがないはずなので、同じディレクトリのファイルをコピーする。記述内容は以下の1行で良い。

extension=imagick.so

再起動する。

/etc/init.d/httpd restart

これで使えるようになったはずだ。

■swftools

画像ファイルをswfに変換する得体のしれないツールだ。

cd /home/admin
wget http://www.swftools.org/swftools-2009-08-24-2042.tar.gz
tar -xzvf swftools-2009-08-24-2042.tar.gz
./configure
make
make install

美人時計(bijin-tokei)の写真を全部集めよう

巷で話題の美人時計。全ての写真を集める方法をご紹介。

PHPだと以下のようになる。

■bijin.php

tie-upディレクトリがあるので、こちらの方が完璧に集まるはずだ。177人のtie-upも分けて収集可能。

<?php
//美人スクリプト
chdir(dirname(__FILE__));
for($s = 0; $s < 24; $s++){
	for($t = 0; $t < 60; $t++){
		$filename = sprintf('%02d%02d', $s, $t);
		$command = "wget http://www.bijint.com/jp/img/clk/{$filename}.jpg --referer=http://www.bijint.com/jp/";
		system($command, $rv);
		print($command . ':' . $rv . "\n");
	}
}
for($s = 0; $s < 24; $s++){
	for($t = 0; $t < 60; $t++){
		$filename = sprintf('%02d%02d', $s, $t);
		$command = "wget http://www.bijint.com/jp/img/clk/tie-up/{$filename}.jpg --referer=http://www.bijint.com/jp/ -O tie_up_{$filename}.jpg";
		system($command, $rv);
		print($command . ':' . $rv . "\n");
	}
}

PHPを実行できない人もいるだろう。以下のhtmlをブラウザで実行すればキャッシュとして写真がストックされるはずだ。

■bijin.html

JavaScriptを使用してブラウザにキャッシュさせる手法。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>美人時計(bijin-tokei)の写真を全部集める</title>
</head>

<body>
<iframe src="http://www.bijint.com/cache/0000.html" id="iframe" width="900" height="550">
</iframe>
<p id="time"></p>
</body>
<script type="text/javascript">
var hour = 0;
var minute = 0;
if(!!(window.attachEvent && !window.opera)){
    document.getElementById('iframe').onreadystatechange = function(){
        if(this.readyState === 'complete'){
		    chageSrc();
        }
    }
}
else{
    document.getElementById('iframe').onload = function(){
	    chageSrc();
    }
}
function chageSrc(h, m){
    if(minute > 59){
        minute = 0;
        hour++;
    }
    var h = (hour < 10)? ('0' + hour) : hour;
    var m = (minute < 10)? ('0' + minute) : minute;
    if(hour < 24){
        document.getElementById('iframe').src = 'http://www.bijint.com/cache/' + h + '' + m + '.html';
        document.getElementById('time').innerHTML = (h + ':' + m + '<br />');
    }
    minute++;
}
</script>
</html>

ieではiframeのsrcを入れ替えてもonloadイベントが発生しないらしい。

JavaScriptにブロックレベルスコープはない

備忘録。

var str = 'fuga';
function sample(){
    alert(str);//undefined(not 'fuga')
    var str = 'hoge';
    alert(str);//hoge
}

これは以下のように書いたのと同じである。

var str = 'fuga';
function sample(){
    var str;//undefined
    alert(str);//undefined
    str = 'hoge';
    alert(str);//hoge
}

関数内の変数や関数宣言は巻き取りが行われ、その関数の先頭部分で宣言した事になる。従って、変数は関数の先頭で宣言するのが良い。

PHPでデザインパターン:Iterator(イテレータ)

Student.php

class Student
{
    private $name;
    private $age;
    private $sex;
    public function __construct($name, $age, $sex)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getAge()
    {
        return $this->age;
    }
    public function getSex()
    {
        return $this->sex;
    }
}

Students.php

class Students iplements IteratorAggregate
{
    private $students;
    public function __construct()
    {
        $this->students = new ArrayObject();
    }
    public function add(Student $student)
    {
        $this->students[] = $student;
    }
    public function getIterator()
    {
        return $this->students->getIterator();
    }
}

MaleIterator.php

require_once 'Student.php';

class MaleIterator extends FileterIterator
{
    public function __construct($iterator)
    {
        parent::__construct($iterator);
    }
    public function accept()
    {
        $student = $this->current();
        return ($student->getSex() === 'male');
    }
}

■クライアントコード

require_once 'Student.php';
require_once 'Students.php';
require_once 'MaleIterator.php';

$students = new Students();
$students->add(new Student('John', 12, 'male'));
$students->add(new Student('Jack', 13, 'male'));
$students->add(new Student('Emily', 14, 'female'));

$iterator = $students->getIterator();
while($iterator->valid()){
    $student = $iterator->current();
    $list[] = array(
        'name' => $student->getName(),
        'age'  => $student->getAge(),
        'sex'  => $student->getSex()
    );
    $student = $iterator->next();
}
var_dump($list);
/*
array(3) {
  [0]=>
  array(3) {
    ["name"]=>
    string(4) "John"
    ["age"]=>
    int(12)
    ["sex"]=>
    string(4) "male"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(4) "Jack"
    ["age"]=>
    int(13)
    ["sex"]=>
    string(4) "male"
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(5) "Emily"
    ["age"]=>
    int(14)
    ["sex"]=>
    string(6) "female"
  }
}
*/
$iterator = new MaleIterator($iterator);
foreach($iterator as $student){
    $list[] = array(
        'name' => $student->getName(),
        'age'  => $student->getAge(),
        'sex'  => $student->getSex()
    );
}
var_dump($list);
/*
array(2) {
  [0]=>
  array(3) {
    ["name"]=>
    string(4) "John"
    ["age"]=>
    int(12)
    ["sex"]=>
    string(4) "male"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(4) "Jack"
    ["age"]=>
    int(13)
    ["sex"]=>
    string(4) "male"
  }
}
*/

きれいだ。