<?php
namespace App\Classes;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// Imports imagens
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\UploadedFile;
// use File;
use Str;
use Illuminate\Support\Facades\URL;
class ImageUploader extends Controller
{
private $baseUrl = '';
private $storagePath = '';
public function __construct($folder_name = 'documentos')
{
$this->baseUrl = URL::to("/") . '/images/' . $folder_name . '/';
$this->storagePath = public_path() . '/images/' . $folder_name;
}
# actualizar no server
public function imageCompress($image, $newImageName, $imgDefaultRatio)
{
$image = \Image::make(file_get_contents($image));
$image->save($this->storagePath . '/' . $newImageName, $imgDefaultRatio);
}
#actualizar no server
public function imageUpload($image, $newImageName)
{
$image->move($this->storagePath, $newImageName);
}
# actualizar no server
public function generateImageUrl(Request $request, $imageAttr)
{
if ($request->hasFile($imageAttr) && $request->file($imageAttr)->isValid()) {
// Validar imagem
$this->validate(
$request,
[
$imageAttr => 'required|file|mimes:jpeg,jpg,png|max:4096'
],
[
$imageAttr . '.required' =>
[
'messagePT' => 'O campo ' . $imageAttr . ' é Obrigatório',
'messageEN' => 'The ' . $imageAttr . ' must be a file'
],
$imageAttr . '.file' =>
[
'messagePT' => 'O campo ' . $imageAttr . ' é um ficheiro',
'messageEN' => 'The ' . $imageAttr . ' must be a file'
],
$imageAttr . '.mimes' =>
[
'messagePT' => 'Formato de imagem invalido, formatos permitidos jpeg,jpg,png',
'messageEN' => 'Invalid image format, allowed formats jpeg,jpg,png'
],
$imageAttr . '.max' =>
[
'messagePT' => 'O tamanho de imagem permitido somente abaixo de 4 MB',
'messageEN' => 'Image size allowed only below 4MB'
]
]
);
//fazer o upload
$image = $request[$imageAttr];
$newImageName = time() . $image->getClientOriginalName();
//verificar size
$imageSizeMB = round($request->file($imageAttr)->getSize() / (1024 * 1024), 2);
// Diminuir tamanho..
if ($imageSizeMB >= 1) {
$imgDefaultRatio = 65;
if ($imageSizeMB >= 3) {
$imgDefaultRatio = 35;
}
//comprimir e fazer upload
$this->imageCompress($image, $newImageName, $imgDefaultRatio);
} else {
$this->imageUpload($image, $newImageName);
}
return $this->baseUrl . $newImageName;
} else {
$exploded = explode(',', $request[$imageAttr]);
$decoded = base64_decode($exploded[$this->is_string_encoded($request[$imageAttr]) ? 0 : 1], True);
$f = finfo_open();
$mime_type = finfo_buffer($f, $decoded, FILEINFO_MIME_TYPE);
$valiExtension = ['jpeg', 'jpg', 'png'];
$imageExtention = substr($mime_type, 6, strlen($mime_type));
if (!in_array($imageExtention, $valiExtension)) return response()->json(['message' => "Formato de imagem invalido, formatos permitidos jpeg,jpg,png"], 400);
if ($this->getImageSizeMB($decoded) > 4) return response()->json(['message' => "O tamanho de imagem permitido somente abaixo de 4 MB"], 400);
// if (base64_encode($decoded) !== $exploded[$this->is_string_encoded($request[$imageAttr])?0:1]) return response()->json(['message' => 'Imagem invalida.'],400);
//faz o upload temporario no storage - by Rodrigues Mafumo
$tempFileName = $imageAttr . '.jpg';
if (Storage::put($tempFileName, $decoded)) {
$path = storage_path('app/') . $tempFileName;
$tempFile = new \Symfony\Component\HttpFoundation\File\File($path);
$file = UploadedFile::createFromBase(new UploadedFile($tempFile->getPathname(), $tempFile->getFilename(), $tempFile->getMimeType(), null, true));
$newRequest = new Request();
$newRequest->files->set($imageAttr, $file);
return $this->generateImageUrl($newRequest, $imageAttr);
}
}
}
// todo - 15 de April 2025
public function generateImageUrlName(Request $request, $imageAttr)
{
$link = $this->generateImageUrl($request, $imageAttr);
$startpos = strpos($link, 'links/') + 6;
return substr($link, $startpos, strlen($link));
}
#server
private function getImageSizeMB($imagebase64)
{
$size_in_bytes = (int) (strlen(rtrim($imagebase64, '=')) * 1);
$size_in_kb = $size_in_bytes / 1024;
$size_in_mb = round($size_in_kb / 1024, 2);
return $size_in_mb;
}
#server
// Check if there are valid base64 characters
function is_string_encoded($s)
{
return !startsWith("data:image/", $s);
}
public function deleteImageFile($obj, $param, $location)
{
//? Retorna a posicao do documentos
$posicao = strrpos($obj[$param], '/') + 1;
$imageName = substr($obj[$param], $posicao, strlen($obj[$param]));
\File::delete(public_path($location . $imageName));
}
}