Python django.core.files.images.ImageFile() Examples
The following are 24
code examples of django.core.files.images.ImageFile().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.core.files.images
, or try the search function
.
Example #1
Source File: test_imagefield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def setUp(self): """ Creates a pristine temp directory (or deletes and recreates if it already exists) that the model uses as its storage directory. Sets up two ImageFile instances for use in tests. """ if os.path.exists(temp_storage_dir): shutil.rmtree(temp_storage_dir) os.mkdir(temp_storage_dir) file_path1 = os.path.join(os.path.dirname(__file__), '4x8.png') self.file1 = self.File(open(file_path1, 'rb'), name='4x8.png') file_path2 = os.path.join(os.path.dirname(__file__), '8x4.png') self.file2 = self.File(open(file_path2, 'rb'), name='8x4.png')
Example #2
Source File: test_homepage_context.py From conf_site with MIT License | 6 votes |
def test_logo_image(self): homepage = HomePage.objects.get() self.assertIsNone(homepage.logo_image) with self.settings(CONFERENCE_ID=self.conference.id): # Test that default logo image appears. response = self.client.get(homepage.url) self.assertContains(response, "/logo.png") # Replace default logo with a new image. test_logo_name = Faker().uuid4() image_file = ImageFile( open("conf_site/cms/tests/test-logo.png", "rb"), test_logo_name ) ImageModel = get_image_model() image = ImageModel(file=image_file) # The image must be saved before it is attached # to the homepage. image.save() homepage.logo_image = image homepage.save() response = self.client.get(homepage.url) self.assertNotContains(response, "/logo.288981a8dfa8.png") self.assertContains(response, test_logo_name)
Example #3
Source File: odlcs_test.py From interop with Apache License 2.0 | 6 votes |
def test_get(self): """Test GET when there are odlcs.""" odlc = Odlc(mission=self.mission, user=self.team, odlc_type=interop_api_pb2.Odlc.STANDARD) odlc.save() with open(test_image('A.jpg'), 'rb') as f: odlc.thumbnail.save('%d.%s' % (odlc.pk, 'jpg'), ImageFile(f)) odlc.save() response = self.client.get(odlcs_review_url) self.assertEqual(200, response.status_code) data = json.loads(response.content) self.assertEqual(1, len(data)) self.assertIn('odlc', data[0]) self.assertIn('type', data[0]['odlc']) self.assertEqual('STANDARD', data[0]['odlc']['type'])
Example #4
Source File: test_imagefield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def setUp(self): """ Creates a pristine temp directory (or deletes and recreates if it already exists) that the model uses as its storage directory. Sets up two ImageFile instances for use in tests. """ if os.path.exists(temp_storage_dir): shutil.rmtree(temp_storage_dir) os.mkdir(temp_storage_dir) file_path1 = os.path.join(os.path.dirname(__file__), '4x8.png') self.file1 = self.File(open(file_path1, 'rb'), name='4x8.png') file_path2 = os.path.join(os.path.dirname(__file__), '8x4.png') self.file2 = self.File(open(file_path2, 'rb'), name='8x4.png')
Example #5
Source File: test_commands.py From django-cloudinary-storage with MIT License | 6 votes |
def setUpClass(cls): super(BaseOrphanedMediaCommandTestsMixin, cls).setUpClass() set_media_tag(get_random_name()) TestModelWithoutFile.objects.create(name='without file') TestModel.objects.create(name='without file') TestImageModel.objects.create(name='without image') cls.file = cls.add_file_to_model(TestModel(name='with file')).file.name cls.file_2 = cls.add_file_to_model(TestModel(name='with file')).file.name image_model_instance = cls.add_file_to_model(TestImageModel(name='with file and image')) cls.file_removed = image_model_instance.file.name cls.add_file_to_model(image_model_instance) cls.file_removed_2 = image_model_instance.file.name cls.add_file_to_model(image_model_instance) cls.file_3 = image_model_instance.file.name image = ImageFile(open(os.path.join('tests', 'dummy-files', 'dummy-image.jpg'), 'rb')) image_model_instance.image.save(get_random_name(), image) cls.file_4 = image_model_instance.image.name
Example #6
Source File: utils.py From developer-portal with Mozilla Public License 2.0 | 5 votes |
def _store_external_image(image_url: str) -> MozImage: """Download an image from the given URL and store it as a Wagtail image""" response = requests.get(image_url) filename = image_url.split("/")[-1] image = MozImage( title=filename, file=ImageFile(BytesIO(response.content), name=filename) ) image.save() return image
Example #7
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_valid_image(self): """ get_image_dimensions() should catch struct.error while feeding the PIL Image parser (#24544). Emulates the Parser feed error. Since the error is raised on every feed attempt, the resulting image size should be invalid: (None, None). """ img_path = os.path.join(os.path.dirname(__file__), "test.png") with mock.patch('PIL.ImageFile.Parser.feed', side_effect=struct.error): with open(img_path, 'rb') as fh: size = images.get_image_dimensions(fh) self.assertEqual(size, (None, None))
Example #8
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_multiple_calls(self): """ Multiple calls of get_image_dimensions() should return the same size. """ img_path = os.path.join(os.path.dirname(__file__), "test.png") with open(img_path, 'rb') as fh: image = images.ImageFile(fh) image_pil = Image.open(fh) size_1 = images.get_image_dimensions(image) size_2 = images.get_image_dimensions(image) self.assertEqual(image_pil.size, size_1) self.assertEqual(size_1, size_2)
Example #9
Source File: migrate_people.py From hypha with BSD 3-Clause "New" or "Revised" License | 5 votes |
def wagtail_image_obj_from_url(url, drupal_id=None): """ Get the image from the Nesta site if it doesn't already exist. """ if drupal_id is not None and drupal_id: try: return WagtailImage.objects.get(drupal_id=drupal_id) except WagtailImage.DoesNotExist: pass if url and valid_url_extension(url) and valid_url_mimetype(url): r = requests.get(url, stream=True) if r.status_code == requests.codes.ok: img_buffer = BytesIO(r.content) img_filename = url.rsplit('/', 1)[1] # Test downloaded file is valid image file try: pil_image = Image.open(img_buffer) pil_image.verify() except Exception as e: print(f"Invalid image {url}: {e}") else: img = WagtailImage.objects.create( title=img_filename, file=ImageFile(img_buffer, name=img_filename), drupal_id=drupal_id ) return img return None
Example #10
Source File: migrate_projects.py From hypha with BSD 3-Clause "New" or "Revised" License | 5 votes |
def wagtail_image_obj_from_url(url, drupal_id=None): """ Get the image from the Nesta site if it doesn't already exist. """ if drupal_id is not None and drupal_id: try: return WagtailImage.objects.get(drupal_id=drupal_id) except WagtailImage.DoesNotExist: pass if url and valid_url_extension(url) and valid_url_mimetype(url): r = requests.get(url, stream=True) if r.status_code == requests.codes.ok: img_buffer = BytesIO(r.content) img_filename = url.rsplit('/', 1)[1] # Test downloaded file is valid image file try: pil_image = Image.open(img_buffer) pil_image.verify() except Exception as e: print(f"Invalid image {url}: {e}") else: img = WagtailImage.objects.create( title=img_filename, file=ImageFile(img_buffer, name=img_filename), drupal_id=drupal_id ) return img return None
Example #11
Source File: tests.py From cartoview with BSD 2-Clause "Simplified" License | 5 votes |
def test_create_site_logo(self): logo_path = os.path.join(settings.CARTOVIEW_DIR, "static", "cartoview", "img", "cartoview-logo.png") logo = ImageFile(open(logo_path, "rb"), 'cartoview_logo.png') site_logo = SiteLogo.objects.create(site=self.site, logo=logo) self.assertIsNotNone(site_logo) print(site_logo.__str__())
Example #12
Source File: tests.py From pets with MIT License | 5 votes |
def get_test_image_file(filename="test.png"): from six import BytesIO from PIL import Image from django.core.files.images import ImageFile f = BytesIO() image = Image.new("RGB", (200, 200), "white") image.save(f, "PNG") return ImageFile(f, name=filename)
Example #13
Source File: test_models.py From credentials with GNU Affero General Public License v3.0 | 5 votes |
def get_image(self, name): """Get one of the test images from the test data directory.""" return ImageFile(open(TEST_DATA_ROOT + name + '.png'))
Example #14
Source File: factories.py From adhocracy4 with GNU Affero General Public License v3.0 | 5 votes |
def __call__(self, resolution, image_format='JPEG', name=None): filename = name or 'default.{}'.format(image_format.lower()) color = 'blue' image = Image.new('RGB', resolution, color) image_data = BytesIO() image.save(image_data, image_format) image_content = base.ContentFile(image_data.getvalue()) return images.ImageFile(image_content.file, filename)
Example #15
Source File: import_issues.py From WF-website with GNU Affero General Public License v3.0 | 5 votes |
def handle(self, *args, **options): # Get the only instance of Magazine Index Page magazine_index_page = MagazineIndexPage.objects.get() with open(options["file"]) as import_file: issues = csv.DictReader(import_file) for issue in issues: response = requests.get(issue["cover_image_url"]) image_file = BytesIO(response.content) image = Image( title=issue["title"] + " cover image", file=ImageFile(image_file, name=issue["cover_image_file_name"]), ) image.save() import_issue = MagazineIssue( title=issue["title"], publication_date=issue["publication_date"], first_published_at=issue["publication_date"], issue_number=issue["issue_number"], cover_image=image, ) # Add issue to site page hiererchy magazine_index_page.add_child(instance=import_issue) magazine_index_page.save() self.stdout.write("All done!")
Example #16
Source File: importbasics.py From SchoolIdolAPI with Apache License 2.0 | 5 votes |
def downloadFile(url): img_temp = NamedTemporaryFile(delete=True) req = urllib2.Request(url, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36' }) img_temp.write(urllib2.urlopen(req).read()) img_temp.flush() return ImageFile(img_temp)
Example #17
Source File: utils.py From SchoolIdolAPI with Apache License 2.0 | 5 votes |
def shrunkImage(picture, filename): api_key = settings.TINYPNG_API_KEY if not api_key or not filename.endswith('.png'): return picture img_shrunked = NamedTemporaryFile(delete=False) shrink_info = shrink_file( picture.name, api_key=api_key, out_filepath=img_shrunked.name ) img_shrunked.flush() return ImageFile(img_shrunked)
Example #18
Source File: utils.py From SchoolIdolAPI with Apache License 2.0 | 5 votes |
def dataToImageFile(data): image = NamedTemporaryFile(delete=False) image.write(data) image.flush() return ImageFile(image)
Example #19
Source File: utils.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_test_image_file_webp(filename='test.webp', colour='white', size=(640, 480)): f = BytesIO() image = PIL.Image.new('RGB', size, colour) image.save(f, 'WEBP') return ImageFile(f, name=filename)
Example #20
Source File: utils.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_test_image_file_jpeg(filename='test.jpg', colour='white', size=(640, 480)): f = BytesIO() image = PIL.Image.new('RGB', size, colour) image.save(f, 'JPEG') return ImageFile(f, name=filename)
Example #21
Source File: utils.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_test_image_file(filename='test.png', colour='white', size=(640, 480)): f = BytesIO() image = PIL.Image.new('RGBA', size, colour) image.save(f, 'PNG') return ImageFile(f, name=filename)
Example #22
Source File: 0002_auto_20180716_1327.py From DeerU with GNU General Public License v3.0 | 5 votes |
def upload_img(model, name, path): with open(path, 'rb')as f: img = ImageFile(f) a = model(name=name) a.img.save(name, img)
Example #23
Source File: odlcs.py From interop with Apache License 2.0 | 4 votes |
def post(self, request, pk): try: odlc = find_odlc(request, int(pk)) except Odlc.DoesNotExist: return HttpResponseNotFound('Odlc %s not found' % pk) except ValueError as e: return HttpResponseForbidden(str(e)) # Request body is the file f = io.BytesIO(request.body) # Verify that this is a valid image try: i = Image.open(f) i.verify() except IOError as e: return HttpResponseBadRequest(str(e)) if i.format not in ['JPEG', 'PNG']: return HttpResponseBadRequest( 'Invalid image format %s, only JPEG and PNG allowed' % (i.format)) # Clear thumbnail review state. if odlc.thumbnail_approved is not None: odlc.thumbnail_approved = None # Save the thumbnail, note old path. old_path = odlc.thumbnail.path if odlc.thumbnail else None odlc.thumbnail.save('%d.%s' % (odlc.pk, i.format), ImageFile(f)) # ODLC has been modified. odlc.update_last_modified() odlc.save() # Check whether old thumbnail should be deleted. Ignore errors. if old_path and odlc.thumbnail.path != old_path: try: os.remove(old_path) except OSError as e: logger.warning("Unable to delete old thumbnail: %s", e) return HttpResponse("Image uploaded.")
Example #24
Source File: add.py From opensurfaces with MIT License | 4 votes |
def add_photo(path, must_have_fov=False, must_have_exif=False, **args): """ Add a photo to the database """ if not os.path.exists(path): raise ValueError("File does not exist") if 'license' not in args: args['license'] = License.objects.get_or_create( name='All Rights Reserved')[0] # md5: check for duplicates md5 = md5sum(path) duplicate = True try: photo = Photo.objects.get(md5=md5) except Photo.DoesNotExist: duplicate = False except Photo.MultipleObjectsReturned: duplicates = Photo.objects.filter(md5=md5).order_by('id') for d in duplicates[1:]: d.delete() if duplicate: raise ValueError("Duplicate photo import: '%s'" % path) # parse exif if 'exif' not in args: print 'Obtaining EXIF...' exif = get_exif(path) if exif: args['exif'] = exif elif must_have_exif: raise ValueError("Photo has no EXIF: %s" % path) if 'fov' not in args: print 'Obtaining FOV...' fov = get_fov(args['exif']) if fov: args['fov'] = fov elif must_have_fov: raise ValueError("Could not obtain photo FOV: %s" % path) photo = None # use a transaction so that it is only committed to the database # after save() returns. otherwise, there's a small time betwee # when the photo is added and it has an image attached. with transaction.atomic(): with open(path, 'rb') as f: print 'Uploading photo...' photo = Photo.objects.create( image_orig=ImageFile(f), md5=md5, **args ) from mturk.tasks import add_pending_objects_task add_pending_objects_task.delay([get_content_tuple(photo)]) return photo