def save(self, *args, **kwargs): if self.image: #open image pil_image_obj = Image.open(self.image) img_size = pil_image_obj.size if float(img_size[0]) > 500: new_image = resizeimage.resize_width(pil_image_obj, 500) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = self.image.name self.image.delete(save=False) self.image.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) if self.image_slurp: print("image slurp") imgRequest = request.urlopen(self.image_slurp) if imgRequest.status == 200: file_name = self.image_slurp.split('/')[-1] img_temp = NamedTemporaryFile() img_temp.write(imgRequest.read()) img_temp.flush() img_file = File(img_temp) pil_image_obj = Image.open(img_temp) img_size = pil_image_obj.size if float(img_size[0]) > 500: new_image = resizeimage.resize_width(pil_image_obj, 500) else: new_image = pil_image_obj new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = file_name self.image_slurp = None self.image.delete(save=False) self.image.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) super(Article, self).save(*args, **kwargs)
def resize(im, crop, limit): """ Resize image to limit if limit > 0 if crop_square, and height and width are within 9 % crop to smaller dimension """ width = im.width height = im.height if width == height: size = width if 0 < limit < width: size = limit im = resizeimage.resize_width(im, size) elif width > height: size = height if 0 < limit < height: size = limit if crop and (width - height) / width < 0.09: im = resizeimage.resize_crop(im, [size, size]) else: im = resizeimage.resize_width(im, size) elif height > width: size = width if limit and width > limit: size = limit if crop and (height - width) / height < 0.09: im = resizeimage.resize_crop(im, [size, size]) else: im = resizeimage.resize_height(im, size) return im
def save(self, *args, **kwargs): # exif情報を持っている場合イメージをローテートする rotate_image(self.foot_left) # 左足イメージのサイズ調整 left_pil_image_obj = Image.open(self.foot_left) left_pil_image_obj = left_pil_image_obj.convert("RGB") left_new_image = resizeimage.resize_width(left_pil_image_obj, 500) left_new_image_io = BytesIO() left_new_image.save(left_new_image_io, format="JPEG") left_temp_name = self.foot_left.name self.foot_left.delete(save=False) self.foot_left.save( left_temp_name, content=ContentFile(left_new_image_io.getvalue()), save=False, ) # exif情報を持っている場合イメージをローテートする rotate_image(self.foot_right) # 右足イメージのサイズ調整 right_pil_image_obj = Image.open(self.foot_right) right_pil_image_obj = right_pil_image_obj.convert("RGB") right_new_image = resizeimage.resize_width(right_pil_image_obj, 500) right_new_image_io = BytesIO() right_new_image.save(right_new_image_io, format="JPEG") right_temp_name = self.foot_right.name self.foot_right.delete(save=False) self.foot_right.save( right_temp_name, content=ContentFile(right_new_image_io.getvalue()), save=False, ) super(FootImage, self).save(*args, **kwargs)
def test_can_not_resize_larger_width(self): """ Test that resizing an image with resize_width to a size larger than the original raises an error """ with self._open_test_image() as img: with self.assertRaises(ImageSizeError): resizeimage.resize_width(img, 801)
def handle_click(): for root,dirs,file in os.walk(imageOptimizeDirectory): for image in file: if image.endswith(('jpg', 'png' )) and not "optimized_" in image and not "thumb_" in image : img = Image.open(os.path.join(root,image)) img = resizeimage.resize_width(img, int(maxWidth), validate=False) img.save(os.path.join(root,optimizedPrefix+image), optimize=True, quality=int(OptimizationLevel)) img = resizeimage.resize_width(img, int(maxWidthThumbnail), validate=False) img.save(os.path.join(root,ThumbnailPrefix+image)) MessageBox(None, 'All images optimized!', 'Success!', 0) sys.exit(0)
def resizeImages(productDirectory, folderSizes): import shutil # Find all the images in the given directory productImages = loadIms(productDirectory) for x, prdImage in enumerate(productImages): print("Image {} out of {}".format(x + 1, len(productImages))) filename = os.path.basename(prdImage) # direcname = os.path.dirname(prdImage) with open(prdImage, 'r+b') as imageFile: # Create a new image for each of the given sizes for outdir in folderSizes: # The given size is used for the width baseWidth = int(outdir) # We need a folder for each size, create if it doesn't exist already outdirPath = os.path.join(productDirectory, outdir) if not os.path.exists(outdirPath): print("Creating {} ..".format(outdirPath)) os.makedirs(outdirPath) pathResizedImage = os.path.join(productDirectory, outdir, filename) print("Generating for {} ..".format(outdirPath)) with Image.open(imageFile) as image: currentWidth, _ = image.size if currentWidth > baseWidth: cover = resizeimage.resize_width(image, baseWidth) cover.save(pathResizedImage, image.format) else: print( "Image smaller than resize. Copying unmodified {} to {}" .format(prdImage, pathResizedImage)) shutil.copy(prdImage, pathResizedImage)
def result_image(url, left, top, right, bottom): """ Returns a resized image of PDF page based on bounding box """ response = requests.get(url) byte_array = Image.open(BytesIO(response.content)) # Size of the image in pixels (size of orginal image) # (This is not mandatory) width, height = byte_array.size im1 = byte_array.crop((left, top, right, bottom)) # Shows the image in image viewer filename = "result.png" new_image = resizeimage.resize_width(im1, im1.width) new_image_io = BytesIO() new_image.save(new_image_io, format='PNG') final_image = ContentFile(new_image_io.getvalue()) doc_page = DocumentPages( pdf=Document.objects.get(pk=1), page=42, image=InMemoryUploadedFile( final_image, # file None, # field_name filename, # file name 'image/png', # content_type final_image.tell, # size None)) # co) doc_page.save() link = 'https://discussai.blob.core.windows.net/media/' + doc_page.image.name return link im1.show()
def make_small_file(photo_id): """ Task for making small photo :param photo_id: :return: """ from app.models import Photo photo = Photo.objects.get(pk=photo_id) image = photo.original_file file_name = image.name.split('/')[-1] image_obj = Image.open(image) file_format = image_obj.format width, height = image_obj.size image_obj.convert('RGB') if width > height: image_obj = resizeimage.resize_width(image_obj, 150) else: image_obj = resizeimage.resize_height(image_obj, 150) thumb_io = BytesIO() image_obj.save(thumb_io, file_format, quality=90) file_object = File(thumb_io, name=file_name) photo.small_file = file_object photo.save()
def resize(source_image, target_image): source_image_path = os.path.join(IMAGES_DIR, source_image) target_image_path = os.path.join(IMAGES_DIR, target_image) with open(source_image_path, 'rb') as fd_img: img = Image.open(fd_img) img = resizeimage.resize_width(img, 98) img.save(target_image_path)
def resize(filepath): fd = open(filepath, 'r') img = Image.open(fd) # hardcoded size based on website layyout img = resizeimage.resize_width(img, 540) img.save(filepath, img.format) fd.close()
def resize(self, width, height, name='', type='width'): output = os.path.join(self.cdir, self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext) with open(self.src, 'r+b') as f: with Image.open(f) as image: if type == 'contain': try: result = resizeimage.resize_cover(image, [width, height]) except: tmp = resizeimage.resize_contain(image, [width, height]) result = resizeimage.resize_cover(tmp, [width, height]) elif type == 'height': result = resizeimage.resize_height(image, height, validate=False) elif type == 'crop': tmp = resizeimage.resize_contain(image, [width + 150, height + 150]) result = resizeimage.resize_crop(tmp, [width, height]) elif type == 'tcrop': tmp = resizeimage.resize_contain(image, [width, height]) result = resizeimage.resize_crop(tmp, [width, height]) elif type == 'thumbnail': result = resizeimage.resize_thumbnail(image, [width, height]) else: result = resizeimage.resize_width(image, width, validate=False) result.save(output, optimize=True) return [output, '[{}x{}] {}'.format(width, height, name), self.name + '-' + str(width) + 'x' + str(height) + '-' + name + self.ext, name]
def resizeImg(fileName): #ปรับขนาดรูป for name in glob.glob('temp/' + fileName[0] + ".png"): with open(name, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_width(image, 148) cover = resizeimage.resize_cover(image, [148, 165]) cover.save(name, image.format)
def save(self, *args, **kwargs): try: pil_image_obj = Image.open(self.picture) new_image = resizeimage.resize_width(pil_image_obj, 150) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') # Get MetaData for the Save orig_picture_name = self.name orig_picture_name = orig_picture_name.replace(" ", "_") team = self.manager.team team = team.replace(" ", "_") temp_name = '' + team + '_' + orig_picture_name + '.jpg' self.picture.delete(save=False) self.picture.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) except: #temp_name = None # Handle Null Setting of Image (Clear Route) super(Player, self).save() # if temp_name is None: # super(Player, self).save() # #super(Player, self).clean(*args, **kwargs) # else: # If Not save the in memory image to disk ans set it to db super(Player, self).save(*args, **kwargs)
def standard_resize_image(filename): img_file = open(filename, 'rb') img = Image.open(img_file) if img.size[0] > container.file_width: img = resizeimage.resize_width(img, container.file_width) img.save(filename, img.format) img_file.close()
def resize_image(file: pathlib.Path, indir: pathlib.Path, outdir: pathlib.Path, width=None, height=None, verbose=False): assert width or height, "At least height or width must be specified" if verbose: print("Opening file {}".format(file)) with Image.open(file.resolve()) as img: if width and height: resized = resizeimage.resize_thumbnail(img, [width, height]) elif width: resized = resizeimage.resize_width(img, width) else: resized = resizeimage.resize_height(img, height) if verbose: print("File {} resized. Will save it.".format(file)) final_path = file.relative_to(indir) final_path = outdir.joinpath(final_path) if not final_path.parent.exists(): final_path.parent.mkdir(parents=True) resized.save(final_path, resized.format) if verbose: print("Saved resized version of {} to {}".format(file, final_path))
def grey(): im = Image.open("./test_image.png") im = im.crop((0, 0, 288, 288)) cover = resizeimage.resize_width(im, 50) # print(cover.size) cover.save("test_image.png")
def resize_image(image_path, output_dir): ''' :param image_path: str, path to image :param output_dir: str, path to destination directory saving the resized image :return: boolean, indicate if image exists and is valid ''' image_exist = False if os.path.exists(image_path): file_info = os.stat(image_path) if file_info.st_size < 15424400: image_exist = True else: return image_exist with open(image_path, 'r+b') as f: image = Image.open(f) width, height = image.size if width >= height: if width > 640: width = 640 image = resizeimage.resize_width(image, width) else: if height > 640: height = 640 image = resizeimage.resize_height(image, height) # create new resized image at output_dir image.save(output_dir + os.path.basename(image_path), image.format) return image_exist
def setViewingPanelImage(self, pilImage): if hasattr(self, "lastPilImage"): if PIL.ImageChops.difference(pilImage, self.lastPilImage).getbbox() is None: # pylint: disable=E0203 return else: self.lastPilImage.close() # pylint: disable=E0203 # only gets to this point if the image is not the same as last time # resize image to width keeping aspect ratio pilImage = resizeimage.resize_width(pilImage, self.imageViewWidth) # make this the lastpilimage (ie current) self.lastPilImage = pilImage # create wximage from pil image wxImg = wx.Image(*pilImage.size) pilRgbStr = pilImage.convert( "RGB").tobytes() # no transparency supported wxImg.SetData(pilRgbStr) # resize to small image so it is not too big in the panel # the 400 and 250 need to be changed if the panel needs to be resized currentImage = wxImg.ConvertToBitmap() dc = wx.MemoryDC(currentImage) dc.DrawBitmap(currentImage, 0, 0) bitmapToAdd = wx.StaticBitmap(parent=self, id=wx.ID_ANY, bitmap=currentImage) if len(self.viewingPanelSizer.GetChildren()) != 0: # not first time adding it self.viewingPanelSizer.Remove(self.lastViewingBitmap) # pylint: disable=E0203 self.viewingPanelSizer.Insert(0, bitmapToAdd, 0, wx.ALL, 10) # first 0 is index, 10 is border self.Layout() self.lastViewingBitmap = bitmapToAdd
def get_gray_img(frame, data, is_square, img_width, img_height): x, y, w, h = data img = Image.fromarray(frame[y:y+h, x:x+w]) if is_square: return resizeimage.resize_cover(img, [img_width, img_height]) else: width_scaled_img = resizeimage.resize_width(img, img_width) return resizeimage.resize_crop(width_scaled_img, [img_width, img_height])
def create_thumb(dirpath, imgname): """write a thumbnail of the image to the output dir""" with open(join(dirpath, imgname), 'r+b') as f: with Image.open(f) as image: thumb = resizeimage.resize_width(image, 50) thumbpath = join(outdir, thumbdir, imgname) print("saving thumbnail to", thumbpath) thumb.save(thumbpath, image.format)
def resize(pixel_size, icon_extension, magnitude): dir_path = os.path.dirname(os.path.realpath(__file__)) + "/icon_bundle" if not os.path.exists(dir_path): os.makedirs(dir_path) fd_img = open('image.png', 'r') img = Image.open(fd_img) img = resizeimage.resize_width(img, pixel_size) img.save(dir_path+'/Icon-%d%s.png' %(icon_extension,magnitude), img.format) fd_img.close()
def resize(): ''' Resize images found in the "large" images directory. medium: 1200px wide small: 300px wide ''' images_directory = os.path.join('static', 'images') # First clear out any resizing work we may have done. clear_resized_images(images_directory) try: for entry in os.scandir(images_directory): orig_images = os.path.join(images_directory, entry.name, 'large') for orig_image in os.scandir(orig_images): with open(os.path.join(orig_images, orig_image.name), 'r+b') as f: with Image.open(f) as large_image: med_image = resizeimage.resize_width(large_image, 1200) med_image.save( os.path.join(images_directory, entry.name, 'medium', orig_image.name)) # small ones need to be a uniform 300px by 199px (WxH) so portrait ones will be center cropped if large_image.height > large_image.width: small_image = resizeimage.resize_width( large_image, 300) small_image = resizeimage.resize_crop( small_image, [300, 199]) else: small_image = resizeimage.resize_width( large_image, 300) small_image.save( os.path.join(images_directory, entry.name, 'small', orig_image.name)) except OSError as ex: raise Exception( "Error encountered while trying to resize images. {0}".format(ex)) return
def resize_width(img_path, width: int): img_path = img_path[1:] path, filename = os.path.split(img_path) new_path = os.path.join(path, "resized", f"w{width}_{filename}") if FORCE_RESIZE or not os.path.exists(new_path): img = Image.open(img_path) img = resizeimage.resize_width(img, width) img.save(new_path, img.format) return f"/{new_path}"
def on_series_select(self, evt): ''' Callback function for event in self.lb_series i.e when user selects a series in the listbox actions: 1. Find out number of channels for this series 2. Create as many sub-frames in bottomf as there are channels ''' w = evt.widget index = int(w.curselection()[0]) self.series_indx = index # Index of series (for later use) self.series_name = w.get(index) # Folder name corresponding to selected series: self.series_folder_name = 'S{:0>2d}'.format(index + 1) + '_' + self.series_name # Display number of channels in listbox self.nchans = self.md['Nchan'][index] # Number of channels in series CHANNELS = ['Channel ' + str(x + 1) for x in range(self.nchans)] self.lb_chan.delete(0, 'end') # Clear listbox self.lb_chan.insert('end', *CHANNELS) # Clear content of bottomf for w in self.bottomf.winfo_children(): w.destroy() # Dictionnary to dynamically hanle sub-frames instances (one sub-frame/channel) lst = ['self.chan' + str(x) + 'f' for x in range(self.nchans)] self.subframe_dict = {i: lst[i] for i in range(0, len(lst))} # Dictionnary to dynamically handle label instances in sub-frames lst = ['self.chan' + str(x) + 'f_label' for x in range(self.nchans)] self.subframe_lab_dict = {i: lst[i] for i in range(0, len(lst))} # Dictionnary to dynamically handle projection images lst = ['self.im_' + str(x) for x in range(self.nchans)] self.subframe_im_dict = {i: lst[i] for i in range(0, len(lst))} # Dictionnary to dynamically handle scale instances # Name is made simple (e.g. self.scale_0 for first channel) # So that channel index can be extracted from name of scale instance lst = ['self.scale_' + str(x) for x in range(self.nchans)] self.subframe_scale_dict = {i: lst[i] for i in range(0, len(lst))} # Dictionnary to dynamically handle check buttons and associated booleans lst = ['self.check_' + str(x) for x in range(self.nchans)] self.subframe_check_dict = {i: lst[i] for i in range(0, len(lst))} lst = ['self.booleanvar_' + str(x) for x in range(self.nchans)] self.subframe_booleanvar_dict = {i: lst[i] for i in range(0, len(lst))} for i in range(len(lst)): self.subframe_booleanvar_dict[i] = BooleanVar() for i in range(len(lst)): # Create sub-frames in bottomf self.subframe_dict[i] = Frame(self.bottomf, width=self.width // self.nchans, bg=self.bg_col) self.subframe_dict[i].pack(side='left', fill='both', padx=10, pady=0, expand=True) # Grab and resize projection images: im_file = os.path.join(os.path.split(self.fullpath)[0], self.series_folder_name, 'z_proj_chan' + str(i + 1) + '.png') if os.path.exists(im_file): im = Image.open(im_file) self.subframe_im_dict[i] = resizeimage.resize_width(im, math.floor( 0.9 * self.width) // self.nchans)
def compress(self, filename): im = Image.open(filename) max_width = 720 if im.size[0] > max_width: im = resizeimage.resize_width(im, max_width) im_io = BytesIO() im.save(im_io, 'JPEG', quality=60) new_image = File(im_io, name=filename.name) return new_image
def resize_and_optimize(imagefile, imagename: str, subfolder: str, width: int, shall_optimize: bool, optimizationgrade: int): img = resizeimage.resize_width(imagefile, width, validate=False) path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'site', 'images', subfolder) if not os.path.exists(path): os.makedirs(path) img.save(os.path.join(path, imagename), optimize=shall_optimize, quality=optimizationgrade)
def resizeImageIntoSquare(original_img_name): original_img=open(original_img_name,'rb') new_img=Image.open(original_img) new_img=resizeimage.resize_width(new_img,450) longer_side=max(new_img.size) horizontal_padding=(longer_side-new_img.size[0])/2 vertical_padding=(longer_side-new_img.size[1])/2 new_img=new_img.crop((-horizontal_padding,-vertical_padding,new_img.size[0] + horizontal_padding,new_img.size[1] + vertical_padding)) new_img.convert('RGB').save("img_02.png", "PNG", optimize=True) original_img.close()
def resizeImage(url: str, width: int): ''' resize the image from the url to the width stated \n url: the url of the image \n width: int: the image will be resized to this width (measured in pixels) ''' from resizeimage import resizeimage img = imageFromUrl(url) resizedImg = resizeimage.resize_width(img, 200) return resizedImg
def upload(): if request.method == "POST": target = os.path.join( APP_ROOT, '/var/www/homeDelicious/home_delicious_frontend/dist/img/uploadImgs' ) # target = os.path.join(APP_ROOT, '/Users/Taylo/InnoTech/Assignments/Project/Home delicious/home_delicious_frontend') if not os.path.isdir(target): os.mkdir(target) files = request.files.getlist("file") for file in files: # print(file) filename = file.filename destination = "/".join([target, filename]) print(destination) file.save(destination) image = Image.open(destination) if image.width > 1280 and image.height < 1280: with open(destination, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_width(image, 1280) cover.save(destination, image.format) elif image.width < 1280 and image.height > 1280: with open(destination, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_height(image, 1280) cover.save(destination, image.format) elif image.width > 1280 and image.height > 1280: with open(destination, 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_cover(image, [1280, 1280]) cover.save(destination, image.format) return Response(json.dumps(destination, default=str), mimetype="application/json", status=204) if __name__ == "__main__": app.run(port=4555, debug=True) if request.method == "DELETE": image = request.json.get("image") print(image) path = "/var/www/homeDelicious/home_delicious_frontend/dist/img/uploadImgs/" image_path = path + image print(image_path) if os.path.exists(image_path): os.remove(image_path) if os.path.exists(image_path): return Response("Delete went wrong!", mimetype="text/html", status=500) else: return Response("Delete sucess", mimetype="application/json", status=200) else: print("The file does not exist")
def crop_image( image_base64: str, png_image_quality: int = IMAGE_QUALITY_PNG ) -> str: """ Crop an image, encoded in Base64. Args: image_base64: Image encoded in Base64 Kwargs: png_image_quality: PNG image quality (defaults to 6) Returns: PNG image (possibly cropped) encoded in Base64 """ img: Image.Image = Image.open(BytesIO(base64.b64decode(image_base64))) img_width: int img_height: int img_width, img_height = img.size cropped_image_base64: str # Image is too small if img_width < IMAGE_WIDTH_DESKTOP or img_height < IMAGE_HEIGHT_DESKTOP: raise ValidationError( "Image is too small (min {} x {} pixels): {} x {} pixels".format( IMAGE_WIDTH_DESKTOP, IMAGE_HEIGHT_DESKTOP, img_width, img_height, ) ) # Image is too big elif img_width > IMAGE_WIDTH_DESKTOP or img_height > IMAGE_HEIGHT_DESKTOP: # Image is too wide if (img_width / img_height) > ( IMAGE_WIDTH_DESKTOP / IMAGE_HEIGHT_DESKTOP ): img = resizeimage.resize_height(img, IMAGE_HEIGHT_DESKTOP) # Image is too high (and wide) else: img = resizeimage.resize_width(img, IMAGE_WIDTH_DESKTOP) img = img.crop((0, 0, IMAGE_WIDTH_DESKTOP, IMAGE_HEIGHT_DESKTOP)) buffered = BytesIO() img.save( buffered, format="PNG", compress_level=png_image_quality ) # [0, 9], where 0 = no compression and 9 = best compression, defaults to 6 cropped_image_base64 = base64.b64encode(buffered.getvalue()).decode( "utf-8" ) # Image dimensions are correct (use the original image) else: cropped_image_base64 = image_base64 return cropped_image_base64
def main(): # Measures total program runtime by collecting start time start_time = time() max_width = 960 max_height = 960 folder = 'uploaded_images' for filename in listdir(folder): filepath = "%s/%s" % (folder, filename) if not filename.endswith('.jpg'): continue size_slug = "contain%dx%d" % (max_width, max_height) new_filename = "%s.%s.%s" % (filename.split('.')[0], size_slug, filename.split('.')[-1]) new_filepath = "%s/%s" % (folder, new_filename) replace_file = False if filename == new_filename or path.isfile(new_filepath): print("File %s already exists, skipping file" % (new_filename)) continue with open(filepath, 'r+b') as file: with Image.open(file) as image: if image.width <= max_width and image.height <= max_height: print("File %s already resized, skipping file" % (filename)) else: print('Resizing image %s => %s' % (filename, new_filename)) if image.width > image.height: resized = resizeimage.resize_width(image, max_width) else: resized = resizeimage.resize_height(image, max_height) resized.convert('RGB').save(new_filepath, image.format) replace_file = True if replace_file: remove(filepath) rename(new_filepath, filepath) # Measure total program runtime by collecting end time end_time = time() # Computes overall runtime in seconds & prints it in hh:mm:ss format tot_time = end_time - start_time # calculate difference between end time and start time print( "\n** Total Elapsed Runtime:", str(int((tot_time / 3600))) + ":" + str(int( (tot_time % 3600) / 60)) + ":" + str(int((tot_time % 3600) % 60)))
def get_screenshot(self, trello_card, in_flask=False): attachment = self.trello.cards.get_attachment(trello_card['id']) try: # if an attachment exists and its an image # do not get a screenshot if attachment[0]["url"][-3] == 'png': return attachment[0]["url"] else: # if its not an image then raise a key error so # we can hit the exception below and get a screenshot raise KeyError except (KeyError, IndexError): try: url_regex = r'URL: <https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)>' url = re.search( url_regex, str(trello_card['desc'].encode('utf-8'))).group() url = url.strip('URL: <') url = url.strip('>') if in_flask: chrome_options = Options() chrome_options.binary_location = \ os.environ['GOOGLE_CHROME_BIN'] chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(executable_path=str( os.environ.get('CHROMEDRIVER_PATH')), chrome_options=chrome_options) else: driver = webdriver.Chrome(chrome_driver_path) driver.get(url) time.sleep(3) # wait for page to load driver.save_screenshot('lead_screenshot.png') driver.quit() # resize image with open('lead_screenshot.png', 'r+b') as f: with Image.open(f) as image: img = resizeimage.resize_width(image, 600) img.save('lead_screenshot.png', image.format) ss_path = os.path.abspath('lead_screenshot.png') self.upload_file_to_trello_card(trello_card['id'], ss_path) os.remove(ss_path) return self.trello.cards.get_attachment( trello_card['id'])[0]["url"] except AttributeError: card_name = trello_card['name'].encode('utf-8') print(f'Failed to get screenshot for {card_name}') return ''
def test_resize_width(self): """ Test that the image resized with resize_width has the expected size """ with self._open_test_image() as img: img = resizeimage.resize_width(img, 200) filename = self._tmp_filename('resize-width.jpeg') img.save(filename, img.format) with Image.open(filename) as image: self.assertEqual(image.size[0], 200)
def resize_width(width, file_name): name, ext = get_file_ext(file_name) if ext not in ['jpg', 'png', 'jpeg']: return fd_img = open(file_name, 'r') img = Image.open(fd_img) w, h = img.size if w <= width: return img = resizeimage.resize_width(img, width) img.save(name + '_p' + str(width) + '.' + ext, img.format) fd_img.close()
def resize(filepath): exts = ('.jpg', '.jpeg', '.JPG', '.JPEG', '.png', '.PNG', '.gif', '.GIF') if os.path.splitext(filepath)[1] in exts: img = Image.open(filepath) w, h = img.size if w >= 540: # hardcoded size based on website layout try: img = resizeimage.resize_width(img, 540, Image.ANTIALIAS) except: print "Problem with image : " + filepath img.save(filepath, img.format)
def _resize(inpath, outpath, width=None, height=None): with open(inpath, 'r+b') as infile: with Image.open(infile) as inimage: if width and height: thumb = resizeimage.resize_cover(inimage, [width, height]) elif width: thumb = resizeimage.resize_width(inimage, width, validate=True) elif height: thumb = resizeimage.resize_height(inimage, height, validate=True) else: raise RuntimeError('at least width or height must be provided') thumb.save(outpath, inimage.format)
def _resize_image(final_image, width, height): orig_data = io.BytesIO(final_image) with Image.open(orig_data) as image: resized = None if width and height: resized = resizeimage.resize_cover(image, [width, height]) elif width: resized = resizeimage.resize_width(image, width) elif height: resized = resizeimage.resize_height(image, height) resized_data = io.BytesIO() resized.save(resized_data, image.format) final_image = resized_data.getvalue() return final_image
def save(self, *args, **kwargs): if self.image_new == True: pil_image_obj = Image.open(self.car_image) new_image = resizeimage.resize_width(pil_image_obj, 800) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = self.car_image.name self.car_image.delete(save=False) self.car_image.save( temp_name, content=ContentFile(new_image_io.getvalue()), save=False ) else: pass super(Vehicle, self).save(*args, **kwargs)
def resize_image(image): f = open(image, 'r') img = Image.open(f) img = resizeimage.resize_width(img, 1000) img.save(image, img.format) f.close()
def one_dim_resize(folder, file_name): file_path = os.path.join(folder, file_name) im = Image.open(file_path) new_im = resizeimage.resize_width(im, img_width) # use `resize_height` for height changes new_im.save(file_path + "_resized.jpg")
#!/usr/bin/env python import sys import os from PIL import Image from resizeimage import resizeimage import subprocess patho = os.path.join("uploads/"+sys.argv[1]+"/"+sys.argv[2]) fd_img = open(patho, 'r') img = Image.open(fd_img) img = resizeimage.resize_width(img, 500) img.save("uploads/"+sys.argv[1]+"/re-"+sys.argv[2], img.format) fd_img.close() cmd = "python chainer-fast-neuralstyle-master/generate.py"+" uploads/"+sys.argv[1]+"/"+"re-"+sys.argv[2]+" -m"+" chainer-fast-neuralstyle-master/models/"+sys.argv[3]+".model -o"+" processed/"+sys.argv[1]+"/"+sys.argv[3]+sys.argv[2] subprocess.call(str(cmd), shell=True)
def save_locally(self): image_tmp_name = str(self.user_id) + 'tmp' image_tmp_dir = 'app/static/user/img/' print "--- Getting image and saving to directory (%s) from url: \r\n %s" % (image_tmp_dir + image_tmp_name, self.image_url) image_tmp_full_path = os.path.join(image_tmp_dir, image_tmp_name) try: f = open(image_tmp_full_path,'wb') f.write(urllib.urlopen(self.image_url).read()) f.close() try: img_format = imghdr.what(image_tmp_full_path) self.image_type = img_format print "= %s" % (self.image_type) if self.image_type == None: if self.image_url.lower().find('.jpg') >= 0: self.image_type = 'jpg' elif self.image_url.lower().find('.jpeg') >= 0: self.image_type = 'jpeg' elif self.image_url.lower().find('.png') >= 0: self.image_type = 'png' elif self.image_url.lower().find('.gif') >= 0: self.image_type = 'gif' else: print "ERROR... Could not identify image by library or string in url. Saving without extension" self.image_type = '' print "--- Image type: %s" % (self.image_type) except Exception as e: print "Exception ", e.message, e.args print "ERROR Could not detect image type. Saving without extension" self.image_type = '' image_id = str(self.id) image_dir = image_tmp_dir image_original_path = os.path.join(image_dir, image_id + '.' + self.image_type) shutil.copy(image_tmp_full_path, image_original_path) image_large_path = os.path.join(image_dir, image_id + '_large.' + self.image_type) image_thumb_path = os.path.join(image_dir, image_id + '_thumb.' + self.image_type) thumbnail_width = 200 large_width = 1024 fd_img = open(image_tmp_full_path, 'r') # Converting original image to larger width try: print "--- Resizing image to width %s" % large_width img = Image.open(fd_img) img = resizeimage.resize_width(img, large_width) img.save(image_large_path, img.format) print "Saved larger img: %s" % (image_large_path) self.image_large = image_large_path except Exception as e: print "Could resize image since it would require enlarging it. Referencing original path\r\n", e.message, e.args image_large_path = image_original_path print "Saved larger img: %s" % (image_large_path) self.image_large = image_large_path # Converting original image to thumbnail try: print "--- Resizing image to width %s" % thumbnail_width img = Image.open(fd_img) img = resizeimage.resize_width(img, thumbnail_width) img.save(image_thumb_path, img.format) print "Saved thumb img: %s " % (image_thumb_path) except Exception as e: print "ERROR Could resize image since it would require enlarging it. Referencing original path\r\n", e.message, e.args image_thumb_path = image_original_path print "Saved thumb img: %s " % (image_thumb_path) self.image_thumb = image_thumb_path db.session.commit() except Exception as e: print "--- ERROR Could not save tmp image ", e.message, e.args print "Exception ", e.message, e.args