2012-10-12 123 views
1

可能重复:
Transform array to png in php从JSON文件创建一个图像?

Pixels.JSON

{ 
    "274:130":"000", 
    "274:129":"000", 
    "274:128":"000", 
    "274:127":"000", 
    "274:126":"000", 
    "274:125":"000", 
} 

什么是从X一个JSON文件,以最好的一段路要走,Y坐标和十六进制代码根据数据生成图像?

+0

解码它,使用循环,[图像函数](http://php.net/gd),拆分十六进制数字,然后绘制像素或线条。 – mario

回答

2

现在缺少这里是heightwidth,但如果你能得到那么你可以使用imagesetpixel生成从像素

图像例

$pixels = '{ 
     "274:130":"000", 
     "274:129":"000", 
     "274:128":"000", 
     "274:127":"000", 
     "274:126":"000", 
     "274:125":"000" 
    }'; 

$list = json_decode($pixels, true); 

//#GENERATE MORE DATA 
for($i = 0; $i < 10000; $i ++) { 
    $list[mt_rand(1, 300) . ":" . mt_rand(1, 300)] = random_hex_color(); 
} 

$h = 300; 
$w = 300; 

$gd = imagecreatetruecolor($h, $w); 
// ImageFillToBorder($gd, 0, 0, 0, 255); 

foreach ($list as $xy => $color) { 
    list($r, $g, $b) = html2rgb($color); 
    list($x, $y) = explode(":", $xy); 
    $color = imagecolorallocate($gd, $r, $g, $b); 
    imagesetpixel($gd, $x, $y, $color); 
} 

header('Content-Type: image/png'); 
imagepng($gd); 

样本输出

enter image description here

使用的功能

function html2rgb($color) { 
    if ($color[0] == '#') 
     $color = substr($color, 1); 
    if (strlen($color) == 6) 
     list($r, $g, $b) = array($color[0] . $color[1],$color[2] . $color[3],$color[4] . $color[5]); 
    elseif (strlen($color) == 3) 
     list($r, $g, $b) = array($color[0] . $color[0],$color[1] . $color[1],$color[2] . $color[2]); 
    else 
     return false; 
    return array(hexdec($r),hexdec($g),hexdec($b)); 
} 

function random_hex_color(){ 
    return sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); 
} 
0

假设你是指在客户端网页/浏览器中:你可以创建一个HTML5画布并根据你的JSON数据直接绘制到它上面;我想它会很慢,但它会起作用。

您的'最佳'选项可能是重新考虑您为什么要在JSON对象中发送图像数据,但我想这具有一些不共享的上下文。