Skip to content

Commit

Permalink
Conversor nativo de thumbnails para Google WebP
Browse files Browse the repository at this point in the history
  • Loading branch information
robsonvleite committed Jun 23, 2020
1 parent e118a06 commit 7adf471
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 28 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@

Cropper é um componente que simplifica a criação de miniaturas de imagens JPG e PNG com um motor de cache. O Cropper CC cria versões de suas imagens para cada dimensão necessária na aplicação com zero de complexidade.

####WEBP THUMBNAILS:

Published in version 1.3.* by default how thumbnails are converted to webP.

Adicionado na versão 1.3.* por padrão as miniaturas são convertidas para webP.

## About CoffeeCode

###### CoffeeCode is a set of small and optimized PHP components for common tasks. Held by Robson V. Leite and the UpInside team. With them you perform routine tasks with fewer lines, writing less and doing much more.
Expand All @@ -32,7 +38,7 @@ CoffeeCode é um conjunto de pequenos e otimizados componentes PHP para tarefas
Cropper is available via Composer:

```bash
"coffeecode/cropper": "1.2.*"
"coffeecode/cropper": "1.3.*"
```

or run
Expand Down
9 changes: 7 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
"Upload",
"image thumb",
"image crop",
"image cache"
"image cache",
"thumbnails jpg",
"thumbnails png",
"thumbnails webp",
"webp converter"
],
"homepage": "http://www.upinside.com.br",
"license": "MIT",
Expand All @@ -21,7 +25,8 @@
"php": "^7.2",
"ext-gd": "*",
"ext-mbstring": "*",
"ext-fileinfo": "*"
"ext-fileinfo": "*",
"rosell-dk/webp-convert": "2.3.2"
},
"autoload": {
"psr-4": {
Expand Down
4 changes: 2 additions & 2 deletions example/thumb.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

require "../vendor/autoload.php";

$thumb = new \CoffeeCode\Cropper\Cropper("cache");
$thumb->flush();
$thumb = new \CoffeeCode\Cropper\Cropper("cache", 75, 5, true);
//$thumb->flush();

echo "<p><img src='{$thumb->make("images/image.jpg", 200)}' alt='Happy Coffe' title='Happy Coffe'></p>";
echo "<p><img src='{$thumb->make("images/image.jpg", 400)}' alt='Happy Coffe' title='Happy Coffe'></p>";
Expand Down
80 changes: 57 additions & 23 deletions src/Cropper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

namespace CoffeeCode\Cropper;

use Exception;
use WebPConvert\Convert\Exceptions\ConversionFailedException;
use WebPConvert\WebPConvert;

/**
* Class CoffeeCode Cropper
*
Expand All @@ -13,12 +17,6 @@ class Cropper
/** @var string */
private $cachePath;

/** @var int */
private $jpgSize;

/** @var int */
private $pngSize;

/** @var string */
private $imagePath;

Expand All @@ -28,9 +26,17 @@ class Cropper
/** @var string */
private $imageMime;

/** @var int */
private $quality;

/** @var int */
private $compressor;

/**@var bool */
private $webP;

/**
* Allow jpg and png to thumb and cache generate
*
* @var array allowed media types
*/
private static $allowedExt = ['image/jpeg', "image/png"];
Expand All @@ -39,19 +45,21 @@ class Cropper
* Cropper constructor.
*
* @param string $cachePath
* @param int $jpgQuality
* @param int $pngCompressor
* @throws \Exception
* @param int $quality
* @param int $compressor
* @param bool $webP
* @throws Exception
*/
public function __construct(string $cachePath, int $jpgQuality = 75, int $pngCompressor = 5)
public function __construct(string $cachePath, int $quality = 75, int $compressor = 5, bool $webP = true)
{
$this->cachePath = $cachePath;
$this->jpgSize = $jpgQuality;
$this->pngSize = $pngCompressor;
$this->quality = $quality;
$this->compressor = $compressor;
$this->webP = $webP;

if (!file_exists($this->cachePath) || !is_dir($this->cachePath)) {
if (!mkdir($this->cachePath, 0755, true)) {
throw new \Exception("Could not create cache folder");
throw new Exception("Could not create cache folder");
}
}
}
Expand All @@ -71,16 +79,23 @@ public function make(string $imagePath, int $width, int $height = null): ?string
}

$this->imagePath = $imagePath;
$this->imageName = $this->name($this->imagePath, $width, $height);
$this->imageMime = mime_content_type($this->imagePath);
$this->imageInfo = pathinfo($this->imagePath);

if (!in_array($this->imageMime, self::$allowedExt)) {
return "Not a valid JPG or PNG image";
}

$this->imageName = $this->name($this->imagePath, $width, $height);
if (file_exists("{$this->cachePath}/{$this->imageName}") && is_file("{$this->cachePath}/{$this->imageName}")) {
return "{$this->cachePath}/{$this->imageName}";
$imageWebP = "{$this->cachePath}/{$this->imageName}.webp";
$imageExt = "{$this->cachePath}/{$this->imageName}.{$this->imageInfo['extension']}";

if ($this->webP && file_exists($imageWebP) && is_file($imageWebP)) {
return $imageWebP;
}

if (file_exists($imageExt) && is_file($imageExt)) {
return $imageExt;
}

return $this->imageCache($width, $height);
Expand All @@ -99,11 +114,10 @@ protected function name(string $name, int $width = null, int $height = null): st
$name = str_replace(["-----", "----", "---", "--"], "-", str_replace(" ", "-", $trimName));

$hash = $this->hash($this->imagePath);
$ext = ($this->imageMime == "image/jpeg" ? ".jpg" : ".png");
$widthName = ($width ? "-{$width}" : "");
$heightName = ($height ? "x{$height}" : "");

return "{$name}{$widthName}{$heightName}-{$hash}{$ext}";
return "{$name}{$widthName}{$heightName}-{$hash}";
}

/**
Expand Down Expand Up @@ -199,12 +213,16 @@ private function fromJpg(int $width, int $height, int $src_x, int $src_y, int $s
$source = imagecreatefromjpeg($this->imagePath);

imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
imagejpeg($thumb, "{$this->cachePath}/{$this->imageName}", $this->jpgSize);
imagejpeg($thumb, "{$this->cachePath}/{$this->imageName}.jpg", $this->quality);

imagedestroy($thumb);
imagedestroy($source);

return "{$this->cachePath}/{$this->imageName}";
if ($this->webP) {
return $this->toWebP("{$this->cachePath}/{$this->imageName}.jpg");
}

return "{$this->cachePath}/{$this->imageName}.jpg";
}

/**
Expand All @@ -224,11 +242,27 @@ private function fromPng(int $width, int $height, int $src_x, int $src_y, int $s
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
imagepng($thumb, "{$this->cachePath}/{$this->imageName}", $this->pngSize);
imagepng($thumb, "{$this->cachePath}/{$this->imageName}.png", $this->compressor);

imagedestroy($thumb);
imagedestroy($source);

return "{$this->cachePath}/{$this->imageName}";
if ($this->webP) {
return $this->toWebP("{$this->cachePath}/{$this->imageName}.png");
}

return "{$this->cachePath}/{$this->imageName}.png";
}

public function toWebP($image): string
{
$webPConverted = pathinfo($image)["dirname"] . "/" . pathinfo($image)["filename"] . ".webp";
try {
WebPConvert::convert($image, $webPConverted, ["default-quality" => $this->quality]);
unlink($image);
return $webPConverted;
} catch (ConversionFailedException $exception) {
return $image;
}
}
}

1 comment on commit 7adf471

@wilderamorim
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O Whallysson da tribo tem um componente para converter em WebP também: https://packagist.org/packages/codeblog/conveter-php-webp
Talvez seja interessante estuda-lo.

Please sign in to comment.