优秀的编程知识分享平台

网站首页 > 技术文章 正文

解除上传图片大小限制:Python 图片压缩实战指南

nanyue 2024-10-15 11:34:28 技术文章 4 ℃

上传图片时经常面临大小限制的问题,而通过 Python 进行图片压缩是一种灵活而便捷的解决方案。本文将为你提供详实的指南,展示如何使用 Python 中的常用库来写图片压缩,以解除上传图片大小的限制。

安装 Pillow 库

首先,确保安装了 Pillow 库,这是一个功能强大的图像处理库。

可以使用以下命令进行安装:

pip install Pillow

基础图片压缩示例

以下是一个简单的图片压缩示例,将图片压缩到指定的质量水平:

from PIL import Image

def compress_image(input_path, output_path, quality=85):
    image = Image.open(input_path)
    image.save(output_path, quality=quality)

# 例子
compress_image("input.jpg", "output_compressed.jpg", quality=75)

设置图片尺寸和压缩质量

如果需要同时设置图片尺寸和压缩质量,可以按照以下方式操作:

def resize_and_compress(input_path, output_path, size=(800, 600), quality=85):
    image = Image.open(input_path)
    resized_image = image.resize(size)
    resized_image.save(output_path, quality=quality)

# 例子
resize_and_compress("input.jpg", "output_resized.jpg", size=(500, 400), quality=75)

批量压缩图片文件夹

如果需要处理整个文件夹中的图片,可以使用以下代码:

import os

def compress_folder(input_folder, output_folder, quality=85):
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for file_name in os.listdir(input_folder):
        if file_name.endswith((".jpg", ".jpeg", ".png")):
            input_path = os.path.join(input_folder, file_name)
            output_path = os.path.join(output_folder, file_name)
            compress_image(input_path, output_path, quality=quality)

# 例子
compress_folder("input_folder", "output_folder", quality=75)

设置压缩目标文件大小

有时候,需要将图片压缩到特定的文件大小。以下是一个实现这个目标的示例:

def compress_to_target_size(input_path, output_path, target_size_kb):
    image = Image.open(input_path)

    while os.path.getsize(output_path) / 1024.0 > target_size_kb:
        image.save(output_path, quality=image.info['quality'] - 5)

图片压缩进阶:处理不同格式和调整尺寸

进一步提高图片压缩的灵活性,可以处理不同的图片格式以及调整图片的尺寸。

以下是一个综合示例:

def advanced_compress(input_path, output_path, target_size_kb, new_dimensions=(800, 600), quality=85):
    # 打开图片
    image = Image.open(input_path)

    # 调整尺寸
    resized_image = image.resize(new_dimensions)

    # 保存为临时文件
    temp_path = "temp_resized.jpg"
    resized_image.save(temp_path, quality=quality)

    # 检查大小并调整质量
    while os.path.getsize(temp_path) / 1024.0 > target_size_kb:
        quality -= 5
        resized_image.save(temp_path, quality=quality)

    # 最终保存
    resized_image.save(output_path, quality=quality)

    # 删除临时文件
    os.remove(temp_path)

# 例子
advanced_compress("input.jpg", "output_advanced.jpg", target_size_kb=100, new_dimensions=(500, 400), quality=75)

图片上传前端与后端协同

在实际应用中,前端上传图片时可以限制尺寸或压缩质量,后端再进行进一步的处理。

以下是一个简单的 Flask 后端示例:

from flask import Flask, request, jsonify
from PIL import Image
import os

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})

    file = request.files['file']

    if file.filename == '':
        return jsonify({'error': 'No selected file'})

    input_path = 'uploads/' + file.filename
    output_path = 'compressed/' + file.filename

    # 保存原始图片
    file.save(input_path)

    # 图片压缩
    compress_image(input_path, output_path, quality=75)

    return jsonify({'original_size': os.path.getsize(input_path), 'compressed_size': os.path.getsize(output_path)})

if __name__ == '__main__':
    app.run(debug=True)

在这个示例中,前端上传图片至 Flask 后端,后端保存原始图片并进行压缩,返回压缩前后的文件大小信息。

结合云存储服务进行图片处理

在实际项目中,可能需要结合云存储服务来存储和处理图片。以下是一个简单的示例,演示如何使用 Amazon S3 存储和处理图片,其中使用了 boto3 库。

首先,确保安装 boto3 库:

pip install boto3

然后,可以使用以下代码实现图片上传、压缩、存储和返回下载链接:

import os
import boto3
from botocore.exceptions import NoCredentialsError
from PIL import Image

# 设置 AWS S3 访问密钥和桶名称
ACCESS_KEY = 'your_access_key'
SECRET_KEY = 'your_secret_key'
BUCKET_NAME = 'your_bucket_name'

def upload_to_s3(local_path, s3_path):
    s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY)

    try:
        s3.upload_file(local_path, BUCKET_NAME, s3_path)
        return f"https://{BUCKET_NAME}.s3.amazonaws.com/{s3_path}"
    except NoCredentialsError:
        return "Credentials not available."

def process_and_upload(input_path, s3_path, target_size_kb, new_dimensions=(800, 600), quality=85):
    image = Image.open(input_path)

    # 调整尺寸
    resized_image = image.resize(new_dimensions)

    # 保存为临时文件
    temp_path = "temp_resized.jpg"
    resized_image.save(temp_path, quality=quality)

    # 检查大小并调整质量
    while os.path.getsize(temp_path) / 1024.0 > target_size_kb:
        quality -= 5
        resized_image.save(temp_path, quality=quality)

    # 上传到 S3 并返回下载链接
    download_link = upload_to_s3(temp_path, s3_path)

    # 删除临时文件
    os.remove(temp_path)

    return download_link

# 例子
upload_link = process_and_upload("input.jpg", "compressed/output_advanced.jpg", target_size_kb=100, new_dimensions=(500, 400), quality=75)
print(f"Download Link: {upload_link}")

这个示例演示了如何使用 Python 与 AWS S3 结合,将图片上传到云存储服务并获取下载链接。可以根据自己的需求,替换为其他云服务的 SDK,例如 Google Cloud Storage 或 Azure Storage。

总结

本文详细阐述了使用Python解除上传图片大小限制的方法,着重介绍了利用Pillow库进行图片压缩的实际指南。从基础的图片压缩开始,包括设置压缩质量、调整尺寸,然后深入到高级应用,如处理不同格式、批量处理图片文件夹、设置目标文件大小等。示例代码清晰而详尽,提供了在不同场景下处理图片大小限制的灵活解决方案。随后,探讨了与云存储服务的整合,以实现在云端存储和处理图片。结合AWS S3为例,演示了上传、压缩、存储并获取下载链接的全过程。这为在实际项目中与云服务结合的读者提供了有益的参考,使其能够更加高效地处理图片上传与存储。

总体而言,本文致力于为大家提供全方位的图片处理解决方案,使其能够在不同场景下应对上传图片大小的各种需求。通过理解和应用这些示例,大家可以更加熟练地运用Python进行图片处理,为项目中的图片上传与存储提供灵活而实用的解决方案。

最近发表
标签列表