I made a class to generate thumbs of images:
class Thumbnail {
private static $allowedTypes = [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP];
private $JPEGQuality = 75;
public function makeTumb($src, $dest, $desired_width) {
$aImage = $this->imageCreateFromAny($src);
if (!$aImage) {
return false;
}
$source_image = $aImage['image'];
$type = $aImage['type'];
$width = imagesx($source_image);
$height = imagesy($source_image);
$desired_height = floor($height * ($desired_width / $width));
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
// usando assim funciona
// imagejpeg($virtual_image, $dest);
// usando em uma funçao o imagejpeg($virtual_image, $dest); salva o arquivo, mas quando tento abrir diz que não é um .jpeg válido
$this->imageSave($virtual_image, $dest, $type);
return true;
}
private function imageSave($virtual_image, $dest, $type) {
switch ($type) {
case IMAGETYPE_GIF :
imagegif($virtual_image, $dest);
break;
case IMAGETYPE_JPEG :
imagejpeg($virtual_image, $dest);
case IMAGETYPE_PNG :
imagepng($virtual_image, $dest);
break;
case IMAGETYPE_BMP :
imagewbmp($virtual_image, $dest);
break;
}
}
private function imageCreateFromAny($src) {
$type = exif_imagetype($src);
if (!in_array($type, self::$allowedTypes)) {
return false;
}
switch ($type) {
case IMAGETYPE_GIF :
$rImage = imageCreateFromGif($src);
break;
case IMAGETYPE_JPEG :
$rImage = imageCreateFromJpeg($src);
break;
case IMAGETYPE_PNG :
$rImage = imageCreateFromPng($src);
break;
case IMAGETYPE_BMP :
$rImage = imageCreateFromBmp($src);
break;
}
return ['image' => $rImage, 'type' => $type];
}
}
$oThumb = new Thumbnail();
$src = __DIR__.'/imagem_1.jpg';
$dest = __DIR__.'/thumb/thumb_imagem_1.jpg';
$desired_width = 256;
$oThumb->makeTumb($src, $dest, $desired_width);
But save the image and when I try to open it says it is not a valid image file, unless you use the imagejpeg
function directly.