def test_create_event_from_dict_with_all_fields(self): with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "some organizer", "creator": User.objects.filter(pk=1)[0], "title": "event title", "pub_date": datetime.datetime.now(), "country": "SI", "geoposition": Geoposition(46.05528, 14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag1", "tag2"], "picture": uploaded_picture, } test_event = create_or_update_event(**event_data) self.assertEqual(2, test_event.pk) self.assertEqual("Ljubljana", test_event.location) self.assertEqual("46.05528", str(test_event.geoposition.latitude)) self.assertIn("tag1", test_event.tags.names()) self.assertIn("tag2", test_event.tags.names()) assert "event_picture/alja" in test_event.picture.path
def _update_image(facebook_id, image_url): ''' Updates the user profile's image to the given image url Unfortunately this is quite a pain to get right with Django Suggestions to improve this are welcome ''' image_name = 'fb_image_%s.jpg' % facebook_id image_temp = NamedTemporaryFile() try: image_response = urllib2.urlopen(image_url) except AttributeError: image_response = urllib.request.urlopen(image_url) image_content = image_response.read() image_temp.write(image_content) http_message = image_response.info() image_size = len(image_content) try: content_type = http_message.type except AttributeError: content_type = http_message.get_content_type() image_file = InMemoryUploadedFile( file=image_temp, name=image_name, field_name='image', content_type=content_type, size=image_size, charset=None ) image_file.seek(0) image_temp.flush() return image_name, image_file
def get_shp_from_zip(zip_file): """ extract components file parts of a shapefile from a zip file zip_file -- zip file """ try: zip_f = ZipFile(zip_file, 'r') except BadZipfile: return None list_names = zip_f.namelist() d = {} for elem in list_names: t = elem.split('.') d[t[1].lower()] = t[0] ll = d.values() # shp name validation (same name) if all(x == ll[0] for x in ll): k = d.keys() # shp file type validation if len(k) == 4 and ( 'shp' in k and 'dbf' in k and 'shx' in k and 'prj' in k): res = {} for name in zip_f.namelist(): io = StringIO.StringIO() zo = zip_f.open(name, 'r') io.write(zo.read()) # .decode('ISO8859-1').encode('utf-8')) zo.close() res_file = InMemoryUploadedFile( io, None, name.lower(), 'text', io.len, None) res_file.seek(0) res[name.split('.')[1].lower()] = res_file return res else: return None
def test_parse(self): import StringIO from django.core.files.uploadedfile import InMemoryUploadedFile io = StringIO.StringIO() text = 'year;year_range;indicator_id;friendly_name;type_data;selection_type;' \ 'deprivation_type;country;city;region;value;description;category\n' \ '1992;;indicator_id;indicator text;p;Total;;Netherlands;;;13.3;Global_UNHABITAT-DHS;Health\n' \ '1993;;indicator_id;indicator text;p;Total;;Netherlands;;;13.5;Global_UNHABITAT-DHS;Health\n' io.write(text) uploaded_file = InMemoryUploadedFile(io, None, 'testindicator.csv', 'csv', io.len, None) uploaded_file.seek(0) class MockObject(object): user = None self.parser.parse(uploaded_file, None, MockObject()) self.assertEqual(2, Indicator.objects.all().count()) self.assertEqual(1, IndicatorData.objects.all().count()) self.assertEqual(2, IndicatorDataValue.objects.all().count()) self.assertEqual('indicator_id', Indicator.objects.all()[1].id) self.assertEqual(self.country, IndicatorData.objects.all()[0].country) self.assertEqual(13.5, IndicatorDataValue.objects.all()[1].value) self.assertEqual(1993, IndicatorDataValue.objects.all()[1].year)
def convert_to_csv(self, file_): wb = xlrd.open_workbook(file_contents=file_.read()) if len(wb.sheets()) > 1: raise forms.ValidationError( "Os arquivos devem conter apenas uma aba. Verifique também as abas escondidas" ) sh = wb.sheet_by_index(0) output = StringIO() writer = csv.writer(output) for rownum in range(sh.nrows): writer.writerow(sh.row_values(rownum)) size = output.tell() output.seek(0) in_memory = InMemoryUploadedFile( output, name=file_.name, content_type="text/csv", size=size, field_name=file_.field_name, charset=file_.charset, ) in_memory.seek(0) return in_memory
def create_thumbnail(file_path): thumbnail_filename = utils.get_thumb_filename(file_path) thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1]) image = storage.open(file_path) image = Image.open(image) file_format = image.format # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = BytesIO() imagefit.save(thumbnail_io, format=file_format) thumbnail = InMemoryUploadedFile(thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) return storage.save(thumbnail_filename, thumbnail)
def get_temporary_xml_file(xml_abs_path): fp = open(xml_abs_path) io = StringIO.StringIO(fp.read()) fp.close() xml_file = InMemoryUploadedFile(io, field_name='file', name='foo.xml', content_type='text/xml', size=io.len, charset='utf8') xml_file.seek(0) return xml_file
def create_thumbnail(file_path): thumbnail_filename = utils.get_thumb_filename(file_path) thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1]) image = default_storage.open(file_path) image = Image.open(image) file_format = image.format # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = BytesIO() imagefit.save(thumbnail_io, format=file_format) thumbnail = InMemoryUploadedFile( thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) return default_storage.save(thumbnail_filename, thumbnail)
def test_create_event_with_image(admin_user, admin_client, db): with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "audience": [4, 5], "theme": [1, 2], "contact_person": u"*****@*****.**", "country": u"SI", "description": u"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\r\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\r\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\r\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\r\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\r\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "event_url": u"", "location": u"Ljubljana, Slovenia", "organizer": u"Mozilla Slovenija", "picture": uploaded_picture, "start_date": datetime.datetime.now(), "end_date": datetime.datetime.now() + datetime.timedelta(days=3, hours=3), "tags": [u"css", u"html", u"web"], "title": u"Webmaker Ljubljana", "user_email": u"*****@*****.**", } response = admin_client.post(reverse("web.add_event"), event_data) assert response.status_code == 302 response = admin_client.get(response.url) assert "event_picture/alja" in response.content
def get_file(self): # read image from InMemoryUploadedFile self.upload_file.file.seek(0) data = self.upload_file.file # create PIL Image instance image = Image.open(data) watermark_img = Image.open("/app/ojoalplato/static/wpfamily/img/logo2_white.png") rgba_image = image.convert('RGBA') rgba_watermark = watermark_img.convert('RGBA') # resize watermark image image_x, image_y = rgba_image.size watermark_x = watermark_y = max(math.floor(image_x / 10), math.floor(image_y / 10)) new_size = (watermark_x, watermark_y) rgba_watermark = rgba_watermark.resize(new_size, resample=Image.ANTIALIAS) # apply watermark position = ((image_x - watermark_x - 10), (image_y - watermark_y - 10)) rgba_image = watermark(rgba_image, rgba_watermark, position=position) # save new watermarked image cimage = BytesIO() rgba_image.save(cimage, format="PNG") cimage.seek(0) try: field_name = self.upload_file.field_name except: field_name = self.upload_file.name image_file = InMemoryUploadedFile(cimage, field_name, self.upload_file.name, self.upload_file.content_type, rgba_image.tell, None) image_file.seek(0) self.upload_file = image_file return image_file
def resize_image(upload, file_name): resized_image_filename = file_name thumbnail_format = 'JPEG' #file_format = thumbnail_format.split('/')[1] file_format = 'JPEG' #image = default_storage.open(file_path) image = Image.open(upload) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop original photo resized_imagefit = ImageOps.fit(image, PHOTO_SIZE, Image.ANTIALIAS) resized_image_io = BytesIO() resized_imagefit.save(resized_image_io, format=file_format) resized_image = InMemoryUploadedFile( resized_image_io, None, resized_image_filename, thumbnail_format, len(resized_image_io.getvalue()), None) resized_image.seek(0) return resized_image
def _update_image(facebook_id, image_url): ''' Updates the user profile's image to the given image url Unfortunately this is quite a pain to get right with Django Suggestions to improve this are welcome ''' image_name = 'fb_image_%s.jpg' % facebook_id image_temp = NamedTemporaryFile() try: image_response = urllib2.urlopen(image_url) except AttributeError: image_response = urllib.request.urlopen(image_url) image_content = image_response.read() image_temp.write(image_content) http_message = image_response.info() image_size = len(image_content) try: content_type = http_message.type except AttributeError: content_type = http_message.get_content_type() image_file = InMemoryUploadedFile(file=image_temp, name=image_name, field_name='image', content_type=content_type, size=image_size, charset=None) image_file.seek(0) image_temp.flush() return image_name, image_file
def check_number_of_samples(file: InMemoryUploadedFile): with tempfile.NamedTemporaryFile(suffix=".vcf") as f: f.write(file.read()) file.seek(0) logger.info("Saved VCF to the temporary file {}", f.name) logger.debug("Is file readable: {}", f.readable()) try: vcf = VariantFile(f.name) except (ValueError, OSError) as e: raise ValidationError( _("Reading of the file has failed. Probably, the file has a wrong format" ), code="format.invalid", ) from e record = next(vcf.fetch()) samples = record.samples if len(samples) > 1: raise ValidationError( _("Uploaded file has more than 1 sample. Number of samples: %(n_samples)s" ), params={"n_samples": len(samples)}, code="samples.number.invalid", )
def create_thumbnail(file_path): thumbnail_filename = utils.get_thumb_filename(os.path.basename(file_path)) thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1]) file_format = thumbnail_format.split('/')[1] image_from_url = cStringIO.StringIO(urllib.urlopen(file_path).read()) image = Image.open(image_from_url) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = BytesIO() imagefit.save(thumbnail_io, format=file_format) thumbnail = InMemoryUploadedFile( thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) cc = CloudContainer('mediaplan-images') data = thumbnail.read() cc.upload_data(filename=thumbnail_filename, data=data) return thumbnail_filename
def strip_img_metadata(in_memory_img): if not in_memory_img: return None content_type = "" if type(in_memory_img) == InMemoryUploadedFile: content_type = in_memory_img.content_type else: # XXX some testcases seem to create files with wrong file format. In case of erroneous magic # bytes we do not strip any data. # TODO is there something we can do about that? pass # jpeg if content_type == "image/jpeg" or content_type == "image/jpg": img = Image.open(in_memory_img) img_io_bytes = io.BytesIO() img.save(img_io_bytes, format='JPEG') new_img = InMemoryUploadedFile(img_io_bytes, None, in_memory_img.name, 'image/jpeg', img_io_bytes.getbuffer().nbytes, None) new_img.seek(0) img.close() return new_img # TODO remove additional metadata for other formats return in_memory_img
def create_thumbnail(filename): thumbnail_filename = get_thumb_filename(filename) thumbnail_format = get_image_format(os.path.splitext(filename)[1]) pil_format = thumbnail_format.split('/')[1] image = default_storage.open(filename) image = Image.open(image) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = io.StringIO() if sys.version_info >= (3, 0): handle = str(thumbnail_io) else: handle = unicode(thumbnail_io) imagefit.save(handle, format=pil_format) thumbnail = InMemoryUploadedFile( thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) return default_storage.save(thumbnail_filename, thumbnail)
def get_temporary_text_file(): sio = io.StringIO() sio.write('text') uploadedfile = InMemoryUploadedFile(sio, None, 'text.txt', 'text/plain', sio.tell(), None) uploadedfile.seek(0) return uploadedfile
def test_create_event_from_dict_with_all_fields(self): with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "some organizer", "creator": User.objects.filter(pk=1)[0], "title": "event title", "pub_date": datetime.datetime.now(), "country": "SI", "geoposition": Geoposition(46.05528, 14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag1", "tag2"], "picture": uploaded_picture } test_event = create_or_update_event(**event_data) self.assertEqual(2, test_event.pk) self.assertEqual("Ljubljana", test_event.location) self.assertEqual("46.05528", str(test_event.geoposition.latitude)) self.assertIn("tag1", test_event.tags.names()) self.assertIn("tag2", test_event.tags.names()) assert 'event_picture/alja' in test_event.picture.path
def test_create_event_with_image(admin_user, admin_client, db): with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { 'audience': [4, 5], 'theme': [1, 2], 'contact_person': u'*****@*****.**', 'country': u'SI', 'description': u'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\r\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\r\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\r\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\r\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\r\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'event_url': u'', 'location': u'Ljubljana, Slovenia', 'organizer': u'Mozilla Slovenija', 'picture': uploaded_picture, 'start_date': datetime.datetime.now(), 'end_date': datetime.datetime.now() + datetime.timedelta(days=3, hours=3), 'tags': [u'css', u'html', u'web'], 'title': u'Webmaker Ljubljana', 'user_email': u'*****@*****.**' } response = admin_client.post(reverse('web.add_event'), event_data) assert response.status_code == 302 response = admin_client.get(response.url) assert 'event_picture/alja' in response.content
def get_temporary_text_file(): sio = io.StringIO() sio.write('text') uploadedfile = InMemoryUploadedFile( sio, None, 'text.txt', 'text/plain', sio.tell(), None) uploadedfile.seek(0) return uploadedfile
def get_temporary_text_file(name): io = StringIO.StringIO() io.write('test') text_file = InMemoryUploadedFile( io, None, name, 'text', io.len, None) text_file.seek(0) return text_file
def get_temporary_text_file(file_name, content='File Content'): io = StringIO() io.write(content) io.seek(0, os.SEEK_END) text_file = InMemoryUploadedFile(io, None, file_name, 'text', io.tell(), None) text_file.seek(0) return text_file
def test_create_event_with_image(admin_user, admin_client, db): with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { 'audience': [4, 5], 'theme': [1,2], 'contact_person': u'*****@*****.**', 'country': u'SI', 'description': u'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\r\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\r\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\r\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\r\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\r\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'event_url': u'', 'location': u'Ljubljana, Slovenia', 'organizer': u'Mozilla Slovenija', 'picture': uploaded_picture, 'start_date': datetime.datetime.now(), 'end_date': datetime.datetime.now() + datetime.timedelta(days=3, hours=3), 'tags': [u'css', u'html', u'web'], 'title': u'Webmaker Ljubljana', 'user_email': u'*****@*****.**' } response = admin_client.post(reverse('web.add_event'), event_data) assert response.status_code == 302 response = admin_client.get(response.url) assert 'event_picture/alja' in response.content
def create_img(in_memory_img, format_str, suffix_str, content_type): # remove any possible suffixes to avoid possible confusion img_name = in_memory_img.name.partition(".")[0] img = Image.open(in_memory_img) img_io_bytes = io.BytesIO() # img.save(img_io_bytes, format=format_str) # new_img = InMemoryUploadedFile(img_io_bytes, None, img_name+suffix_str, content_type, # img_io_bytes.getbuffer().nbytes, None) # store the image always as jpeg # transform the alpha channel to white if img.mode in ('RGBA', 'LA'): img_wo_alpha = Image.new(img.mode[:-1], img.size, '#ffffff') img_wo_alpha.paste(img, img.split()[-1]) # TODO should img get closed? img = img_wo_alpha # TODO I'm not sure yet whether this sanitizes the image too img.convert('RGB').save(img_io_bytes, format="JPEG") new_img = InMemoryUploadedFile(img_io_bytes, None, img_name + ".jpg", "image/jpeg", img_io_bytes.getbuffer().nbytes, None) new_img.seek(0) img.close() in_memory_img.close() return new_img
def get_temporary_text_file(): io = StringIO() io.write('foo') io.seek(0, os.SEEK_END) text_file = InMemoryUploadedFile(io, None, 'foo.txt', 'text', io.tell(), None) text_file.seek(0) return text_file
def process_thumbnail(instance, sizes, crop=False): file = StringIO.StringIO(instance.original_photo.read()) original_image = Image.open(file) # open the image using PIL # pull a few variables out of that full path filename = os.path.basename(instance.original_photo.name).rsplit('.', 1)[0] extension = os.path.basename(instance.original_photo.name).rsplit('.', 1)[1] # the file extension # If there is no extension found try jpg if extension == '': extension = 'jpg' # use the file extension to determine if the image is valid before proceeding if extension not in ['jpg', 'jpeg', 'gif', 'png']: return False for size_name, size in sizes.iteritems(): im = original_image.copy() (x_size, y_size) = im.size original_ratio = float(x_size) / float(y_size) width = size['width'] height = size['height'] new_ratio = float(width / height) if new_ratio > original_ratio: im = im.resize((width, int(width / original_ratio)), Image.ANTIALIAS) if crop: clip_amount = int((int(width / original_ratio) - height) / 2) im = im.crop((0, clip_amount, width,height + clip_amount)) else: im = im.resize((int(height * original_ratio), height), Image.ANTIALIAS) if crop: clip_amount = int((int(height * original_ratio) - width) / 2) im = im.crop((clip_amount, 0, width + clip_amount, height)) name = "%s.jpg" % filename tempfile_io = StringIO.StringIO() if im.mode != "RGB": im = im.convert("RGB") im.save(tempfile_io, 'JPEG') temp_file = InMemoryUploadedFile(tempfile_io, None, name, 'image/jpeg', tempfile_io.len, None) done, tries = False, 0 while not done: try: # Make sure we're at the beginning of the file for reading when saving temp_file.seek(0) getattr(instance, size_name).save(name, temp_file) done = True except SSLError: pass # Try at max, 10 times before quitting tries += 1 if tries > 10: done = True return True
def test_edit_event_with_all_fields(self): # First create a new event with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "some organizer", "creator": User.objects.filter(pk=1)[0], "title": "event title", "pub_date": datetime.datetime.now(), "country": "SI", "geoposition": Geoposition(46.05528, 14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag1", "tag2"], "picture": uploaded_picture } test_event = create_or_update_event(**event_data) # Then edit it with open( local(__file__).dirname + '/../../static/img/team/ercchy.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "ercchy.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "another organiser", "creator": User.objects.filter(pk=1)[0], "title": "event title - edited", "pub_date": datetime.datetime.now(), "country": "SI", # "geoposition": Geoposition(46.05528,14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag3", "tag4"], "picture": uploaded_picture } test_event = create_or_update_event(event_id=test_event.id, **event_data) assert "tag1" not in test_event.tags.names() assert 'event_picture/alja' not in test_event.picture assert 'event_picture/ercchy' in test_event.picture.path
def _get_temporary_file(self, type='application/pdf', extension='pdf'): io = StringIO.StringIO() io.write('foo') text_file = InMemoryUploadedFile( io, None, 'foo.%s' % extension, type, io.len, None ) text_file.seek(0) return text_file
def get_in_memory_file(image: "Image"): temp_file_io = BytesIO() image.save(temp_file_io, "jpeg", optimize=True) temp_file_io.seek(0) image_file = InMemoryUploadedFile(temp_file_io, None, str(uuid.uuid4()) + ".jpeg", "jpeg", None, None) image_file.seek(0) return image_file
def get_temporary_image(): io = StringIO.StringIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', io.len, None) image_file.seek(0) return image_file
def rotate_image(image: InMemoryUploadedFile, angle: int) -> Tuple[float, InMemoryUploadedFile]: img = Image.open(image.file) start = time.time() img = img.rotate(angle, expand=True) rotate_duration = time.time() - start image.seek(0) img.save(image) return rotate_duration, image
def get_temporary_image(): io = BytesIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'test.jpg', 'jpeg', None, None) image_file.seek(0) return image_file
def get_temporary_image(self): io = BytesIO() size = (100, 100) color = (255, 0, 0) image = Image.new("RGB", size, color) image.save(io, format='PNG') image_file = InMemoryUploadedFile(io, None, 'foo.png', 'png', io.__sizeof__(), None) image_file.seek(0) return image_file
def get_temporary_image(): io = StringIO.StringIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='PNG') image_file = InMemoryUploadedFile(io, None, 'temp.png', 'image/png', io.len, None) image_file.seek(0) return image_file
def get_temporary_image_file(): bio = io.BytesIO() size, color = (300, 300,), (200, 50, 200, 80,) image = Image.new("RGBA", size, color) image.save(bio, format='PNG') uploadedfile = InMemoryUploadedFile( bio, None, 'image.png', 'png', bio.tell(), None) uploadedfile.seek(0) return uploadedfile
def get_in_memory_file(image: 'Image'): temp_file_io = BytesIO() image.save(temp_file_io, 'jpeg', optimize=True) temp_file_io.seek(0) image_file = InMemoryUploadedFile(temp_file_io, None, str(uuid.uuid4()) + '.jpeg', 'jpeg', None, None) image_file.seek(0) return image_file
def get_temporary_image_file(): io = StringIO.StringIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='PNG') image_file = InMemoryUploadedFile(io, field_name='file', name='foo.png', content_type='png', size=io.len, charset=None) image_file.seek(0) return image_file
def test_ambassadors_list(db, client): test_country_name = "Austria" test_country_code = "AT" test_username = "******" test_email = "*****@*****.**" test_first_name = "Testko" test_last_name = "Test" test_full_name = test_first_name + " " + test_last_name test_ambassador = User.objects.create( username=test_username, email=test_email, first_name=test_first_name, last_name=test_last_name ) test_ambassador_profile = UserProfile.objects.create(user=test_ambassador, country=test_country_code) group = Group.objects.get(name="ambassadors") group.user_set.add(test_ambassador) with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja17.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) avatar = Avatar(user=test_ambassador, primary=True) avatar.avatar.save(uploaded_picture.name, uploaded_picture) avatar.save() new_avatar = get_primary_avatar(test_ambassador, size=80) test_amb_avatar = new_avatar.avatar_url(80) response = client.get(reverse("web.ambassadors")) # We're expecting to the Ambassador under the right country, # with the right avatar and the right email contact expected_result = """ <h2 class="clearfix">%s</h2> <div class="ambassador clearfix"> <img src="%s" alt="%s" width="80" height="80" class="img-circle" /> <h4>%s <span> <a alt="Send me an email" href="mailto:%s"><i class="fa fa-envelope"></i></a> """ % ( test_country_name, test_amb_avatar, test_username, test_full_name, test_email, ) expected_result = expected_result.replace("\t", "").replace("\n", "") ambassadors_content = response.content.replace("\t", "").replace("\n", "") # Check this test and modify it to integrating the Ambassadors page changes # assert expected_result in ambassadors_content test_ambassador.delete() avatar.delete()
def test_edit_event_with_all_fields(self): # First create a new event with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile( io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "some organizer", "creator": User.objects.filter(pk=1)[0], "title": "event title", "pub_date": datetime.datetime.now(), "country": "SI", "geoposition": Geoposition(46.05528, 14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag1", "tag2"], "picture": uploaded_picture } test_event = create_or_update_event(**event_data) # Then edit it with open(local(__file__).dirname + '/../../static/img/team/ercchy.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile( io, None, "ercchy.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "another organiser", "creator": User.objects.filter(pk=1)[0], "title": "event title - edited", "pub_date": datetime.datetime.now(), "country": "SI", # "geoposition": Geoposition(46.05528,14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag3", "tag4"], "picture": uploaded_picture } test_event = create_or_update_event( event_id=test_event.id, **event_data) assert "tag1" not in test_event.tags.names() assert 'event_picture/alja' not in test_event.picture assert 'event_picture/ercchy' in test_event.picture.path
def create_uploaded_image(): io = BytesIO() size = (1, 1) color = (255, 0, 0) image = PILImage.new("RGB", size, color) image.save(io, format="JPEG") image_file = InMemoryUploadedFile(io, None, "foo.jpg", "jpeg", image.size, None) image_file.seek(0) return image_file
def get_temporary_image(): output = StringIO.StringIO() size = (1200, 700) color = (255, 0, 0, 0) image = Img.new("RGBA", size, color) image.save(output, format='JPEG') image_file = InMemoryUploadedFile( output, None, 'test.jpg', 'jpeg', output.len, None) image_file.seek(0) return image_file
def create_temp_file(name="temp.txt", filetype="text"): """ Create an in-memory temporary file. Suitable to be attached as file data in tests. """ temp_io = StringIO() temp_io.write("Temporary File") temp_file = InMemoryUploadedFile(temp_io, None, name, filetype, temp_io.len, None) temp_file.seek(0) return temp_file
def get_temporary_image(): # Testing utility. io = BytesIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new('RGBA', size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', 1, None) image_file.seek(0) return image_file
def get_temporary_image(): output = StringIO.StringIO() size = (1200, 700) color = (255, 0, 0, 0) image = Img.new("RGBA", size, color) image.save(output, format='JPEG') image_file = InMemoryUploadedFile(output, None, 'test.jpg', 'jpeg', output.len, None) image_file.seek(0) return image_file
def create_new(upfile: InMemoryUploadedFile, activity: Activity) -> \ 'ActivityTrack': """Create a new activity""" track = ActivityTrack.objects.create(activity=activity, original_filename=upfile.name) ActivityTrackFile.objects.create(track=track, file=upfile) upfile.seek(0) ActivityTrackpoint.create_trackpoints(track, upfile) track.reset_trim() return track
def get_temporary_image(ext='jpg'): io = StringIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='JPEG') name = 'test.{}'.format(ext) image_file = InMemoryUploadedFile(io, None, name, 'jpeg', io.len, None) image_file.seek(0) return image_file
def get_temporary_image(): io = BytesIO() size = (200, 200) color = (255, 0, 0) image = Image.new("RGB", size, color) image.save(io, format="JPEG") image_file = InMemoryUploadedFile(io, None, "foo.jpg", "jpeg", image.size, None) image_file.seek(0) return image_file
def get_temporary_image(): """ Quick hack, credit to https://stackoverflow.com/questions/43135771/ """ io = BytesIO() size = (200, 200) color = (255, 0, 0) image = Image.new("RGB", size, color) image.save(io, format="JPEG") image_file = InMemoryUploadedFile(io, None, "foo.jpg", "jpeg", image.size, None) image_file.seek(0) return image_file
def get_image_in_memory_data(): """ Creates the InMemoryUploadedFile object using thedata from io to save it into the ImageField of the database """ io = get_image_data() # get a red rectangle 200x200px # create the InMemoryUploadedFile object with the 'foo.jpg' file image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', sys.getsizeof(io), None) image_file.seek(0) # seek to the beginning return image_file
def get_temporary_text_file(): io = StringIO.StringIO() io.write('foo') text_file = InMemoryUploadedFile(io, field_name='file', name='foo.txt', content_type='text', size=io.len, charset='utf8') text_file.seek(0) return text_file
def test_file(title): """ Create text file. """ io = BytesIO() io.write(b'test') text_file = InMemoryUploadedFile( io, None, title, 'text', 'utf-8', None) text_file.seek(0) return text_file
def mock_text_file(): """ Generates in memory .txt, text/plain file. Size is set to 100kB (fake) for ease of testing of min and max file size. """ io = StringIO() io.write('test content') text_file = InMemoryUploadedFile(io, None, 'foo.txt', 'text', 100 * 1024, None) text_file.seek(0) return text_file
def get_temporary_image(): """ Quick hack, credit to https://stackoverflow.com/questions/43135771/ """ io = BytesIO() size = (200, 200) color = (255, 0, 0) image = Image.new("RGB", size, color) image.save(io, format="JPEG") image_file = InMemoryUploadedFile( io, None, "foo.jpg", "jpeg", image.size, None ) image_file.seek(0) return image_file
def create_inmemory_image(file_name='tmp.png', format=None, width=200, height=200): from PIL import Image if not format: _, extension = os.path.splitext(file_name) format = extension[1:].upper() stream = six.BytesIO() size = (width, height) color = (255, 0, 0, 0) image = Image.new('RGBA', size, color) image.save(stream, format=format) image_file = InMemoryUploadedFile(stream, None, file_name, format, stream.tell(), None) image_file.seek(0) return image_file
def file(self): if self._file: self._file.seek(0) return self._file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file_path = os.path.join(BASE_DIR, "excel_import/testdata/test.xlsx") f = open(file_path, 'rb') io = BytesIO(f.read()) f.seek(0, os.SEEK_END) size = f.tell() f.close() file = InMemoryUploadedFile(io, None, 'test.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', size, None) file.seek(0) self._file = file return file
def _update_image(facebook_id, image_url): """ Updates the user profile's image to the given image url Unfortunately this is quite a pain to get right with Django Suggestions to improve this are welcome """ image_name = "fb_image_%s.jpg" % facebook_id image_temp = NamedTemporaryFile() image_response = urllib2.urlopen(image_url) image_content = image_response.read() image_temp.write(image_content) http_message = image_response.info() image_size = len(image_content) content_type = http_message.type image_file = InMemoryUploadedFile( file=image_temp, name=image_name, field_name="image", content_type=content_type, size=image_size, charset=None ) image_file.seek(0) image_temp.flush() return image_name, image_file
def resizeByWidth(inMemFile, newWidth, fName=None): inMemFile.seek(0) # Приводим изображение к ширине from PIL import Image im = Image.open(inMemFile) ratio = newWidth / float(im.size[0]) im = im.resize((newWidth, int(im.size[1] * ratio)), Image.ANTIALIAS) # Сохраняем его обратно в файл from django.core.files.uploadedfile import InMemoryUploadedFile import StringIO im_io = StringIO.StringIO() im.save(im_io, inMemFile.content_type.split("/")[1]) fileObj = InMemoryUploadedFile( im_io, None, fName if fName else inMemFile.name, inMemFile.content_type, im_io.len, None ) fileObj.seek(0) return fileObj