本地测试基于Blobstore与GCS的图片裁剪器时遇到问题
Blobstore与GCS图片裁剪器本地测试问题
我最近在本地测试一个基于Blobstore和GCS的图片裁剪器,但碰到了不少问题。得先说明下,我还没完全吃透GCS的用法,估计这里面有好几个坑等着填。相关代码片段如下:
def resize_and_insert_image(raw_blob_key, size, crop_info=None, is_percentage=False): with google_blobstore.BlobReader(raw_blob_key) as f: blob_data = f.read() img = google_images.Image(image_data=blob_data) if crop_info: # 需要0.0至1.0范围内的浮点裁剪坐标 width = img.width height = img.height # 需要...的内容
裁剪坐标转换的解决方案
我猜你现在卡在把crop_info转换成0-1浮点坐标这一步对吧?其实核心就是根据is_percentage参数分两种情况处理:
- 如果
is_percentage=True:说明传入的crop_info是百分比数值(比如0-100),直接除以100就能转成0-1的浮点数 - 如果
is_percentage=False:说明crop_info是像素坐标,需要分别除以图片的实际宽高来得到比例值
假设你的crop_info是包含x1, y1, x2, y2的元组(左上角和右下角坐标),可以这么补全代码:
if crop_info: # 需要0.0至1.0范围内的浮点裁剪坐标 width = img.width height = img.height x1, y1, x2, y2 = crop_info # 根据is_percentage处理坐标 if is_percentage: x1 = x1 / 100.0 y1 = y1 / 100.0 x2 = x2 / 100.0 y2 = y2 / 100.0 else: x1 = x1 / width y1 = y1 / height x2 = x2 / width y2 = y2 / height # 执行裁剪操作 img.crop(x1, y1, x2, y2)
给GCS新手的额外提示
除了坐标转换,你可能还会碰到这些常见问题:
- 本地测试时要确保Blobstore模拟器配置正确,不然可能读不到Blob数据
- 检查GCS的权限设置,确保你的服务账号有读写对应存储桶的权限
- 确认
google_images.Image的裁剪方法参数顺序是否正确(有些库要求坐标顺序是y1, x1, y2, x2,得仔细看文档)
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

