def expand_image_with_mask(image_path, top, bottom, left, right):
:param image_path: 输入图像路径
:return: (扩展后图像base64, 对应mask base64)
original_img = Image.open(image_path)
width, height = original_img.size
new_width = width + left + right
new_height = height + top + bottom
expanded_img = Image.new('RGB', (new_width, new_height), (255, 255, 255))
expanded_img.paste(original_img, (left, top))
mask = Image.new('L', (new_width, new_height), 255)
mask.paste(0, (left, top, left + width, top + height))
expanded_img.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
mask.save(buffered, format="PNG")
mask_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
return img_base64, mask_base64
if __name__ == "__main__":
image_path = "test.jpg"
top, bottom, left, right = 50, 50, 500, 50
expanded_img, mask = expand_image_with_mask(image_path, top, bottom, left, right)
print("\n对应mask base64:")