File size: 3,105 Bytes
ad3aed5
 
 
 
 
 
f1dd29d
 
 
 
 
 
 
 
ad3aed5
 
 
 
 
 
 
 
f1dd29d
 
 
ad3aed5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from google.cloud import storage
from PIL import Image
import os
import uuid
import tempfile

def get_credentials():
    credentials_json_string = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")

    # create a temp file with the credentials
    with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as temp_file:
        temp_file.write(credentials_json_string)
        temp_file_path = temp_file.name
    return temp_file_path

class GoogleCloudImageUploadService:
    BUCKET_NAME = "picchat-assets"
    MAX_DIMENSION = 1024

    def __init__(self):
        # Using API key here as per your original code. Note that for production,
        # service account credentials are generally recommended.
        # get credentials from env
        credentials_json = get_credentials()
        self.storage_client = storage.Client.from_service_account_json(credentials_json)

    def upload_image_to_gcs(self, source_file_name):
        """
        Uploads an image to the specified Google Cloud Storage bucket.
        Supports both JPEG and PNG formats.
        """
        try:
            bucket = self.storage_client.bucket(self.BUCKET_NAME)
            blob_name = str(uuid.uuid4())
            blob = bucket.blob(blob_name)

            # Open and optionally resize the image, then save to a temporary file.
            with Image.open(source_file_name) as image:
                # Determine the original format. If it's not JPEG or PNG, default to JPEG.
                original_format = image.format.upper() if image.format in ['JPEG', 'PNG'] else "JPEG"

                # Resize if needed.
                if image.width > self.MAX_DIMENSION or image.height > self.MAX_DIMENSION:
                    image.thumbnail((self.MAX_DIMENSION, self.MAX_DIMENSION))
                
                # Choose the file extension based on the image format.
                suffix = ".jpg" if original_format == "JPEG" else ".png"
                
                # Create a temporary file with the appropriate suffix.
                with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
                    temp_filename = temp_file.name
                    image.save(temp_filename, format=original_format)

            try:
                # Set content type based on the image format.
                content_type = "image/jpeg" if original_format == "JPEG" else "image/png"
                blob.upload_from_filename(temp_filename, content_type=content_type)
                blob.make_public()
            finally:
                # Remove the temporary file.
                os.remove(temp_filename)

            print(f"File {source_file_name} uploaded to {blob_name} in bucket {self.BUCKET_NAME}.")
            return blob.public_url
        except Exception as e:
            print(f"An error occurred: {e}")
            return None

if __name__ == "__main__":
    image = "./assets/lakeview.jpg"  # Replace with your JPEG or PNG image path.
    upload_service = GoogleCloudImageUploadService()
    url = upload_service.upload_image_to_gcs(image)
    print(url)