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. 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. The model field is defined as:
screenshot = models.ImageField(upload_to='news_source_screenshots',blank=True,null=True)
What am I missing?
region
... insource.screenshot.save(source.slug_name+"-screenshot", ContentFile(region.get_value()), save=True)
, remember that region os now your tempfile, cause tempfile_io is a void buffer – Moshercode
TypeError: 'Image' does not support the buffer interfacecode
and the image is not longer saved in the /media/news_source_screenshost/ directory – Diallagetempfile_io = io.BytesIO()
totempfile_io = io.StringIO()
and gotTypeError: string argument expected, got 'bytes'
referring to theregion.save
line of code @german-alzate-martinez – Diallage