Diese Woche am beliebtesten

Vertiefendes Material

Bildbearbeitung in PHP

Dieses Codeschnipsel Tutorial zeigt, wie ihr mit PHP Bilder nachträglich bearbeiten könnt. Mit unserer modernen Dreamcodes Image Bibliothek lassen sich Rauschen hinzufügen und entfernen, Graustufen erzeugen, Farben anpassen und Bilder skalieren. Ideal für Entwickler, die die Bildverarbeitung direkt in PHP nutzen möchten.

Die Bibliothek ist modular aufgebaut, sodass ihr verschiedene Algorithmen nutzen könnt:

  • Salt & Pepper: Fügt Schwarz-Weiß-Rauschen hinzu (ideal zum Testen anderer Filter)
  • Median: Entfernt Rauschen effektiv
  • MeanValue / WeightedMeanValue: Mittelwertfilter, gewichtet oder ungefiltert
  • GrayScale / GammaCorrect / Colorize: Farbtransformationen
  • Scale: Bildgröße ändern

Speichere das Script ab und und rufe Sie via http://www.deine-seite.Endung/deinname.php?file=test.jpg auf.

<?php
require 'Dreamcodes_ImageLibrary.php';
set_time_limit(0);
if (empty($_GET['file'])) {
    die("Bitte eine JPG-Datei angeben");
}
$filename = $_GET['file'];
if (!file_exists($filename)) {
    die("Datei nicht gefunden: $filename");
}
$info = getimagesize($filename);
if ($info === false || $info[2] !== IMAGETYPE_JPEG) {
    die("Bitte eine gültige JPG-Datei angeben.");
}
$image = imagecreatefromjpeg($filename);
$imgLib = new ImageLibrary($image);
$imgLib->Transformation->scale(200, 200);
$imgLib->NoiseReduction->saltAndPepper();
$imgLib->NoiseReduction->weightedMeanValue();
$imgLib->ColorTransformation->grayScale();

// Bild ausgeben
$imgLib->dump();
?>

Dann speicherst du auch die Bibliothek als Dreamcodes_ImageLibrary.php ab:

<?php

declare(strict_types=1);

class ImageLibrary
{
    public \GdImage $image;
    public int $width;
    public int $height;

    public NoiseReduction $NoiseReduction;
    public ColorTransformation $ColorTransformation;
    public Transformation $Transformation;

    public function __construct(\GdImage $image)
    {
        $this->setImage($image);

        $this->NoiseReduction = new NoiseReduction($this->image);
        $this->ColorTransformation = new ColorTransformation($this->image);
        $this->Transformation = new Transformation($this->image);
    }

    public function setImage(\GdImage $image): void
    {
        $this->image = $image;
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
    }

    public function dump(): void
    {
        header('Content-Type: image/png');
        imagepng($this->image);
    }
}

class NoiseReduction
{
    private \GdImage $image;
    private int $width;
    private int $height;

    public function __construct(\GdImage $image)
    {
        $this->setImage($image);
    }

    public function setImage(\GdImage $image): void
    {
        $this->image = $image;
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
    }

    public function saltAndPepper(int $frequency = 5, int $intensity = 100): void
    {
        $freq = pow($frequency / 100, 2) * 100;

        for ($x = 0; $x < $this->width; $x++) {
            for ($y = 0; $y < $this->height; $y++) {
                if ($freq > random_int(0, 100)) {
                    $colorIndex = imagecolorat($this->image, $x, $y);
                    $rgba = imagecolorsforindex($this->image, $colorIndex);

                    $add = random_int(intval($intensity * -2.55), intval($intensity * 2.55));
                    $r = max(0, min(255, $rgba['red'] + $add));
                    $g = max(0, min(255, $rgba['green'] + $add));
                    $b = max(0, min(255, $rgba['blue'] + $add));

                    $color = imagecolorresolve($this->image, $r, $g, $b);
                    imagesetpixel($this->image, $x, $y, $color);
                }
            }
        }
    }

    public function median(int $size = 3): void
    {
        $half = (int)(($size - 1) / 2);
        $newImage = imagecreatetruecolor($this->width, $this->height);

        for ($x = 0; $x < $this->width; $x++) {
            for ($y = 0; $y < $this->height; $y++) {
                $pixels = [];
                for ($i = max(0, $x - $half); $i < min($this->width, $x + $half + 1); $i++) {
                    for ($j = max(0, $y - $half); $j < min($this->height, $y + $half + 1); $j++) {
                        $color = imagecolorsforindex($this->image, imagecolorat($this->image, $i, $j));
                        $pixels[] = ($color['red'] + $color['green'] + $color['blue']) / 3;
                    }
                }
                sort($pixels, SORT_NUMERIC);
                $gray = $pixels[(int)floor(count($pixels) / 2)];
                $color = imagecolorresolve($newImage, (int)$gray, (int)$gray, (int)$gray);
                imagesetpixel($newImage, $x, $y, $color);
            }
        }

        $this->image = $newImage;
    }

    public function meanValue(int $size = 3): void
    {
        $half = (int)(($size - 1) / 2);
        $newImage = imagecreatetruecolor($this->width, $this->height);

        for ($x = 0; $x < $this->width; $x++) {
            for ($y = 0; $y < $this->height; $y++) {
                $r = $g = $b = 0;
                $count = 0;

                for ($i = max(0, $x - $half); $i < min($this->width, $x + $half + 1); $i++) {
                    for ($j = max(0, $y - $half); $j < min($this->height, $y + $half + 1); $j++) {
                        $color = imagecolorsforindex($this->image, imagecolorat($this->image, $i, $j));
                        $r += $color['red'];
                        $g += $color['green'];
                        $b += $color['blue'];
                        $count++;
                    }
                }

                $color = imagecolorresolve($newImage, (int)round($r / $count), (int)round($g / $count), (int)round($b / $count));
                imagesetpixel($newImage, $x, $y, $color);
            }
        }

        $this->image = $newImage;
    }

    public function weightedMeanValue(): void
    {
        $newImage = imagecreatetruecolor($this->width, $this->height);

        for ($x = 0; $x < $this->width; $x++) {
            for ($y = 0; $y < $this->height; $y++) {
                $r = $g = $b = $c = 0;
                for ($i = max(0, $x - 1); $i < min($this->width, $x + 2); $i++) {
                    for ($j = max(0, $y - 1); $j < min($this->height, $y + 2); $j++) {
                        $color = imagecolorsforindex($this->image, imagecolorat($this->image, $i, $j));
                        $weight = match(abs($i - $x) + abs($j - $y)) {
                            0 => 4,
                            1 => 2,
                            2 => 1,
                            default => 0
                        };
                        $r += $color['red'] * $weight;
                        $g += $color['green'] * $weight;
                        $b += $color['blue'] * $weight;
                        $c += $weight;
                    }
                }

                $color = imagecolorresolve($newImage, (int)round($r / $c), (int)round($g / $c), (int)round($b / $c));
                imagesetpixel($newImage, $x, $y, $color);
            }
        }

        $this->image = $newImage;
    }
}

class ColorTransformation
{
    private \GdImage $image;
    private int $width;
    private int $height;

    public function __construct(\GdImage $image)
    {
        $this->setImage($image);
    }

    public function setImage(\GdImage $image): void
    {
        $this->image = $image;
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
    }

    public function grayScale(float $rWeight = 0.4, float $gWeight = 0.35, float $bWeight = 0.25): void
    {
        for ($x = 0; $x < $this->width; $x++) {
            for ($y = 0; $y < $this->height; $y++) {
                $color = imagecolorsforindex($this->image, imagecolorat($this->image, $x, $y));
                $gray = max(0, min(255, (int)round($color['red'] * $rWeight + $color['green'] * $gWeight + $color['blue'] * $bWeight)));
                $newColor = imagecolorresolve($this->image, $gray, $gray, $gray);
                imagesetpixel($this->image, $x, $y, $newColor);
            }
        }
    }

    public function gammaCorrect(float $gamma): void
    {
        imagegammacorrect($this->image, 1.0, $gamma);
    }

    public function colorize(float $rFactor = 1.0, float $gFactor = 1.0, float $bFactor = 1.0): void
    {
        for ($x = 0; $x < $this->width; $x++) {
            for ($y = 0; $y < $this->height; $y++) {
                $color = imagecolorsforindex($this->image, imagecolorat($this->image, $x, $y));
                $r = max(0, min(255, (int)round($color['red'] * $rFactor)));
                $g = max(0, min(255, (int)round($color['green'] * $gFactor)));
                $b = max(0, min(255, (int)round($color['blue'] * $bFactor)));
                $newColor = imagecolorresolve($this->image, $r, $g, $b);
                imagesetpixel($this->image, $x, $y, $newColor);
            }
        }
    }
}

class Transformation
{
    private \GdImage $image;
    private int $width;
    private int $height;

    public function __construct(\GdImage $image)
    {
        $this->setImage($image);
    }

    public function setImage(\GdImage $image): void
    {
        $this->image = $image;
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
    }

    public function scale(int $maxWidth, int $maxHeight): void
    {
        $ratio = min($maxWidth / $this->width, $maxHeight / $this->height);
        $newWidth = (int)($this->width * $ratio);
        $newHeight = (int)($this->height * $ratio);

        $newImage = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $newWidth, $newHeight, $this->width, $this->height);

        $this->image = $newImage;
        $this->width = $newWidth;
        $this->height = $newHeight;
    }
}
Dreamcodes Redaktion
Dreamcodes Redaktion
Jeder Inhalt auf Dreamcodes entsteht mit einem klaren Anspruch: geprüfte Praxis statt schneller Theorie. Was hier veröffentlicht wird, basiert auf Best Practices, echten Projekterfahrungen und technischem Verständnis, das über das Offensichtliche hinausgeht. Unser Ziel ist ein Fundament, auf dem du aufbauen kannst, nicht eines, das beim ersten produktiven Einsatz bricht. Wie du die Inhalte integrierst, absicherst und in deinen Kontext überträgst, liegt bei dir. Die fachliche Grundlage liefern wir, die Verantwortung für den Einsatz bleibt deine.
Vorheriges Tutorial
Nächstes Tutorial

Vielleicht einen Blick WERT?