从JSON文件创建图像?

时间:2012-10-12 17:50:17

标签: php json image image-processing

  

可能重复:
  Transform array to png in php

Pixels.JSON

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

从具有X,Y坐标和十六进制代码的JSON文件到基于数据生成图像的最佳方法是什么?

2 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分:0)

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

您的“最佳”选项可能是重新考虑您在JSON对象中发送图像数据的原因,但我想这有一些未共享的上下文。

相关问题