File size: 3,021 Bytes
30944a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import base64
import mimetypes
import os
from urllib.parse import unquote, urlparse

import requests
from file_util import File_Util


class Image_Util:
    """
        Manipulação de imagens
    """
    @staticmethod
    def encode_image_to_base64(image_path: str) -> str:
        """Codifica um arquivo de imagem (frame) para base64."""

        image_path_tratado = File_Util.tratar_arquivo_local(image_path)
        if not image_path_tratado:
            return None
        try:
            with open(image_path_tratado, "rb") as image_file:
                return base64.b64encode(image_file.read()).decode('utf-8')
        except FileNotFoundError:
            print(f"Erro: Arquivo não encontrado em {image_path}")
            return None
        except Exception as e:
            print(f"Erro ao codificar imagem {image_path} para base64: {e}")
            return None

    @staticmethod
    def get_image_extension_from_url(url: str) -> str:
        """
        Retorna a extensão do arquivo de imagem com base na URL informada.

        Args:
            url: URL da imagem (pode conter parâmetros).

        Returns:
            Extensão do arquivo (ex: 'jpg', 'png') ou None se não for possível identificar.
        """

        path = unquote(urlparse(url).path)  # decodifica e extrai o caminho da URL
        filename = os.path.basename(path)

        # Tenta extrair extensão diretamente
        _, ext = os.path.splitext(filename)
        ext = ext.lower().lstrip('.')  # remove o ponto

        # Verifica se a extensão é de imagem conhecida
        if ext in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff']:
            return ext

        # Caso não haja extensão, tenta deduzir pelo tipo MIME
        mime_type, _ = mimetypes.guess_type(url)
        if mime_type and mime_type.startswith("image/"):
            return mime_type.split("/")[1]  # ex: 'image/png' → 'png'

        return None

    @staticmethod
    def download_image_from_url(url: str, output_path: str, image_file_name: str) -> str:
        """
            Baixa uma imagem a partir de uma URL.
            Args:
                url: url da imagem
                output_path: local esperado para gravação da imagem
                image_file_name: nome do arquivo que deve ser utilizado para download
        """
        File_Util.create_or_clear_output_directory(output_path)
        image_path = f'{output_path}/{image_file_name}.{Image_Util.get_image_extension_from_url(url)}'
        response = requests.get(url, stream=True)

        if response.status_code == 200:
            if save_path is None:
                save_path = os.path.basename(url.split("?")[0])  # remove query params, se houver

            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)
            return save_path
        else:
            raise Exception(f"Erro ao baixar imagem: {response.status_code} - {response.reason}")

        return image_path