Transform array to png in php [closed]

拟墨画扇 提交于 2019-12-02 13:06:19

问题


I was wondering how i could transform an array of colors to a png image file. the array is called $pixels. Please help me.

$im = imagecreatefrompng('start.png');
$background = imagecreatefrompng('background.png');
imageconverttruecolor($background);
imageconverttruecolor($im);
define('x',imagesx($im));
define('y',imagesy($im));
$pixels=array();
for ($x = 0; x>$x;++$x){
for ($y=0;y>$y;++$y){
    $s=imagecolorat($background,$x,$y);
    if ($s&&$s==imagecolorat($im,$x,$y))
    $pixels[$x][$y]=0xFFFFFF;
    else $pixels[$x][$y]=0x000000;
}
}

回答1:


You can, but you haven't provided much information on the structure of your array. What I'd recommend using is the following;

Array $arr = (Array($x, $y, $r, $g, $b), Array($x, $y, $r, $g, $b) ...);

So you're looking at a multidimensional array, of which each embedded array is storing;

$x = x position of pixel
$y = y position of pixel
$r = red value (0 - 255)
$g = green value (0 - 255)
$b = blue value (0 - 255)

From here, you can use GD to draw the image. In order to find the correct height and width of the picture, you'll want to define a function to compare the max x and y values, and update them based on the largest x/y values found in the array. i.e;

$max_height = (int) 0;
$max_width = (int) 0;

foreach ($arr as $a)
{
    if ($a[0] > $max_width)
    {
        $max_width = $a[0];
    }
    if ($a[1] > $max_height)
    {
        $max_height = $a[1];
    }
}

So, now you've got the max width and height for your image. From here, we can start constructing the image by running through the multidimensional array - basically, one pixel at a time.

To actually draw the pixel, we're going to use imagesetpixel.

$im = imagecreatetruecolor($width, $height);
foreach ($arr as $b)
{
    $col = imagecolorallocate($im, $a[2], $a[3], $a[4]);
    imagesetpixel ($im , $a[0] , $a[1] , $col );
}

Now, once we've finished, all that's left to do is actually display the image in the browser.

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

Hope this helps.

  • Eoghan


来源:https://stackoverflow.com/questions/11199723/transform-array-to-png-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!