PHP 生成最接近真随机数的图像
0 381论如何丧心病狂地用php生成比较接近真随机数的图像,而且不使用mt_rand()
函数
结果图:
使用rand()
:
88kB随机数据时候:
2kB随机数据时候:
看起来基本没什么区别,但是用起来可能就不一样了,毕竟还是和伪随机数差不多,效率还没有mt_rand()
高。
说明:新建一个rand.txt
,然后从random.org里面生成随机数,去掉换行符号和空格符号并导入进去,最后执行脚本即可。也可以试试手打 :)
直接上源码:
<?php
/*
$ct = file_get_contents("rand.txt");
$ct = str_replace(["\r\n"," "], "", $ct);
file_put_contents("rand.txt", $ct);
exit;
*/
header("Content-type: image/png");
$im = imagecreatetruecolor(512, 512) or die("Cannot Initialize new GD image stream");
$white = imagecolorallocate($im, 255, 255, 255);
$ct = file_get_contents("rand.txt");
$ctlen = strlen($ct);
for ($y = 0; $y < 512; $y++) {
for ($x = 0; $x < 512; $x++) {
if (getrand(1) >= 6) {
imagesetpixel($im, $x, $y, $white);
}
}
}
imagepng($im);
imagedestroy($im);
file_put_contents("rand.txt", $ct);
function getrand($maxlen = 10){
global $ct, $ctlen;
$rand = substr($ct, 0, $maxlen);
$time = rand(1, $ctlen);
$cut = substr($ct, strlen($rand));
$cut = substr_replace($cut, $rand, -$time, 0);
$ct = $cut;
return $rand;
}