2012-10-12 169 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對象中發送圖像數據,但我想這具有一些不共享的上下文。