我试图将图像从网址保存到Django模型。
当我尝试使用此代码时,我会在图像底部看到灰色像素,就像在读取整个图像之前保存它一样。
任何人都会看到此代码可能出现的问题,或者知道更好的方法吗?
def save_image(img_url, img_pk):
file_name = img_url.split('/')[-1]
external_image = requests.get(img_url, stream=True)
if external_image.status_code == 200:
# Create a temporary file
lf = tempfile.NamedTemporaryFile()
# Read the streamed image in sections
for block in external_image.iter_content(1024 * 8):
# If no more file then stop
if not block:
break
# Write image block to temporary file
lf.write(block)
image_obj = Image.objects.get(pk=img_pk)
image_obj.image.save(file_name, files.File(lf))
image_obj.save()
return image_obj
答案 0 :(得分:0)
def save_image(img_url, img_pk):
file_name = img_url.split('/')[-1]
external_image = requests.get(img_url, stream=True)
if external_image.status_code == 200:
# Create a temporary file
lf = tempfile.NamedTemporaryFile()
# Read the streamed image in sections
for block in external_image.iter_content(1024 * 8):
# If no more file then stop
if not block:
break
# Write image block to temporary file
lf.write(block)
#Save the image outside the foorloop
image_obj = Image.objects.get(pk=img_pk)
image_obj.image.save(file_name, files.File(lf))
image_obj.save()
return "Done"