Pergunta

Eu tenho a imagem como este (é um gráfico):

Gold Trade Graph
(fonte: kitconet.com )

Eu quero mudar as cores, de modo que o branco é preto, a linha do gráfico é azul claro, etc .. é possível alcançar com GD e PHP?

Foi útil?

Solução

Isto irá substituir a cor branca com cinza

$imgname = "test.gif";
$im = imagecreatefromgif ($imgname);

$index = imagecolorclosest ( $im,  255,255,255 ); // get White COlor
imagecolorset($im,$index,92,92,92); // SET NEW COLOR

$imgname = "result.gif";
imagegif($im, $imgname ); // save image as gif
imagedestroy($im);

 enter descrição da imagem aqui

Outras dicas

Eu tive problemas para fazer este trabalho solução. A imagem não pode ser uma verdadeira imagem colorida. Convertê-lo primeiro com imagetruecolortopalette ();

$imgname = "test.gif";
$im = imagecreatefromgif ($imgname);

imagetruecolortopalette($im,false, 255);

$index = imagecolorclosest ( $im,  255,255,255 ); // get White COlor
imagecolorset($im,$index,92,92,92); // SET NEW COLOR

$imgname = "result.gif";
imagegif($im, $imgname ); // save image as gif
imagedestroy($im);

Eu sei que é tarde e após o fato, mas eu coloquei um script que vai fazer isso em uma escala um pouco maior. Esperemos que alguém que vem através deste post pode usá-lo. É preciso uma série de imagens de origem que são camadas de uma cor (sua escolha). Você fornecê-lo com uma cor de fonte e a tonalidade de cada camada e o script retorna uma imagem composta (com total transparência) coloridas especificamente para o seu código hexadecimal fornecido.

Confira o código abaixo. Uma explicação mais detalhada pode ser encontrada no meu blogue .

function hexLighter($hex, $factor = 30) {
    $new_hex = '';

    $base['R'] = hexdec($hex{0}.$hex{1});
    $base['G'] = hexdec($hex{2}.$hex{3});
    $base['B'] = hexdec($hex{4}.$hex{5});

    foreach ($base as $k => $v) {
        $amount = 255 - $v;
        $amount = $amount / 100;
        $amount = round($amount * $factor);
        $new_decimal = $v + $amount;

        $new_hex_component = dechex($new_decimal);

        $new_hex .= sprintf('%02.2s', $new_hex_component);
    }

    return $new_hex;
}

// Sanitize/Validate provided color variable
if (!isset($_GET['color']) || strlen($_GET['color']) != 6) {
    header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request', true, 400);

    exit(0);
}

if (file_exists( "cache/{$_GET['color']}.png" )) {
    header( 'Content-Type: image/png' );
    readfile( "cache/{$_GET['color']}.png" );

    exit(0);
}

// Desired final size of image
$n_width = 50;
$n_height = 50;

// Actual size of source images
$width = 125;
$height = 125;

$image =    imagecreatetruecolor($width, $height);
            imagesavealpha($image, true);
            imagealphablending($image, false);

$n_image =  imagecreatetruecolor($n_width, $n_height);
            imagesavealpha($n_image, true);
            imagealphablending($n_image, false);

$black = imagecolorallocate($image, 0, 0, 0);
$transparent = imagecolorallocatealpha($image, 255, 255, 255, 127);

imagefilledrectangle($image, 0, 0, $width, $height, $transparent);

$layers = array();
$layers_processed = array();

$layers[] = array( 'src' => 'layer01.gif', 'level' => 0 );  // Border
$layers[] = array( 'src' => 'layer02.gif', 'level' => 35 );     // Background
$layers[] = array( 'src' => 'layer03.gif', 'level' => 100 );    // White Quotes

foreach ($layers as $idx => $layer) {
    $img = imagecreatefromgif( $layer['src'] );
    $processed = imagecreatetruecolor($width, $height);

    imagesavealpha($processed, true);
    imagealphablending($processed, false);

    imagefilledrectangle($processed, 0, 0, $width, $height, $transparent);

    $color = hexLighter( $_GET['color'], $layer['level'] );
    $color = imagecolorallocate($image,
        hexdec( $color{0} . $color{1} ),
        hexdec( $color{2} . $color{3} ),
        hexdec( $color{4} . $color{5} )
    );

    for ($x = 0; $x < $width; $x++)
        for ($y = 0; $y < $height; $y++)
            if ($black === imagecolorat($img, $x, $y))
                imagesetpixel($processed, $x, $y, $color);

    imagecolortransparent($processed, $transparent);
    imagealphablending($processed, true);

    array_push($layers_processed, $processed);

    imagedestroy( $img );
}

foreach ($layers_processed as $processed) {
    imagecopymerge($image, $processed, 0, 0, 0, 0, $width, $height, 100);

    imagedestroy( $processed );
}

imagealphablending($image, true);

imagecopyresampled($n_image, $image, 0, 0, 0, 0, $n_width, $n_height, $width, $height);

imagealphablending($n_image, true);

header( 'Content-Type: image/png' );
imagepng( $n_image, "cache/{$_GET['color']}.png" );
imagepng( $n_image );

// Free up memory
imagedestroy( $n_image );
imagedestroy( $image );

Eu não tentei isso sozinho, mas você pode olhar para a função imagecolorset () na biblioteca GD Ele faz um preenchimento de cor como o efeito, que poderia ajudar com o fundo branco.

Você pode tentar a função imagefilter http://lv.php.net/imagefilter - mas que não vai dar o seu acesso directo para substituir uma cor por outra, apenas mudando o r / g / b componentes.

Uma solução nível muito baixo poderia ser implementado utilizando imagesetpixel http://nl2.php.net/imagesetpixel para definir os novos valores de pixel.

IMG_FILTER_NEGATE: inverte todas as cores da imagem.

http://www.php.net/manual/en/function. imagefilter.php

Que poderia ser uma solução?

A abordagem lenta, mas segura, a iteração sobre cada pixel.

function ReplaceColour($img, $r1, $g1, $b1, $r2, $g2, $b2)
{
    if(!imageistruecolor($img))
        imagepalettetotruecolor($img);
    $col1 = (($r1 & 0xFF) << 16) + (($g1 & 0xFF) << 8) + ($b1 & 0xFF);
    $col2 = (($r2 & 0xFF) << 16) + (($g2 & 0xFF) << 8) + ($b2 & 0xFF);

    $width = imagesx($img); 
    $height = imagesy($img);
    for($x=0; $x < $width; $x++)
        for($y=0; $y < $height; $y++)
        {
            $colrgb = imagecolorat($img, $x, $y);
            if($col1 !== $colrgb)
                continue; 
            imagesetpixel ($img, $x , $y , $col2);
        }   
}

Eu não estou ciente de quaisquer funções prontas. Mas eu suponho que você poderia ir trough cada pixel da imagem e alterá-lo de cor ...

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top