def thumbnail(image_data: io.BytesIO, max_size=(128, 128)) -> None: """Resize an image in place to no more than max_size pixels, preserving aspect ratio.""" with wand.image.Image(blob=image_data) as image: new_resolution = scale_resolution((image.width, image.height), max_size) image.resize(*new_resolution) image_data.truncate(0) image_data.seek(0) image.save(file=image_data) # allow resizing the original image more than once for memory profiling image_data.seek(0)
def convert_image(source_dir, svg_file, img_format, width=None, height=None): """ Convert the svg to png or jpg and scale as directed """ if DEBUG: print(source_dir, svg_file, img_format, str(width), str(height)) if img_format not in IMAGE_FORMATS.keys(): return None if (width and width > MAX_DIMENSION) or (height and height > MAX_DIMENSION): return None real_width = width real_height = height image_result = None if not width or not height: try: doc = minidom.parse(os.path.join(source_dir, svg_file)) except FileNotFoundError: return None svg_width = int(round(float(re.sub("[^0-9.]", "", [path.getAttribute('width') for path in doc.getElementsByTagName('svg')][0])))) svg_height = int(round(float(re.sub("[^0-9.]", "", [path.getAttribute('height') for path in doc.getElementsByTagName('svg')][0])))) doc.unlink() if width and not height: real_height = int(round((float(width) * float(svg_height)/float(svg_width)))) elif height and not width: real_width = int(round((float(height) * float(svg_width)/float(svg_height)))) else: real_width = svg_width real_height = svg_height try: with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) image.read(filename=os.path.join(source_dir, svg_file)) if real_width and real_height: image.resize(real_width, real_height) image_result = image.make_blob(IMAGE_FORMATS[img_format]) except wand.exceptions.BlobError: return None return image_result
def process_file_image(self, doc): """processor for image content-type""" import wand.image image=wand.image.Image(filename=self.get_file_path(doc["file"])) #create jpg thumbnail new_width=200 new_height=(image.height*new_width)//image.width image.resize(new_width, new_height) jpg_image=image.convert("jpg") image.close() jpg_image.save(filename=self.get_thumb_path(doc["file"])) doc["thumbnail"]=self.get_thumb_url(doc["file"]) #ocr to extract text doc["text"]=self.process_ocr(self.get_file_path(doc["file"])) return(doc)
def next_image_and_housekeeping(db, num_labels, label_bias, scale, act_count): """Retrieve the next image to label, and do some housekeeping. Args: db: a label_database.Database object. num_labels: Number of verified labels desired by the user. label_bias: A bias that controls the degree to which we ought to load a new image to label rather than an already-labeled image for verification. scale: amount of scaling to apply to loaded images. action_count: how many labeling actions the user has undertaken in this session prior to now. This function will save the database to disk after every 100 labeling actions. Returns: (None, None) if there are already `num_labels` verified labels in the database. Otherwise, a 2-tuple whose elements are: [0]: filename of an image to label. [1]: wand.image.Image object of the (scaled) image to label. """ # Save the database occasionally, and find out if we have work to do. if (act_count + 1) % 100 == 0: db.save() num_done = db.num_labels_with_counts_of_at_least(2) if num_done >= num_labels: return None, None # Choose an image to label: either a novel one or an unverified one. num_unverified = db.num_labels_with_counts_of(1) fraction_unlabeled = (num_labels - num_done - num_unverified) / num_labels novel_image_probability = fraction_unlabeled * (1 + label_bias) if num_unverified > 0 and random.random() > novel_image_probability: filename = db.random_label_with_count_of(1) # Choose to verify a label. else: filename = db.random_label_with_count_of(0) # Label a novel image. # Attempt to load the image, and scale it. image = wand.image.Image(filename=filename) image.resize(width=round(image.width * scale), height=round(image.height * scale)) return filename, image
def thumbnail(image_data: io.BytesIO, max_size=(128, 128)) -> io.BytesIO: """Resize an image in place to no more than max_size pixels, preserving aspect ratio. Return the new image. """ # Credit to @Liara#0001 (ID 136900814408122368) # https://gitlab.com/Pandentia/element-zero/blob/47bc8eeeecc7d353ec66e1ef5235adab98ca9635/element_zero/cogs/emoji.py#L243-247 with wand.image.Image(blob=image_data) as image: new_resolution = scale_resolution((image.width, image.height), max_size) image.resize(*new_resolution) # we create a new buffer here because there's wand errors otherwise. # specific error: # MissingDelegateError: no decode delegate for this image format `' @ error/blob.c/BlobToImage/353 out = io.BytesIO() image.save(file=out) # allow resizing the original image more than once for memory profiling image_data.seek(0) # allow reading the resized image data out.seek(0) return out
def convert(input_data: str, colourspace: str = "rgb", depth: int = 8, output_format: str = "png", resize=False, keep_aspect=False, resize_filter: wand.image.FILTER_TYPES='lanczos2sharp', compression_quality: int = None): with wand.image.Image(blob=input_data) as image: image.format = output_format if colourspace == "grey": image.type = 'grayscale' image.depth = depth if resize and keep_aspect: image.transform(resize + ">") elif resize: width, height = resize.split("x") image.resize(int(width), int(height)) if compression_quality: image.compression_quality = compression_quality return image.make_blob()
async def resize(imgurl : str, width : int, height : int): """Make an image swole or smoll, ?resize [url] [width] [height]""" imgid = str(randint(1,100)) imgname = "image" + imgid + imgurl[-4:] imgnamer = "image" + imgid + "_r" + imgurl[-4:] await bot.say("Resizing...") #urllib.request.urlretrieve(imgurl, imgname) with aiohttp.ClientSession() as session: async with session.get(imgurl) as resp: with open(imgname, 'wb') as image_file: image_file.write(await resp.content.read()) image_file.close() #await bot.send_file(ctx.message.channel, image_name) #d = urllib.request.urlopen(imgurl) #image_file = io.BytesIO(fd.read()) #im = Image.open(image_file) #imgfile = open(imgname, 'wb') #shutil.copyfileobj(im, imgfile) # with open(imgname, 'r+b') as f: with Image.open(f) as image: image = image.resize((width, height), PIL.Image.NEAREST) image.save(imgnamer) #cover.save(imgnamer, image.format) #output = open(imgname,"wb") #img = Image.open(output) #img = img.resize((int(size), int(size)), PIL.Image.ANTIALIAS) #imgb = img.tobytes() #output.write(imgb) #output.close() await bot.send_file(generalChannel, imgnamer) os.remove(imgname) os.remove(imgnamer)
def square_crop_and_resize(image, size): """Crops an image to be square by removing pixels evenly from both sides of the longest side of the image. Then the image is resized to the desired size""" # Calculate how much longer the longest side is than the shortest. extra = max(image.width, image.height) - min(image.width, image.height) # Remove pixels evenly from the left or top. rem_lt = extra // 2 # Remove pixels evenly from the right or bottom. We may need to take # another single pixel from one side if there is an uneven number of pixels # to split between the two sides. rem_rb = rem_lt + extra % 2 # Crop the image centered so the image is square. if image.width > image.height: image.crop(rem_lt, 0, image.width - rem_rb - 1, image.height - 1) else: image.crop(0, rem_lt, image.width - 1, image.height - rem_rb - 1) assert image.width == image.height image.resize(size, size)
def get_grays(image, width, height): """Convert image to grayscale, downsize to width*height, and return list of grayscale integer pixel values (for example, 0 to 255). >>> get_grays([0,0,1,1,1, 0,1,1,3,4, 0,1,6,6,7, 7,7,7,7,9, 8,7,7,8,9], 5, 5) [0, 0, 1, 1, 1, 0, 1, 1, 3, 4, 0, 1, 6, 6, 7, 7, 7, 7, 7, 9, 8, 7, 7, 8, 9] >>> import os >>> test_filename = os.path.join(os.path.dirname(__file__), 'dhash-test.jpg') >>> with wand.image.Image(filename=test_filename) as image: ... get_grays(image, 9, 9)[:18] [95, 157, 211, 123, 94, 79, 75, 75, 78, 96, 116, 122, 113, 93, 75, 82, 81, 79] """ if isinstance(image, (tuple, list)): if len(image) != width * height: raise ValueError( 'image sequence length ({}) not equal to width*height ({})'. format(len(image), width * height)) return image if wand is None and PIL is None: raise ImportError( 'must have wand or Pillow/PIL installed to use dhash on images') if wand is not None and isinstance(image, wand.image.Image): with image.clone() as small_image: small_image.type = 'grayscale' small_image.resize(width, height) blob = small_image.make_blob(format='RGB') if IS_PY3: return list(blob[::3]) else: return [ord(c) for c in blob[::3]] elif PIL is not None and isinstance(image, PIL.Image.Image): # gray_image = image.convert('L') small_image = image.resize((width, height), PIL.Image.ANTIALIAS) return list(small_image.getdata()) else: raise ValueError( 'image must be a wand.image.Image or PIL.Image instance')
# encoding: utf-8 import os from wand.api import library import wand.color import wand.image base_dir = '/Users/gree2/Downloads/glyph-iconset-master/svg/' file_n = 'si-glyph-abacus.svg' file_i = os.path.join(base_dir, file_n) file_o = os.path.join(base_dir, file_i.replace('.svg', '.png')) with wand.image.Image() as image: with wand.color.Color('transparent') as background_color: library.MagickSetBackgroundColor(image.wand, background_color.resource) with open(file_i) as svg_file: image.read(filename=file_i) # image.read(blob=svg_file.read(), format="svg") image.resize(1024, 1024) png_image = image.make_blob("png32") with open(file_o, "wb") as out: out.write(png_image)
async def shitup(imgurl : str, amount : int): """F**k shit up, ?shitup [image url] [amount] (smaller values = more f****d)""" imgid = str(randint(1,100)) imgname = "image" + imgid + imgurl[-4:] imgnamer = "image" + imgid + "_r" + imgurl[-4:] imgnamer1 = "image" + imgid + "_r2" + imgurl[-4:] await bot.say("Resizing...") #urllib.request.urlretrieve(imgurl, imgname) with aiohttp.ClientSession() as session: async with session.get(imgurl) as resp: with open(imgname, 'wb') as image_file: image_file.write(await resp.content.read()) image_file.close() #await bot.send_file(ctx.message.channel, image_name) #d = urllib.request.urlopen(imgurl) #image_file = io.BytesIO(fd.read()) #im = Image.open(image_file) #imgfile = open(imgname, 'wb') #shutil.copyfileobj(im, imgfile) # with open(imgname, 'r+b') as f: with Image.open(f) as image: origwidth = image.width origheight = image.height image2 = image.resize((amount, amount), PIL.Image.NEAREST) image2.save(imgnamer) with open(imgnamer, 'r+b') as f2: with Image.open(f2) as image: image = image.resize((origwidth, origheight), PIL.Image.NEAREST) image.save(imgnamer1) #cover.save(imgnamer, image.format) #output = open(imgname,"wb") #img = Image.open(output) #img = img.resize((int(size), int(size)), PIL.Image.ANTIALIAS) #imgb = img.tobytes() #output.write(imgb) #output.close() await bot.send_file(generalChannel, imgnamer1) os.remove(imgname) os.remove(imgnamer) os.remove(imgnamer1)
def _imshow(filename): """Show an image file using Sixel graphics.""" image = wand.image.Image(filename=filename) image.resize(width=(image.width * 2), height=(image.height * 2)) sys.stdout.buffer.write(image.make_blob('sixel'))