我有一个条形码的图像,我想将黑色改为任何其他颜色更鲜艳的颜色。我怎么能在PHP中做到这一点?
答案 0 :(得分:6)
如果您的图片是单色的,那么您可以使用imagefilter()
功能:
$image = imagecreatefromjpeg('filename.jpg');
imagefilter($image, IMG_FILTER_COLORIZE, 0, 0, 255); // make it blue!
imagejpeg($image, 'filename.jpg');
答案 1 :(得分: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));