下载图像会在新文件中创建灰色工件

时间:2018-05-31 13:26:00

标签: python django python-3.x

我试图将图像从网址保存到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

1 个答案:

答案 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"