Frage

Wie geht man vor, um ein Bild in Schwarzweiß in PHP zu konvertieren?

Nicht nur in Graustufen umwandeln, sondern jedes Pixel schwarz oder weiß gemacht?

War es hilfreich?

Lösung

Einfach die Graustufenfarbe zu schwarz oder weiß umrunden.

float gray = (r + g + b) / 3
if(gray > 0x7F) return 0xFF;
return 0x00;

Andere Tipps

Verwenden des PHP gd Bibliothek:

imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -100);

Weitere Beispiele finden Sie in den Benutzern Kommentaren im Link oben.

Sie können sich auf Imagemagick ausgeben, vorausgesetzt, Ihr Host unterstützt es. Welche Funktion möchten Sie verwenden, um zu entscheiden, ob ein Pixel schwarz oder weiß sein sollte?

Wenn Sie dies selbst tun möchten, müssen Sie eine implementieren Dithering -Algorithmus. Aber @Jonni Sagt, wäre es viel einfacher, ein vorhandenes Tool zu verwenden?

$rgb = imagecolorat($original, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8 ) & 0xFF;
        $b = $rgb & 0xFF;

        $gray = $r + $g + $b/3;
        if ($gray >0xFF) {$grey = 0xFFFFFF;}
        else { $grey=0x000000;}

This function work like a charm

    public function ImageToBlackAndWhite($im) {

    for ($x = imagesx($im); $x--;) {
        for ($y = imagesy($im); $y--;) {
            $rgb = imagecolorat($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8 ) & 0xFF;
            $b = $rgb & 0xFF;
            $gray = ($r + $g + $b) / 3;
            if ($gray < 0xFF) {

                imagesetpixel($im, $x, $y, 0xFFFFFF);
            }else
                imagesetpixel($im, $x, $y, 0x000000);
        }
    }

    imagefilter($im, IMG_FILTER_NEGATE);

}

For each pixel you must convert from color to greyscale - something like $grey = $red * 0.299 + $green * 0.587 + $blue * 0.114; (these are NTSC weighting factors; other similar weightings exist. This mimics the eye's varying responsiveness to different colors).

Then you need to decide on a cut-off value - generally half the maximum pixel value, but depending on the image you may prefer a higher value (make the image darker) or lower (make the image brighter).

Just comparing each pixel to the cut-off loses a lot of detail - ie large dark areas go completely black - so to retain more information, you can dither. Basically, start at the top left of the image: for each pixel add the error (the difference between the original value and final assigned value) for the pixels to the left and above before comparing to the cut-off value.

Be aware that doing this in PHP will be very slow - you would be much further ahead to find a library which provides this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top