如何在Python Flask中将在线图片URL转换为Blurhash Key?
在Flask中将在线图片URL转换为Blurhash密钥的实现
所需依赖
先安装必要的Python包:
pip install flask blurhash requests pillow
实现步骤与代码
核心逻辑
官方blurhash库仅支持从本地文件或像素数据生成哈希,因此我们需要先拉取在线图片的二进制数据,再转换为符合要求的格式:
- 用
requests下载在线图片的二进制内容 - 通过
Pillow将二进制内容加载为Image对象 - 将图片转换为RGB模式(Blurhash仅支持RGB格式)
- 提取图片像素数据,调用
blurhash.encode生成哈希
Flask路由示例
from flask import Flask, jsonify, request import requests from PIL import Image import blurhash from io import BytesIO app = Flask(__name__) @app.route('/generate-blurhash', methods=['GET']) def generate_blurhash(): # 获取请求中的图片URL参数 image_url = request.args.get('url') if not image_url: return jsonify({'error': 'Missing image URL parameter'}), 400 try: # 下载在线图片,设置超时避免服务挂起 response = requests.get(image_url, timeout=10) response.raise_for_status() # 抛出HTTP请求错误 # 将二进制内容转为Image对象 img = Image.open(BytesIO(response.content)) # 转换为RGB模式(兼容透明图、灰度图等格式) img_rgb = img.convert('RGB') # 获取图片宽高与像素字节数据 width, height = img_rgb.size pixels = img_rgb.tobytes() # 生成Blurhash(x/y_components控制精度,范围1-9,数值越大哈希越精准) blur_hash = blurhash.encode(width, height, pixels, x_components=4, y_components=3) return jsonify({'blurhash': blur_hash}) except requests.exceptions.RequestException as e: return jsonify({'error': f'Failed to download image: {str(e)}'}), 500 except Exception as e: return jsonify({'error': f'Image processing failed: {str(e)}'}), 500 if __name__ == '__main__': app.run(debug=True)
关键说明
x_components和y_components:决定Blurhash的精度,常用4x3或5x4即可平衡效果与字符串长度- 异常处理:覆盖了请求超时、图片加载失败等常见场景,避免服务崩溃
- 格式兼容:强制转换为RGB模式,解决透明图、灰度图等非RGB格式无法生成哈希的问题
内容的提问来源于stack exchange,提问作者Jigyasu Tanwar
相关产品推荐
相关产品推荐

