首页 > 解决方案 > 在 Python 中上传到 Google Cloud 之前压缩图像

问题描述

在将图像文件上传到 Google Cloud 之前,我正在努力寻找一种减小图像文件大小的方法。我曾尝试使用 Base64 对其进行编码,但没有成功。

这个想法是为了节省存储空间。该文件为 3 MB,应该更小。这是我目前拥有的代码(未压缩):

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')

如果您需要任何其他信息,请询问:)

标签: pythongoogle-cloud-storageimage-compression

解决方案


JPEG 具有内置压缩功能。这样做的一个副作用是,通常无法使用无损算法(zip 等)进行进一步压缩。

最好的办法是使用 JPEG 更积极的内置压缩。您可以在 python 中使用Pillow读取文件并在上传前以更高的压缩率再次写入文件。这会降低质量,但这是质量/文件大小权衡的一部分。

另外仅供参考 base64 不是压缩,实际上它会增加文件大小。它的目标是允许在纯 ascii 通道中发送二进制文件。GCS 支持二进制对象,所以你不需要它。


推荐阅读