Kun1009's picture
Upload 86 files
a5b9369 verified
import oss2
import sys
from PIL import Image
from io import BytesIO
#替换为您的AccessKey ID和AccessKey Secret、OSS endpoint和Bucket名称
access_key_id = 'your_access_key_id'
access_key_secret = 'your_access_key_secret'
endpoint = 'your_oss_endpoint'
bucket_name = 'your_bucket_name'
image_path = 'your_image_path'
image_name = 'your_image_name'
object_name = 'your_object_name'
#创建Bucket对象和上传凭证
auth = oss2.Auth(access_key_id, access_key_secret)
bucket = oss2.Bucket(auth, endpoint, bucket_name)
upload_token = bucket.sign_url('PUT', object_name, 3600)
#读取图片文件并上传到阿里云图床
with open(image_path, 'rb') as f:
image = Image.open(f)
image.thumbnail((800, 800)) # 调整图片大小,可选参数为(宽度,高度)
img_buffer = BytesIO()
image.save(img_buffer, format='JPEG') # 保存图片为JPEG格式,可选参数为(格式,质量)
img_buffer.seek(0)
img_data = img_buffer.read()[10:] # 去掉HTTP头部信息,只保留图片数据部分
headers = {'Content-Type': 'image/jpeg'} # 设置请求头信息,可选参数为(Content-Type)
url = upload_token + '&body=' + urllib.parse.quote(img_data) # 拼接URL并上传图片数据
resp = requests.put(url, data=img_data, headers=headers) # 发送PUT请求上传图片数据,可选参数为(URL,数据,请求头)