def pdf2img(self, file): name = os.path.basename(file) print("### Processing {} ###".format(name)) img_list = [] img_buffer = None with WandImage(filename=file, resolution=200) as img: #img_list.append(img) img_buffer = np.asarray(bytearray(img.make_blob()), dtype=np.uint8) if img_buffer is not None: retval = cv2.imdecode(img_buffer, cv2.IMREAD_UNCHANGED) img_list.append(retval) return img_list
def RenderSVGString(svg): if not svg: return svgFile = StringIO.StringIO(svg) try: with WandImage(file=svgFile) as img: img.format = 'png' return img.make_blob() except wand.exceptions.CoderError as e: print('Failed to convert: ' + svg + ': ' + str(e)) except wand.exceptions.MissingDelegateError as e: print('DE Failed to convert: ' + svg + ': ' + str(e)) except wand.exceptions.WandError as e: print('Failed to convert ' + svg + ': ' + str(e))
def is_png_without_transparency(filename): """ Return True, if the given file is a PNG image file without any transparency layer. Usually this means that we could replace the PNG file with a JPG file in order to save storage and bandwidth. """ try: with WandImage(filename=filename) as img: if is_png_image_object(img): return not img.alpha_channel except NOT_AN_IMAGE_WAND_EXCEPTIONS: pass return False
def rainbowify(b: bytes): with WandImage(file=BytesIO(b)) as img: if (img.width * img.height) >= (1200 * 1000): raise commands.BadArgument( "That image is a little too large and may crashy washy my botty wotty 🥺" ) img = Image(b) img.apply_gradient() save_bytes = img.save_bytes() io_bytes = BytesIO(save_bytes) return io_bytes
def gmagik(image): fin = WandImage() ret = BytesIO() with WandImage(file=image) as gif: for f in gif.sequence: with WandImage(image=f) as frame: frame.transform(resize='800x800>') frame.liquid_rescale(width=int(frame.width * 0.5), height=int(frame.height * 0.5), delta_x=1, rigidity=0) frame.liquid_rescale(width=int(frame.width * 1.5), height=int(frame.height * 1.5), delta_x=2, rigidity=0) frame.resize(frame.width, frame.height) fin.sequence.append(frame) fin.save(file=ret) fin.destroy() ret.seek(0) return ret
def assert_pdf_and_images_are_equal(pdf_filename, images, ssim_threshold=0.9985): images_pdf = [] with WandImage(filename=pdf_filename, resolution=150) as pdf: for i, page in enumerate(pdf.sequence): with WandImage(page) as img: img.background_color = WandColor('white') img.alpha_channel = 'remove' blob = img.make_blob(format='bmp') pil_image = PIL.Image.open(BytesIO(blob)).convert(mode='RGB') images_pdf.append(pil_image) images_input = [x.convert(mode='RGB') for x in images] assert len(images_pdf) == len(images_input) # For some reason, the images never match exactly, there seems to be a # subtle (not visible to the human eye) difference. Therefore, we use the # similarity metric SSIM to compare images. # For some examples of SSIM, see the section 'Demonstration' at # http://www.cns.nyu.edu/~lcv/ssim/ for i in range(len(images_pdf)): assert compute_ssim(images_pdf[i], images_input[i]) >= ssim_threshold
def extract_image(zip_data): """Extracts an image from a corrupt zip file inside `zip_data`""" patch_update_crc() with zipfile.ZipFile(BytesIO(zip_data)) as outer: for name in outer.namelist(): try: with zipfile.ZipFile(outer.open(name)) as inner, inner.open( inner.namelist()[0] ) as img_file: # Pillow couldn't read the corrupt gif, even with # PIL.ImageFile.LOAD_TRUNCATED_IMAGES set to True return WandImage(file=img_file) except (zipfile.BadZipFile, WandBaseError): pass
def chroma(image: BytesIO): with WandImage(file=image) as img: if (img.width * img.height) >= (1200 * 1000): raise commands.BadArgument( "That image is a little too large and may crashy washy my botty wotty 🥺" ) img.function("sinusoid", [1.5, -45, 0.2, 0.60]) buffer = BytesIO() img.save(file=buffer) buffer.seek(0) return buffer
def convert_pdf_to_img(blob, img_type="jpg", quality=75, resolution=200): """ Converts PDF with multiple pages into one image. It needs the file content NOT the filename or ioBytes and returns the image content. Note: It has memory leak!! http://stackoverflow.com/a/26233785/1497443 Example: with open('my.pdf', "r") as f: file_content = f.read() # import ipdb # ipdb.set_trace() hh = convert_pdf_to_jpg(file_content) with open('my.jpg', 'wb') as f: f.write(hh) """ from wand.image import Image as WandImage from wand.color import Color as WandColor pdf = WandImage(blob=blob, resolution=resolution) pages = len(pdf.sequence) wimage = WandImage(width=pdf.width, height=pdf.height * pages, background=WandColor("white")) for i in xrange(pages): wimage.composite(pdf.sequence[i], top=pdf.height * i, left=0) if img_type == "jpg": wimage.compression_quality = quality return wimage.make_blob(img_type)
def do_cube(img): with WandImage(blob=img) as image: def s(x): return int(x / 3) image.resize(s(1000), s(860)) image.format = "png" image.alpha_channel = 'opaque' image1 = image image2 = WandImage(image1) out = WandImage(width=s(3000 - 450), height=s(860 - 100) * 3) out.format = "png" image1.shear(background=wand.color.Color("none"), x=-30) image1.rotate(-30) out.composite(image1, left=s(500 - 250), top=s(0 - 230) + s(118)) image1.close() image2.shear(background=wand.color.Color("rgba(0,0,0,0)"), x=30) image2.rotate(-30) image3 = WandImage(image2) out.composite(image2, left=s(1000 - 250) - s(72), top=s(860 - 230)) image2.close() image3.flip() out.composite(image3, left=s(0 - 250) + s(68), top=s(860 - 230)) image3.close() out.crop(left=80, top=40, right=665, bottom=710) buffer = BytesIO() out.save(buffer) buffer.seek(0) return buffer
def process(self, descriptor: StreamDescriptor, context: dict): ensure_wand() # noinspection PyPackageRequirements from wand.image import Image as WandImage # This processor requires seekable stream. descriptor.prepare_to_read(backend='memory') with WandImage(file=descriptor) as img: context.update(width=img.width, height=img.height, content_type=img.mimetype) # prepare for next processor, calling this method is not bad. descriptor.prepare_to_read(backend='memory')
def resize(cls, data, w, h): _img = WandImage(blob=data) # _img.resize(w, h) # return _img.make_blob() if (w / h > _img.width / _img.height): _width = round(h * _img.width / _img.height) _height = h else: _width = w _height = round(w * _img.height / _img.width) _width = int(_width) _height = int(_height) _img.resize(_width, _height) return _img.make_blob()
def test_to_pdf_no_page(): manager = PreviewManager(cache_folder_path=CACHE_DIR, create_folder=True) assert manager.has_pdf_preview(file_path=IMAGE_FILE_PATH, ) is True path_to_file = manager.get_pdf_preview(file_path=IMAGE_FILE_PATH, force=True) assert os.path.exists(path_to_file) is True assert os.path.getsize(path_to_file) > 0 assert re.match(test_utils.CACHE_FILE_PATH_PATTERN__PDF, path_to_file) try: with WandImage(filename=path_to_file) as pdf: assert len(pdf.sequence) == 2 except PolicyError: pytest.skip( 'You must update ImageMagic policy file to allow PDF files')
def test_to_pdf_no_page() -> None: manager = PreviewManager(cache_folder_path=CACHE_DIR, create_folder=True) assert manager.has_pdf_preview(file_path=IMAGE_FILE_PATH) is True path_to_file = manager.get_pdf_preview(file_path=IMAGE_FILE_PATH, force=True) assert os.path.exists(path_to_file) is True assert os.path.getsize(path_to_file) > 0 assert path_to_file == (os.path.join(CACHE_DIR, PDF_FILE_HASH + ".pdf")) try: with WandImage(filename=path_to_file) as pdf: assert len(pdf.sequence) == 2 except PolicyError: pytest.skip( "You must update ImageMagic policy file to allow PDF files")
def trim_image(in_filename: str, out_filename: str or None): if not out_filename: out_filename = in_filename try: with WandImage(filename=in_filename) as img: # noinspection PyTypeChecker img.trim(color=None, fuzz=0) img.save(filename=out_filename) except ImportError: raise exceptions.ImageProcessorException( "ImageMagick is not installed in your system; required for TRIM option." ) except Exception as e: raise exceptions.ImageProcessorException( f"Unhandled exception: {e}")
def do_magic(): i = WandImage(blob=avimg) i.format = 'jpg' #thanks daggy https://github.com/daggy1234/dagpi-image i.virtual_pixel = "mirror" i.resize(250, 250) x, y = i.width, i.height arguments = (0, 0, 77, 153, x, 0, 179, 153, 0, y, 51, 255, x, y, 204, 255) i.distort("perspective", arguments) byt = i.make_blob() im = polaroid.Image(byt) im.resize(500, 500, 1) file = discord.File(BytesIO(im.save_bytes()), filename="magik.jpg") return file
def do_magic(): i = WandImage(blob=avimg) i.format = 'jpg' i.liquid_rescale(width=int(i.width * 0.5), height=int(i.height * 0.5), delta_x=int(0.5 * scale) if scale else 1, rigidity=0) i.liquid_rescale(width=int(i.width * 1.5), height=int(i.height * 1.5), delta_x=scale if scale else 2, rigidity=0) byt = i.make_blob() im = polaroid.Image(byt) im.resize(500, 500, 1) file = discord.File(BytesIO(im.save_bytes()), filename="magik.jpg") return file
def ocr_image(input_file, language, sharpen=False, timeout=20): """ :param input_file: str Path to image to prettify :return: str """ with io.BytesIO() as transfer: with WandImage(filename=input_file) as img: if sharpen: img.auto_level() img.sharpen(radius=0, sigma=4.0) img.contrast() img.save(transfer) with Image.open(transfer) as img: return pytesseract.image_to_string(img, lang=language, timeout=20)
def resize_img(file1, content): img = WandImage(filename=file1) if (img.width > 1920): img.resize(width=1920) if (img.height > 1080): img.resize(height=1080) img.format = "png" stream_out = six.BytesIO() img.alpha_channel = 'remove' img.save(file=stream_out) picture = Image() picture.content = content picture.image.save(name="content" + str(content.pk) + ".png", content=stream_out) picture.save() os.remove(file1)
def is_image(filename, not_image_ext=[]): """ Return True, if the given file is an image file. """ ext = get_ext(filename) if ext == 'pdf': return False if ext in not_image_ext: return False try: with WandImage(filename=filename) as img: return True except NOT_AN_IMAGE_WAND_EXCEPTIONS: return False
def _do_convert(self, src, dst, max_file_size, max_img_size): dst.parent.mkdir(parents=True, exist_ok=True) with WandImage(filename=src) as img_src: with img_src.clone() as img_dst: img_dst.format = 'jpeg' if max_file_size is not None: img_dst.options['jpeg:extent'] = max_file_size if max_img_size is not None: w, h = img_dst.size mw, mh = max_img_size rww, rhw = mw, int(h * mw / w) rwh, rhh = int(w * mh / h), mh rw, rh = min(w, rww, rwh), min(h, rhw, rhh) if (rw < w) or (rh < h): img_dst.resize(rw, rh) img_dst.save(filename=dst)
def magik(image): with WandImage(file=image) as img: ret = BytesIO() img.liquid_rescale(width=int(img.width * 0.4), height=int(img.height * 0.4), delta_x=1, rigidity=0) img.liquid_rescale(width=int(img.width * 1.6), height=int(img.height * 1.6), delta_x=2, rigidity=0) img.save(file=ret) ret.seek(0) return ret
def rotate_image(input_file, output_file, angle=90): """ :param input_file: str Path to image to rotate :param output_file: str Path to output image :param angle: float Angle to rotate :return: void Rotates image and saves result """ print(ORANGE + '\t~: ' + RESET + 'Rotate image' + RESET) with WandImage(filename=input_file) as img: with img.clone() as rotated: rotated.rotate(angle) rotated.save(filename=output_file)
def make_gif(self, frames): anim = WandImage() for image in frames: anim.sequence.append(image) for n in xrange(len(anim.sequence)): with anim.sequence[n] as frame: frame.delay = config.frame_duration_ms / 10 anim.format = 'gif' anim.type = 'optimize' stream = BytesIO() anim.save(file=stream) stream.seek(0) return stream
def createThumb(file, thumbnail): """ Open the comic file and generate a jpeg thumbnail of the first page """ cover = None try: index = 0 kind = filetype.guess(file) if kind is None: logger.error("File type unknown {}".format(file)) return False if kind.mime == 'application/zip': zip = zipfile.ZipFile(file,'r') #find the first image filelist = sorted(zip.namelist()) while not (filelist[index].endswith(".jpg") or filelist[index].endswith(".jpeg") or filelist[index].endswith(".JPG") or filelist[index].endswith(".png")): index += 1 cover = io.BytesIO(zip.read(filelist[index])) zip.close() elif kind.mime == 'application/x-rar-compressed': rar = rarfile.RarFile(file,'r') #find the first image filelist = sorted(rar.namelist()) while not (filelist[index].endswith(".jpg") or filelist[index].endswith(".jpeg") or filelist[index].endswith(".JPG") or filelist[index].endswith(".png")): index += 1 cover = io.BytesIO(rar.read(filelist[index])) rar.close() elif kind.mime == 'application/pdf': with WandImage(filename=file+"[0]") as original: original.transform(resize="{}x{}>".format(thumbsize[0], thumbsize[1])) original.save(filename=thumbnail) return True else: logger.error("File format not handled {} {}".format(kind.mime, file)) return False im = Image.open(cover) im.thumbnail(thumbsize) im.save(thumbnail, "JPEG") return True except: logger.error("Cannot create thumbnail {} for {}".format(thumbnail, file)) logger.error(traceback.format_exc()) return False
def _createMask(self, page=None): w, h = self.pagesize w = float(w) h = float(h) shps = self.hps * self.scale svps = self.vps * self.scale io = BytesIO() c = canvas.Canvas(io, pagesize=(w, h)) c.setStrokeColorRGB(*self.colour) c.setFillColorRGB(*self.colour) allDots = [] for x_ in range(int(w / shps / 72 + 1)): for y_ in range(int(h / svps / 72 + 1)): for xDot, yDot in self.proto: x = (x_ * shps + xDot * self.scale) y = (y_ * svps + yDot * self.scale) if x * 72 > w or y * 72 > h: continue allDots.append((x, y)) if "wand" in globals() and page != None: # PyPDF2 page to cv2 image dpi = 300 pageio = BytesIO() pageWriter = PdfFileWriter() pageWriter.addPage(page) pageWriter.write(pageio) pageio.seek(0) with WandImage(file=pageio, format="pdf", resolution=dpi) as wim: imbin = wim.make_blob("png") file_bytes = np.asarray(bytearray(imbin), dtype=np.uint8) im = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) # remove dots on black spots allDots = [ (x, y) for x, y in allDots if int(y * dpi) >= im.shape[0] or int(x * dpi) >= im.shape[1] or (im[int(y * dpi), int(x * dpi)] != (0, 0, 0)).any() ] for x, y in allDots: c.circle(x * 72, h - y * 72, self.dotRadius * 72, stroke=0, fill=1) c.showPage() c.save() io.seek(0) return io.read()
def auto_fit_image_object(img, width, height, bg_color): """ Automatically fit the given input image into a canvas with the given background color that satisfies the aspect ratio of the target width and height but is just big enough to 'fit' the input image in. """ # invalid target size? if width == 0 or height == 0: return img # colorspace we cannot work with if img.colorspace == 'cmyk': return img # get input image size img_w, img_h = img.size # aspect ratio of the target size and image size ar = float(width) / float(height) img_ar = float(img_w) / float(img_h) # aspect ratio is already almost perfect? if abs(ar - img_ar) < 0.05: return img # try image width w = img_w h = int(w / ar) x = 0 y = int((float(h) - float(img_h)) / 2.0) # if the height is too short, then the other way around must fit... if h < img_h: h = img_h w = int(h * ar) x = int((float(w) - float(img_w)) / 2.0) y = 0 # create a new image of the resolved target size in the given # background color result_img = WandImage(width=w, height=h, background=WandColor(bg_color)) result_img.composite(img, x, y) img.destroy() return result_img
def brighten_image(b: bytes, amount: int): with WandImage(file=BytesIO(b)) as img: if (img.width * img.height) >= (1200 * 1000): raise commands.BadArgument( "That image is a little too large and may crashy washy my botty wotty 🥺" ) image = Image(b) if (image.width * image.height) >= (1200 * 1000): raise commands.BadArgument( "That image is a little too large and may crashy washy my botty wotty 🥺" ) image.brighten(amount) save_bytes = image.save_bytes() io_bytes = BytesIO(save_bytes) return io_bytes
def sharpen_image(input_file, output_file): """ :param input_file: str Path to image to prettify :param output_file: str Path to output image :return: void Prettifies image and saves result """ rotate_image(input_file, output_file) # rotate print(ORANGE + '\t~: ' + RESET + 'Increase image contrast and sharp image' + RESET) with WandImage(filename=output_file) as img: img.auto_level() img.sharpen(radius=0, sigma=4.0) img.contrast() img.save(filename=output_file)
def SVGStringToImageBlob(svg): if not svg: return svgFile = io.StringIO(svg) try: with WandImage(file=svgFile) as img: img.background_color = WandColor('white') img.alpha_channel = 'remove' # Convert to black and white img.negate() img.threshold(0) img.format = 'png' return img.make_blob() except wand.exceptions.CoderError as e: print(('Failed to convert: ' + svg + ': ' + str(e))) except wand.exceptions.MissingDelegateError as e: print(('DE Failed to convert: ' + svg + ': ' + str(e))) except wand.exceptions.WandError as e: print(('Failed to convert ' + svg + ': ' + str(e)))