Kwinten
Kwinten

Reputation: 71

Compressing image before uploading to Google Cloud in Python

I'm struggling to find a way to reduce an image file's size before uploading it to Google Cloud. I have tried encoding it with Base64, but without success.

The idea is to save storage space. The file is 3 MB and should be smaller. This is the code I currently have (without compressing):

def upload_to_bucket(blob_name, file_path, bucket_name):

    try:
        storage_client = storage.Client()
        bucket = storage_client.get_bucket(bucket_name)
        blob = bucket.blob(blob_name)
        blob.upload_from_filename(file_path)

        print("successfully uploaded {} to {}".format(file_path, bucket_name))
        return True
    except Exception as e:
      print(e)
      return False

upload_to_bucket("QR2", 'QRcode_Scanner\whitecards\WC_QR_Scan.jpg', 'test_storage_whitecards')

If you need any additional information, please ask :)

Upvotes: 0

Views: 933

Answers (1)

David
David

Reputation: 9721

JPEG has compression built in. One side effect of this is that further compression with lossless algorithms (zip etc) is generally not possible.

You're best bet is to use the built-in compression JPEG has more aggressively. You can do this in python using Pillow to read the file and write it again with higher compression before uploading. This will degrade quality, but that is part of the quality/filesize trade-off.

Also FYI base64 is not compression, in fact it increases file sizes. Its goal is to allow sending binary files in ascii-only channels. GCS supports binary objects, so you don't need it.

Upvotes: 4

Related Questions