通过php将“0”和“1”的字符串转换为图像

时间:2017-05-22 07:34:11

标签: php

PHP转换标准输入1和0来设置我选择的特定像素颜色。

每个位表示一个像素,\n表示新行。

示例: 对于此给定字符串 1010\n0101\n1010\n0101\n1010\图像看起来像棋盘。

1 个答案:

答案 0 :(得分:1)

这是我的示例代码,希望这可以帮助你^^

<?php
$size = 50; /*the square size*/
$map = "0101\n1010\n0101\n1010"; /*your image map*/


$totalRow = 0;
$totalCol = 0;

$rows = explode("\n", $map); /* split map by '\n' as the requirement stated*/
$totalRow = count($rows); /* get total row */

/**
 * Convert map to array make it loopable
 */
$map = [];
foreach ($rows as $row)
{

    $cols = str_split($row); /* use str_split to split each characters */
    $totalCol = $totalCol < count($cols) ? count($cols) : $totalCol; /* get biggest cols user to calculate image width*/

    $map[] = $cols; /* push to map*/

}

/**
 * Create image
 */
$width = $size * $totalCol; /* width = size * biggest cols*/
$height = $size * $totalRow; /* height = size * total rows*/
$im = imagecreatetruecolor($width, $height); /* create image */

/**
 * Colors
 */
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

/**
 * Build square
 */
$x = 0; /* x pointer*/
$y = 0; /* y pointer*/

foreach ($map as $mapRow) /* rows loop*/
{
    foreach ($mapRow as $square) /* cols loop */
    {
        $color = $square == 1 ? $black : $white; /* black if the code is '1'*/

        // create square
        imagefilledrectangle($im, $x, $y, $x + $size, $y + $size, $color);

        $x += $size; /* increase x pointer*/
    }

    $x = 0;  /* reset x pointer */
    $y += $size; /* increase y pointer*/
}

/* png header */
header('Content-Type: image/png');

/* show image */
imagepng($im);
imagedestroy($im);
?>