/** * Do the actual resize/crop/fit/border logic and return the image data. * * @param Transaction $transaction * * @return string */ protected function resize(Transaction $transaction) { $crop = $transaction->getAction() === Action::CROP; $fit = $transaction->getAction() === Action::FIT; $border = $transaction->getAction() === Action::BORDER; try { $img = ImageResource::createFromString($transaction->getSrcImage()->read()); } catch (Exception $e) { return false; } $target = clone $transaction->getTarget(); $original = $img->getDimensions(); $point = new Point(); if ($crop) { $xratio = $original->getWidth() / $target->getWidth(); $yratio = $original->getHeight() / $target->getHeight(); // calculate x or y coordinate and width or height of source if ($xratio > $yratio) { $point->setX(round(($original->getWidth() - $original->getWidth() / $xratio * $yratio) / 2)); $original->setWidth(round($original->getWidth() / $xratio * $yratio)); } elseif ($yratio > $xratio) { $point->setY(round(($original->getHeight() - $original->getHeight() / $yratio * $xratio) / 2)); $original->setHeight(round($original->getHeight() / $yratio * $xratio)); } } elseif (!$border && !$fit) { $ratio = min($target->getWidth() / $original->getWidth(), $target->getHeight() / $original->getHeight()); $target->setWidth($original->getWidth() * $ratio); $target->setHeight($original->getHeight() * $ratio); } $new = ImageResource::createNew($target, $img->getType()); if ($border) { $new->fill($this->background); $tmpheight = $original->getHeight() * ($target->getWidth() / $original->getWidth()); if ($tmpheight > $target->getHeight()) { $target->setWidth($original->getWidth() * ($target->getHeight() / $original->getHeight())); $point->setX(round(($transaction->getTarget()->getWidth() - $target->getWidth()) / 2)); } else { $target->setHeight($tmpheight); $point->setY(round(($transaction->getTarget()->getHeight() - $target->getHeight()) / 2)); } } if (!$crop && !$border) { $img->resample(new Point(), new Point(), $target, $original, $new); } elseif ($border) { $img->resample($point, new Point(), $target, $original, $new); } else { $img->resample(new Point(), $point, $target, $original, $new); } return $img->toString(); }