2011-08-08 163 views
3

我得到了一個條形碼圖像,並且我想將黑色更改爲任何其他顏色,這看起來會更豐富多彩。如何在PHP中執行操作?如何使用PHP更改圖像中的顏色

+0

圖像格式是什麼?它有半色調嗎? – zerkms

+0

不知道這是不是相同的問題,但答案可能會幫助你弄明白:http://stackoverflow.com/questions/1548534/php-replace-colour-within-image – aevanko

+0

常見的格式是jpeg.If其他人,我認爲它可以改變爲jpeg.Thanks你的答案如此之快! – johnvip

回答

6

如果圖像是單色的,那麼你可以使用imagefilter()功能:

<?php 
$image = imagecreatefromjpeg('filename.jpg'); 

imagefilter($image, IMG_FILTER_COLORIZE, 0, 0, 255); // make it blue! 

imagejpeg($image, 'filename.jpg'); 
+0

偉大的解決方案。我還建議使用gif或png作爲條形碼,因爲jpg可能會有可能導致代碼無法掃描的工件。也請確保您測試條碼,因爲您使用的顏色可能未在所有掃描儀上註冊。條形碼通常是黑白色的,因爲它具有高對比度(並且便宜) – bumperbox

5

結合本網站代碼,並加入少許的我自己,我已經想通了。請享用。

function updateThumb($image, $newColor) { 
    $img = imagecreatefrompng($image); 

    $w = imagesx($img); 
    $h = imagesy($img); 

    // Work through pixels 
    for($y=0;$y<$h;$y++) { 
     for($x=0;$x<$w;$x++) { 
      // Apply new color + Alpha 
      $rgb = imagecolorsforindex($img, imagecolorat($img, $x, $y)); 

      $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127); 
      imagesetpixel($img, $x, $y, $transparent); 


      // Here, you would make your color transformation. 
      $red_set=$newColor[0]/100*$rgb['red']; 
      $green_set=$newColor[1]/100*$rgb['green']; 
      $blue_set=$newColor[2]/100*$rgb['blue']; 
      if($red_set>255)$red_set=255; 
      if($green_set>255)$green_set=255; 
      if($blue_set>255)$blue_set=255; 

      $pixelColor = imagecolorallocatealpha($img, $red_set, $green_set, $blue_set, $rgb['alpha']); 
      imagesetpixel ($img, $x, $y, $pixelColor); 
     } 
    } 

    // Restore Alpha 
    imageAlphaBlending($img, true); 
    imageSaveAlpha($img, true); 

    return $img; 
} 

function makeThumb($path, $top, $bottom=FALSE) { 
    $width = imagesx($top); 
    $height = imagesy($top); 

    $thumbHeight = $bottom != FALSE ? $height * 2 : $height; 

    // Create Transparent PNG 
    $thumb = imagecreatetruecolor($width, $thumbHeight); 
    $transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127); 
    imagefill($thumb, 0, 0, $transparent); 

    // Copy Top Image 
    imagecopy($thumb, $top, 0, 0, 0, 0, $width, $height); 

    // Copy Bottom Image 
    if ($bottom != FALSE) { 
     imagecopy($thumb, $bottom, 0, $height, 0, 0, $width, $height); 
    } 

    // Save Image with Alpha 
    imageAlphaBlending($thumb, true); 
    imageSaveAlpha($thumb, true); 
    header('Content-Type: image/png'); 
    imagepng($thumb, $path); // save image as png 

} 

$thumbTop = updateThumb('input/path', array(240,105,15));