简体   繁体   English

将BytesIO保存到Django ImageField

[英]Saving BytesIO to Django ImageField

I have a web scraper that I want to download an image of the page it's scraping and save it as a "screenshot" ImageField in a Django model. 我有一个网络刮板,我想下载它正在抓取的页面的图像,并将其保存为Django模型中的“屏幕截图”ImageField。 I am using this code: 我正在使用此代码:

def save_screenshot(source,screenshot):
    box = (0, 0, 1200, 600)
    im = Image.open(io.BytesIO(screenshot))
    region = im.crop(box)
    tempfile_io = io.BytesIO()
    region.save(tempfile_io, 'JPEG', optimize=True, quality=70)
    source.screenshot.save(source.slug_name+"-screenshot",ContentFile(tempfile_io.getvalue()),save=True)

It saves the screenshot to the /media/news_source_screenshots/ directory but doesn't save it to the model. 它将屏幕截图保存到/ media / news_source_screenshots /目录,但不将其保存到模型中。 The model field is defined as: 模型字段定义为:

screenshot = models.ImageField(upload_to='news_source_screenshots',blank=True,null=True)

What am I missing? 我错过了什么?

So it turns out the above code works great! 事实证明上面的代码效果很好! The issue was that I was calling the above method using a piece of code like this: 问题是我使用这样的代码调用上面的方法:

source = NewsSource.objects.get(name=name)
html,screenshot = get_url(source.url)
save_screenshot(source,screenshot)
source.save()

So the save_sceenshot method worked but then the work it had done was overwritten by my source.save() call. 所以save_sceenshot方法有效,但是我的source.save()调用覆盖了它所完成的工作。 Go figure! 去搞清楚!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM