claviska / SimpleImage

A PHP class that makes working with images and GD as simple as possible.
MIT License
1.38k stars 382 forks source link

Antialias support for line, ellipse, polygon, etc. #160

Open claviska opened 7 years ago

claviska commented 7 years ago

I'd love to add antialiasing to all drawing methods. The imageantialias method states it works for lines and ellipses, but it doesn't support alpha components.

I would prefer a solution that works for all shapes, although it may not be possible without writing our own shape methods (prefer not to do). This may simply be a limitation of GD.

claviska commented 7 years ago

Some interesting approaches are mentioned here, particularly the zoom trick.

claviska commented 7 years ago

I experimented with the zoom trick and the line method today. The results were good, but extremely slow and memory intensive. Here's a sample for anyone who wants to play with it:

  public function line($x1, $y1, $x2, $y2, $color, $thickness = 1) {
    // Create a new image $zoom times the original's size
    $zoom = 4;
    $new = new SimpleImage();
    $new->fromNew($this->getWidth() * $zoom, $this->getHeight() * $zoom, 'transparent');
    $color = $new->allocateColor($color);

    // Set thickness
    imagesetthickness($new->image, $thickness * $zoom);
    imageline($new->image, $x1 * $zoom, $y1 * $zoom, $x2 * $zoom, $y2 * $zoom, $color);

    // Now scale it down and lay it on top of the original to produce an antialias effect
    $new->resize($this->getWidth(), $this->getHeight());
    $this->overlay($new);
    $new->__destruct();

    return $this;
  }

You can change $zoom. 1 = no zoom, 2 = 2x zoom, etc. Here's what 1 - 4 look like (download to see full size image):

zoom-trick

Given the slow speed and memory usage, I don't think the zoom trick will be a good candidate for supporting antialiasing. 😭