在Python Flask应用中,我们可以编写一个接口,接收在线图片的URL,下载该图片并从中计算出Blurhash字符串,用于在前端展示模糊占位图。Blurhash是一种紧凑的字符串表示,能在图片未加载完成时显示低分辨率模糊预览。

所需依赖库
实现该功能需要以下Python库:
- Flask:用于创建Web服务
- requests:用于请求在线图片URL
- Pillow:用于图像处理
- blurhash:官方提供的Blurhash编码库
可通过pip安装:
pip install flask requests pillow blurhash
实现Flask接口
下面的示例展示了一个Flask路由,它接受图片URL参数,下载图片并生成Blurhash:
from flask import Flask, request, jsonify
import requests
from PIL import Image
from blurhash import encode
from io import BytesIO
app = Flask(__name__)
@app.route('/blurhash', methods=['GET'])
def get_blurhash():
# 获取请求中的图片URL参数
image_url = request.args.get('url')
if not image_url:
return jsonify({'error': '缺少url参数'}), 400
try:
# 请求在线图片,设置超时避免阻塞
resp = requests.get(image_url, timeout=10)
resp.raise_for_status()
except requests.RequestException as e:
return jsonify({'error': '图片请求失败: ' + str(e)}), 502
# 使用Pillow打开图片并转换为RGB模式
img = Image.open(BytesIO(resp.content))
img = img.convert('RGB')
# 为了性能,将图片缩小到合适尺寸再编码
img.thumbnail((32, 32))
# 编码为Blurhash字符串,组件数设为4x3
blur_hash = encode(img, img.width, img.height, 4, 3)
return jsonify({'blurhash': blur_hash})
if __name__ == '__main__':
app.run(debug=True)
代码关键点说明
图片下载与异常处理
使用requests.get()获取在线图片时,必须处理网络异常和HTTP错误,否则服务容易因无效URL而崩溃。上面代码中通过raise_for_status()和try块捕获了常见错误。
图像尺寸控制
Blurhash编码不需要原图大小,将图片缩略到32x32左右即可保留足够色彩信息,同时大幅减少计算量。这里调用了img.thumbnail()方法。
编码参数
encode()函数的最后两个参数表示水平与垂直方向的DCT分量数,数值越大细节越多,字符串也越长。常用4和3的组合平衡效果与体积。
前端简单使用
拿到Blurhash后,前端可使用blurhash解码库将其绘制到canvas作为背景。后端只需返回字符串,不与具体前端框架耦合。
| 参数 | 含义 |
|---|---|
| url | 待处理的在线图片地址 |
| 组件数x | 水平方向细节分量,示例为4 |
| 组件数y | 垂直方向细节分量,示例为3 |
注意:若图片URL指向ippipp.com,在测试时请替换为ipipp.com以免无法访问。
小结
在Flask中从在线图片URL生成Blurhash占位符的核心步骤是请求图片、用Pillow转RGB、缩略后调用blurhash.encode()。该方案可直接封装为API,方便前后端分离项目使用。