记录爬虫利用pyquery爬虫保存图片时遇到的一些问题:
1. cannot write mode P as JPEG
解决办法:将模式“P”转化为“RGB”模式
if img.mode == "P":
img = img.convert('RGB')
2. (PIL) Image.save保存图片后,图片大小为0KB
解决办法:设置quality参数
im.save(img_name, quality=95)
3. Inches(self.px_width / self.horz_dpi) ZeroDivisionError: division by zero
解决办法:这边是由于dpi为0导致的报错,修改图片的dpi后解决
源码的解释:
Return a new picture shape added in its own paragraph at the end of the document. The picture contains the image at *image_path_or_stream*, scaled based on *width* and *height*. If neither width nor height is specified, the picture appears at its native size. If only one is specified, it is used to compute a scaling factor that is then applied to the unspecified dimension, preserving the aspect ratio of the image. The native size of the picture is calculated using the dots-per-inch (dpi) value specified in the image file, defaulting to 72 dpi if no value is specified, as is often the case.
部分代码:
with open(save_path, 'wb') as f:
res = requests.get(picture_url).content
f.write(res)
f.close()
im = ImagePIL.open(save_path)
if im.mode == "P":
im = im.convert('RGB')
save_path_modify = save_path.replace('.jpg', 'modify.jpg')
im.save(save_path_modify, dpi=(300, 300), quality=100)
document.add_picture(save_path_modify, width=Inches(5))