def _run_convert(filename, page, res=120): idx = page + 1 temp_time = time.time() * 1000 # 由于每次转换的时候都需要重新将整个PDF载入内存,所以这里使用内存缓存 pdfile = getPdfReader(filename) pageObj = pdfile.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 90 img.background_color = Color("white") # 保存图片 img_path = '%s%d.png' % (filename[:filename.rindex('.')], idx) img.save(filename=img_path) img.destroy() img = None pdf_bytes = None dst_pdf = None print('convert page %d cost time %d' % (idx, (time.time() * 1000 - temp_time)))
def _run_convert(filename, page, res=120): '''把pdf指定页码转化为图片''' pdfile, f = get_pdf_reader(filename), open(filename, "rb") # pdfile,f = get_pdf_reader2(filename) if page <= pdfile.getNumPages(): idx = page + 1 temp_time = time.time() * 1000 # 由于每次转换的时候都需要重新将整个PDF载入内存,所以这里使用内存缓存 pageobj = pdfile.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageobj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 90 img.background_color = Color("white") # 保存图片 img_path = 'dest/%s_pg%d.png' % (filename[:filename.rindex('.')], idx) img.save(filename=img_path) img.destroy() img, pdf_bytes, dst_pdf = None, None, None print('convert page %d cost time %dms' % (idx, (time.time() * 1000 - temp_time))) else: print("pg%r list index out of range" % page) f.close()
def generate_sprite(image_dir, images): """ (str, list of Image) -> str Generate sprites with 4 images Returns the name of the generated sprite """ image_width = 160 image_height = 232 sprite = None left_position = 0 for image in images: i = get_resized_image(image=image, width=image_width, height=image_height) if sprite is None: if i.height == i.width: sprite = Image(width=image_width*4, height=image_width, background=Color("#fff")) else: sprite = Image(width=image_width*4, height=image_height, background=Color("#fff")) sprite.composite(image=i, left=left_position, top=0) left_position += image_width i.destroy() sprite_file = "%s/sprite.jpg" % (image_dir) if not isdir(image_dir): makedirs(image_dir) sprite.save(filename=sprite_file) sprite.destroy() return sprite_file
def _run_convert(filename, page, res=120): idx = page + 1 temp_time = time.time() * 1000 # 由于每次转换的时候都需要重新将整个PDF载入内存,所以这里使用内存缓存 pdfile = getPdfReader(filename) pageObj = pdfile.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 90 img.background_color = Color('white') img.alpha_channel = 'remove' #img.channels = 'rgb_channels' # 保存图片 #filename[:filename.rindex('.')] img_path = './image/%s.png' % (filename[filename.rindex('/pdf/') + 5:filename.rindex('.pdf')]) #) img.save(filename=img_path) img.destroy() img = None pdf_bytes = None dst_pdf = None
def convert_image(filename, output_path, resolution=72, pages_captured=0): """ Convert a PDF into images. All the pages will give a single png file with format: {pdf_filename}-{page_number}.png The function removes the alpha channel from the image and replace it with a white background. """ all_pages = Image(filename=filename, resolution=resolution) for i, page in enumerate(all_pages.sequence): with Image(page) as img: img.format = 'png' img.background_color = Color('white') img.alpha_channel = 'remove' #same as starting file minus extension image_filename = os.path.splitext(os.path.basename(filename))[0] image_filename = image_filename.lower().replace('_svg', '').replace( ' ', '_') #neat for page number but not needed in this case if (pages_captured > 0): image_filename = '{}-{}.png'.format(image_filename.title(), i) else: image_filename = '{}.png'.format(image_filename.title()) image_filename = os.path.join(output_path, image_filename) img.save(filename=image_filename) if i == pages_captured: all_pages.destroy() return image_filename
def _run_convert_all(filename, res=120): '''把pdf所有页面转化为图片''' # 由于每次转换的时候都需要重新将整个PDF载入内存,所以这里使用内存缓存 pdfile, f = get_pdf_reader(filename), open(filename, "rb") # pdfile,f = get_pdf_reader2(filename) for i in range(0, pdfile.getNumPages()): temp_time = time.time() * 1000 pageobj = pdfile.getPage(i) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageobj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 90 img.background_color = Color("white") # 保存图片 img_path = 'dest/%s_pg%d.png' % (filename[:filename.rindex('.')], i + 1) img.save(filename=img_path) img.destroy() img, pdf_bytes, dst_pdf = None, None, None print('convert page %d cost time %dms' % (i + 1, (time.time() * 1000 - temp_time))) f.close()
def _run_convert(pdfile, savefilename, page_index, res=500): pageobj = pdfile.getPage(page_index) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageobj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'jpg' img.save(filename=savefilename + '-' + str(page_index) + '.jpg') img.destroy()
def download(self): self.filename = self.get_path('original') if os.path.isfile(self.filename): utils.logger.info('Returning cached file "%s".', self.image_url) return try: utils.logger.info('Downloading image "%s" from "%s"', self.image_url, self.source_url) headers = { 'Accept': '*/*', 'User-Agent': cfg('image_search:user_agent'), 'Referer': self.source_url } response = requests.get(self.image_url, headers=headers, timeout=5) except (requests.exceptions.RequestException, socket.timeout): # if the download times out, try with the next result raise ImageSearchResultError('Timed out') # if the download fails (404, ...), try with the next result if response.status_code != requests.codes.ok: raise ImageSearchResultError('Download of image failed') # store the image utils.logger.info('Saving image to "%s"', self.filename) with open(self.filename, 'wb') as handle: for block in response.iter_content(1024 * 1024): if not block: break handle.write(block) # and a metadata file to know where it came from metafile = self.get_path('meta') with open(metafile, 'w') as fp: print('url: %s' % self.image_url, file=fp) print('source: %s' % self.source_url, file=fp) print('query: %s' % self.text, file=fp) # check the size of the image before loading it into memory if os.stat(self.filename).st_size > 25 * 1024 * 1024: raise ImageSearchResultError('Image too big') # try to get Wand to load it as an image. if that doesn't work, raise # an exception so that we try with the next result try: image = Image(filename=self.filename) except Exception: raise ImageSearchResultError('Not an image') else: image.destroy() utils.logger.info('Complete')
def convert(filename, page=0, res=120): reader = PdfFileReader(filename, strict=False) page_obj = reader.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(page_obj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 90 img.background_color = Color('white') img_path = filename.replace('pdf', 'png') img.save(filename=img_path) img.destroy()
def convert(filename, res=120): pdf_file = PdfFileReader(open(filename, "rb")) pageObj = pdf_file.getPage(0) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img_filename = filename.replace('old', 'img').replace('pdf', 'png') img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 120 img.background_color = Color("white") img.save(filename=img_filename) img.destroy()
def _run_convert(pdfile, savedfilename, page_index, index, res=120): pageObj = pdfile.getPage(page_index) #获取pdf的第page_index页 dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 90 img.background_color = Color("white") img_path = '%s%04d.jpg' % (savedfilename, index) img.save(filename=img_path) print(img_path) img.destroy()
def _run_convert(filename, page, res=120): idx = page + 1 pdfile = getPdfReader(filename) pageObj = pdfile.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'jpg' img.compression_quality = 90 img.background_color = Color("white") img_path = '%s%d.jpg' % (filename[:filename.rindex('.')], idx) img.save(filename=img_path) img.destroy()
def _convert_pdf2img(self, file, store_path): pdf_file = PdfFileReader(file, strict=False) pageObj = pdf_file.getPage(0) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=200) img.format = 'jpg' img.compression_quality = 90 img.background_color = Color("white") img_path = store_path + '%s.jpg' % (uuid.uuid3(uuid.uuid1(), file)) print(img_path) img.save(filename=img_path) img.destroy() return img_path
def run_convert(filename, res): pdfile = getPdfReader(filename) pages = pdfile.getNumPages() for page in range(pages): print('正在解析%d页' % (page+1)) pageObj = pdfile.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.compression_quality = 90 img.background_color = Color("white") # img.save(filename = 'C:\\Users\\SXL47\\Desktop\\tupian.jpg') blob = img.make_blob('jpg') img.destroy() yield blob
def _run_convert(pdfile, savedfilename, page_index, index, res=240): # http://www.imooc.com/wenda/detail/600387 # 在Python中从PDF提取图像而无需重新采样? # pageObj = pdfile.getPage(page_index) #获取pdf的第page_index页 dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 100 img.background_color = Color("white") number = index + 1 img_path = '%s页面_%02d.jpg' % (savedfilename, number) #------------------------------------------------------------------------------------------------------------------- # Save Images # img.save(filename=img_path) print("extract " + img_path) img.destroy()
def pdfToImage(f_path, pdf_list): """ Esta función es útil para convertir PDF escaneados en imánes en formato PNG. Se generan tantas imagenes como páginas tenga el PDF a convertir. Parámetros: f_path = path de la carpeta donde guardar las imágenes. pdf_list = lista de PDF escaneados. """ image_folder = f_path + 'Images/' if not os.path.isdir(image_folder): os.mkdir(image_folder) name = [] for pdf in pdf_list: name.append(pdf.replace('.', '/').split('/')[-2]) for i in range(0, len(pdf_list)): try: opdf = Image(filename=pdf_list[i], resolution=300) ipdf = opdf.convert('png') for idx, img in enumerate(ipdf.sequence): page = Image(image=img) page.save(filename=image_folder + name[i] + '_' + 'image' + str(idx) + '.png') page.destroy() #print('Procesado ->', pdf_list[i]) ipdf.destroy() opdf.close() except: #print('No procesado ->', pdf_list[i]) pass
def run_convert(self, filename, page, res=120): # idx = page + 1 pdfile = getPdfReader(filename) pageObj = pdfile.getPage(page) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageObj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=res) img.format = 'png' img.compression_quality = 100 img.background_color = Color("white") filename = filename.split("/")[-1] img_path = 'resource/%s%s.png' % (filename[:filename.rindex('.')], "temp") delete_file("temp", root='resource/') img.save(filename=img_path) img.destroy() return img_path
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
# make text image textimg = Image(width=w, height=h) draw.gravity = 'center' draw.fill_color = Color('white') draw.text(0, 0, text) draw(textimg) # make text with gradient textimg.composite_channel(channel, gradient, 'in') # curve it textimg.distort('arc', [120], True) # add shadow shadowimg = textimg.clone() shadowimg.background_color = Color('black') shadow(shadowimg, 100, 2, 4, 4) # composite all canvas = Image(width=textimg.width, height=textimg.height, background=Color('white')) canvas.composite(shadowimg, 0, 0) canvas.composite(textimg, 0, 0) canvas.save(filename='sample39.png') gradient.destroy() textimg.destroy() shadowimg.destroy() canvas.destroy()
class Card(object): """Individual object containing an image and actions to manipulate it. Posible kwargs to __init__ are filename, file, image, blob. it will load the image from there""" def __init__(self, *args, **kwargs): """Init a new cards with *img* being a wand.image.Image object""" self.img = Image(*args, **kwargs) self.border = None self.changed = True self.pixmap() def __del__(self): self.img.destroy() def format(self, fmt=None): if fmt is None: return self.img.format.lower() else: self.img.format = fmt @set_changed def resize(self, width, height, newres=300): """Resize this card to (*width*, *height*) inches, with a resolution of *newres*""" self.img.transform(resize=str(int(width*newres)) + "x" + str(int(height*newres)) + "!") self.img.reset_coords() self.img.resolution = (newres, newres) return newres def width(self): return self.img.size[0] def height(self): return self.img.size[1] def reset_coords(self): self.img.reset_coords() @set_changed def set_border(self, border): """Set a new *border* for this card""" if self.border is not None: self.del_border() self.border = border with Color(self.border.colour) as colour: self.img.border(colour, self.border.wide, self.border.wide) @set_changed def crop(self, *args, **kwargs): """Crop this card *top*, *bottom*, *left* and *right* pixels""" w, h = self.img.size if "right" in kwargs: kwargs["right"] = w - kwargs["right"] if "bottom" in kwargs: kwargs["bottom"] = h - kwargs["bottom"] self.img.crop(*args, **kwargs) self.reset_coords() def del_border(self): """Remove the border of this card""" if self.border is not None: w = self.border.wide self.crop(top=w, bottom=w, right=w, left=w) self.border = None self.changed = True @set_changed def trim(self, fuzz=13): self.img.trim(fuzz=fuzz) self.reset_coords() def save_as(self, filename): """Save this card in a file named *filename*""" self.img.save(filename = filename) def split(self, rows, cols, separation=0): """Divide this cards in *rows* by *cols* cards, and returns a list""" width, hight = self.img.size width, hight = (int(width), int(hight)) cardWidth = (width - separation * (cols-1)) / cols cardHight = (hight - separation * (rows-1)) / rows res = [] for i in range(rows): for j in range(cols): with self.img.clone() as clon: clon.crop(top=i*cardHight+i*separation, width=cardWidth, left=j*cardWidth+j*separation, height=cardHight) clon.reset_coords() res.append(Card(image=clon)) return res @set_changed def round_corners(self): """Round the corners of the card (setting them to alpha)""" pass def clone(self): c = Card(image=self.img.clone()) c.border = self.border return c def pixmap(self): """Update and returns the pixmap (QPixmap) of the contained image""" if self.changed: self._pixmap = QPixmap(QImage.fromData(self.img.make_blob("jpg"), "jpg"))#self.img.format)) self.changed = False return self._pixmap
class CheckImage(unittest.TestCase): @classmethod def setUpClass(self): os.mkdir(tmpdir) self.rose = Image(filename='rose:') self.grad = Image(filename='gradient:', width=400, height=400) self.logo = Image(filename='logo:') self.text = Image(filename='label:Confirm', width=200, height=60) self.text_a = Image(width=70, height=60) with Drawing() as draw: draw.font = 'Arial' draw.font_size = 50 draw.gravity = 'center' draw.fill_color = Color('white') draw.stroke_color = Color('black') draw.text(0, 0, 'A') draw(self.text_a) self.rose.save(filename=tmpdir + 'rose.png') self.grad.save(filename=tmpdir + 'grad.png') self.logo.save(filename=tmpdir + 'logo.png') self.text.save(filename=tmpdir + 'text.png') self.text_a.save(filename=tmpdir + 'a.png') @classmethod def tearDownClass(self): self.rose.destroy() self.grad.destroy() self.logo.destroy() self.text.destroy() self.text_a.destroy() def test_adaptiveblur(self): f = wpi.adaptiveblur with self.rose.clone() as t: f(t, 5.0, 3.0) save(t, f) with self.rose.clone() as t: f(t, 5.0, 3.0, channel='red') save(t, f, True) def test_adaptiveresize(self): f = wpi.adaptiveresize with self.rose.clone() as t: f(t, int(t.width * 1.5), int(t.height * 2.0)) save(t, f) def test_adaptivesharpen(self): f = wpi.adaptivesharpen with self.rose.clone() as t: f(t, 5, 5) save(t, f) with self.rose.clone() as t: f(t, 5, 5, channel='red') save(t, f, True) def test_adaptivethreshold(self): f = wpi.adaptivethreshold with self.logo.clone() as t: f(t, 20, 20, int(0.1 * t.quantum_range)) save(t, f) def test_addnoise(self): f = wpi.addnoise with self.grad.clone() as t: f(t, 'gaussian') save(t, f) with self.grad.clone() as t: f(t, 'gaussian', channel='red') save(t, f, True) def test_affinetransform(self): f = wpi.affinetransform with self.rose.clone() as t: with Drawing() as d: d.affine([2.0, 0.0, 0.0, 2.0, 0.0, 0.0]) f(t, d) # not work correctly (IM<6.9.9-36) save(t, f) def test_autogamma(self): f = wpi.autogamma with self.rose.clone() as t: f(t) save(t, f) with self.rose.clone() as t: f(t, channel='red') save(t, f, True) def test_autolevel(self): f = wpi.autolevel with self.rose.clone() as t: f(t) save(t, f) with self.rose.clone() as t: f(t, channel='red') save(t, f, True) def test_blackthreshold(self): f = wpi.blackthreshold with self.grad.clone() as t: f(t, Color('gray(50%)')) save(t, f) def test_blueshift(self): f = wpi.blueshift with self.logo.clone() as t: f(t, 0.5) save(t, f) def test_brightnesscontrast(self): f = wpi.brightnesscontrast with self.rose.clone() as t: f(t, -30, 0) save(t, f) with self.rose.clone() as t: f(t, -30, 0, channel='red') save(t, f, True) def test_blur(self): f = wpi.blur with self.rose.clone() as t: f(t, 0, 3) save(t, f) with self.rose.clone() as t: f(t, 0, 3, channel='red') save(t, f, True) def test_charcoal(self): f = wpi.charcoal with self.rose.clone() as t: f(t, 5, 1) save(t, f) def test_chop(self): f = wpi.chop with self.grad.clone() as t: t.gravity = 'north_west' f(t, 0, 00, 200, 200) save(t, f) def test_clamp(self): f = wpi.clamp # TODO: more useful code with self.rose.clone() as t: f(t) save(t, f) with self.rose.clone() as t: f(t, channel='red') save(t, f, True) def test_clip(self): # NOTE: result is always FAILED. f = wpi.clip # I don't have an image which has clipping path with self.rose.clone() as t: f(t) save(t, f) def test_clippath(self): # NOTE: result is always FAILED. f = wpi.clippath with self.rose.clone() as t: f(t, '#1', True) save(t, f) def test_clut(self): f = wpi.clut with Image(filename='gradient:red-blue', width=1, height=100) as p: p.rotate(90) with self.grad.clone() as t: f(t, p) save(t, f) with self.grad.clone() as t: f(t, p, channel='green') save(t, f, True) def test_coalesce(self): # TODO: input optimized .gif file. f = wpi.coalesce with Image() as t: with self.rose.clone() as p: for i in range(5): wpi.blur(p, 0, 1) wpi.add(t, p) with f(t) as p: save(p, f) def test_colordecisionlist(self): xml = """ <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> <ColorCorrection id="cc03345"> <SOPNode> <Slope> 0.9 1.2 0.5 </Slope> <Offset> 0.4 -0.5 0.6 </Offset> <Power> 1.0 0.8 1.5 </Power> </SOPNode> <SATNode> <Saturation> 0.85 </Saturation> </SATNode> </ColorCorrection> </ColorCorrectionCollection> """ f = wpi.colordecisionlist with self.rose.clone() as t: f(t, xml) save(t, f) def test_colorize(self): f = wpi.colorize with self.grad.clone() as t: f(t, Color('red'), Color('gray(25%)')) save(t, f) def test_colormatrix(self): f = wpi.colormatrix with self.logo.clone() as t: kernel = [ 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 1.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] f(t, 5, 5, kernel) save(t, f) def test_combine(self): f = wpi.combine with Image() as t: w = 100 h = 100 black = Color('black') white = Color('white') with Image(width=w, height=w, background=black) as b: with Image(width=h, height=h, background=white) as w: wpi.add(t, b) # add image for red channel wpi.add(t, b) # add image for green channel wpi.add(t, w) # add image for blue channel wpi.setfirstiterator(t) # rewind the index pointer channel = 1 + 2 + 4 # R + G + B with f(t, channel) as q: save(q, f) def test_comment(self): f = wpi.comment with self.grad.clone() as t: f(t, 'hello') save(t, f) def test_compare(self): f = wpi.compare with self.rose.clone() as t: with t.clone() as p: (c, d) = f(t, p, metric='absolute') save(c, f) c.destroy() with self.rose.clone() as t: with t.clone() as p: (c, d) = f(t, p, metric='absolute', channel='red') save(c, f, True) c.destroy() def test_comparelayer(self): f = wpi.comparelayer with Image() as t: with Image(width=50, height=50, background=Color('red')) as p: wpi.add(t, p) with Image(width=25, height=25, background=Color('green1')) as q: for i in range(4): with q.clone() as qq: wpi.resetpage(qq, 5 * (i + 1), 5 * (i + 1)) wpi.add(t, qq) with f(t, 'compareany') as r: save(r, f, ext='.gif') def test_constitute(self): f = wpi.constitute with Image() as t: w = 2 h = 2 b = [0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 255, 0] f(t, w, h, 'RGB', 'char', b) save(t, f) def test_contrast(self): f = wpi.contrast with self.rose.clone() as t: f(t, False) save(t, f) def test_convolve(self): f = wpi.convolve kernel = [ 1 / 16, 2 / 16, 1 / 16, 2 / 16, 4 / 16, 2 / 16, 1 / 16, 2 / 16, 1 / 16 ] with self.rose.clone() as t: f(t, 3, kernel) save(t, f) with self.rose.clone() as t: f(t, 3, kernel, channel='red') save(t, f, True) def test_cyclecolormap(self): f = wpi.cyclecolormap with self.logo.clone() as t: f(t, 5) save(t, f) def test_cipher(self): f = wpi.encipher with self.rose.clone() as t: f(t, 'password') save(t, f) f = wpi.decipher f(t, 'password') save(t, f) def test_deskew(self): f = wpi.deskew with Image(width=80, height=40, background=Color('black')) as t: f(t, 0.5 * t.quantum_range) # TODO: find an skewed image as sample save(t, f) def test_despeckle(self): f = wpi.despeckle with self.rose.clone() as t: # TODO: add speckle noise f(t) save(t, f) def test_edge(self): f = wpi.edge with self.logo.clone() as t: f(t, 3) save(t, f) def test_emboss(self): f = wpi.emboss with self.logo.clone() as t: f(t, 0, 3) save(t, f) def test_enhance(self): f = wpi.enhance with Image(filename='plasma:', width=100, height=100) as t: f(t) save(t, f) def test_equalize(self): f = wpi.equalize with self.rose.clone() as t: f(t) save(t, f) with self.rose.clone() as t: f(t, channel='red') save(t, f, True) def test_exportpixels(self): w = 1 h = 1 channels = 'RGB' with Image(width=w, height=h, background=Color('red')) as t: r = wpi.exportpixels(t, 0, 0, w, h, channels, 'double') self.assertEqual(r[0], 1.0) self.assertEqual(r[1], 0.0) self.assertEqual(r[2], 0.0) def test_extent(self): f = wpi.extent with self.rose.clone() as t: t.gravity = 'center' t.background_color = Color('blue') f(t, -10, -10, t.width + 20, t.height + 20) save(t, f) def test_filterimage(self): f = wpi.filterimage kernel = [ # Sobel filter -1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0, ] with self.rose.clone() as t: f(t, 3, 3, kernel) save(t, f) with self.rose.clone() as t: f(t, 3, 3, kernel, channel='red') save(t, f, True) def test_floodfillpaint(self): f = wpi.floodfillpaint with self.logo.clone() as t: f(t, Color('green'), 0.10 * t.quantum_range, Color('white'), 0, 0) save(t, f) def test_fft(self): f = wpi.forwardfouriertransform # require IM build option '--with-fftw' with self.logo.clone() as t: # I couldn't build on Windows... f(t, True) save(t, f) # includes two images(magnitude&phase) f = wpi.inversefouriertransform with t.sequence[0].clone() as mag: with t.sequence[1].clone() as phase: wpi.blur(mag, 0, 0.5) # as degradation t2 = mag f(t2, phase, True) save(t2, f) def test_haldclut(self): f = wpi.haldclut # TODO: more useful code with Image(filename='hald:12') as p: with self.rose.clone() as t: f(t, p) save(t, f) with self.rose.clone() as t: f(t, p, channel='red') save(t, f, True) def test_implode(self): f = wpi.implode with self.rose.clone() as t: f(t, 1.0) save(t, f) def test_importpixels(self): f = wpi.importpixels with Image(width=4, height=4, background=Color('red')) as t: w = 2 h = 2 b = [0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 255, 0] f(t, 1, 1, w, h, 'RGB', 'char', b) save(t, f) def test_label(self): f = wpi.label with self.rose.clone() as t: f(t, 'hello') save(t, f) def test_localcontrast(self): f = wpi.localcontrast with self.logo.clone() as t: f(t, 5, 30) save(t, f) def test_magnify(self): f = wpi.magnify with self.rose.clone() as t: f(t) save(t, f) def test_minify(self): f = wpi.minify with self.rose.clone() as t: f(t) save(t, f) def test_montage(self): f = wpi.montage with self.rose.clone() as base: with Image() as dst: rows = 2 columns = 3 for i in range(rows * columns): wpi.add(dst, base) tile = "{0}x{1}+0+0".format(columns, rows) thumb = "80x50+4+3" frame = "15x15+3+3" mode = "frame" with Drawing() as d: with f(dst, d, tile, thumb, mode, frame) as result: save(result, f) def test_morph(self): f = wpi.morph color = Color('white') with self.rose.clone() as t: with Image(width=t.width, height=t.height, background=color) as p: wpi.add(t, p) wpi.setfirstiterator(t) wpi.setdelay(t, 60) with f(t, 5) as q: save(q, f, ext='.gif') def test_morphology(self): f = wpi.morphology with self.logo.clone() as t: f(t, 'dilate', 1, 'Diamond') save(t, f) with self.logo.clone() as t: f(t, 'dilate', 1, 'Diamond', channel='red') save(t, f, True) def test_motionblur(self): f = wpi.motionblur with self.logo.clone() as t: f(t, 30, 10, 45) save(t, f) with self.logo.clone() as t: f(t, 30, 10, 45, channel='red') save(t, f, True) def test_oilpaint(self): f = wpi.oilpaint with self.rose.clone() as t: f(t, 2.0) save(t, f) def test_opaquepaint(self): f = wpi.opaquepaint with self.logo.clone() as t: f(t, Color('red'), Color('blue'), 1.0, False) save(t, f) with self.logo.clone() as t: f(t, Color('red'), Color('blue'), 1.0, False, channel='blue') save(t, f, True) def test_orderedposterize(self): f = wpi.orderedposterize with self.grad.clone() as t: f(t, 'o4x4,3,3') save(t, f) with self.grad.clone() as t: f(t, 'o4x4,3,3', channel='red') save(t, f, True) def test_polaroid(self): f = wpi.polaroid with self.logo.clone() as t: with Drawing() as d: f(t, d, 1.0) save(t, f) def test_posterize(self): f = wpi.posterize with self.rose.clone() as t: f(t, 3, True) save(t, f) def test_raiseimage(self): f = wpi.raiseimage with self.rose.clone() as t: f(t, 10, 10, 10, 10, True) save(t, f) def test_randomthreshold(self): f = wpi.randomthreshold with self.text_a.clone() as t: rng = t.quantum_range f(t, int(rng * 0.05), int(rng * 0.95)) save(t, f) with self.text_a.clone() as t: rng = t.quantum_range f(t, int(rng * 0.05), int(rng * 0.95), channel='red') save(t, f, True) def test_remap(self): f = wpi.remap with self.logo.clone() as t: with self.rose.clone() as p: f(t, p, 'nodither') save(t, f) def test_resample(self): f = wpi.resample with self.rose.clone() as t: dpi = 72 * 2 f(t, dpi, dpi, 'lanczos', 1.0) save(t, f) def test_roll(self): f = wpi.roll with self.rose.clone() as t: f(t, 10, 10) save(t, f) def test_rotationalblur(self): f = wpi.rotationalblur with self.rose.clone() as t: f(t, 45) save(t, f) with self.rose.clone() as t: f(t, 45, channel='red') save(t, f, True) def test_scale(self): f = wpi.scale with self.rose.clone() as t: f(t, t.width * 2, t.height * 2) save(t, f) def test_segment(self): f = wpi.segment with self.logo.clone() as t: f(t, 'rgb', False, 5, 20) save(t, f) def test_selectiveblur(self): f = wpi.selectiveblur with self.logo.clone() as t: f(t, 20, 20, 0.5 * t.quantum_range) save(t, f) with self.logo.clone() as t: f(t, 20, 20, 0.5 * t.quantum_range, channel='red') save(t, f, True) def test_separate_channel(self): f = wpi.separate_channel with self.rose.clone() as t: f(t, 'red') save(t, f) def test_sepiatone(self): f = wpi.sepiatone with self.rose.clone() as t: f(t, 0.5 * t.quantum_range) save(t, f) def test_shade(self): f = wpi.shade with self.logo.clone() as t: f(t, True, 45, 135) save(t, f) def test_shadow(self): f = wpi.shadow with self.text.clone() as t: with self.text.clone() as p: p.negate() f(p, 100, 2, 10, 10) t.composite_channel('default_channels', p, 'overlay') save(t, f) def test_sharpen(self): f = wpi.sharpen with self.rose.clone() as t: f(t, 3, 3) save(t, f) with self.rose.clone() as t: f(t, 3, 3, channel='red') save(t, f, True) def test_shave(self): f = wpi.shave with self.logo.clone() as t: f(t, 100, 100) save(t, f) def test_shear(self): f = wpi.shear with self.grad.clone() as t: f(t, Color('red'), 0, 10) save(t, f) def test_sigmoidalcontrast(self): f = wpi.sigmoidalcontrast with self.rose.clone() as t: f(t, True, 3, 3) save(t, f) with self.rose.clone() as t: f(t, True, 3, 3, channel='red') save(t, f, True) def test_sketch(self): f = wpi.sketch with self.logo.clone() as t: f(t, 10, 10, 45) save(t, f) def test_smush(self): f = wpi.smush def makeletter(letter, w, h): img = Image(width=w, height=h) with Drawing() as d: d.font = 'Arial' d.font_size = 24 d.gravity = 'center' d.text(0, 0, letter) d(img) return img with Image() as t: with makeletter('A', 50, 30) as a: with makeletter('B', 50, 30) as b: wpi.add(t, a) wpi.add(t, b) wpi.setfirstiterator(t) with f(t, False, -3) as p: save(p, f) def test_solarize(self): f = wpi.solarize with self.rose.clone() as t: f(t, 0.4 * t.quantum_range) save(t, f) with self.rose.clone() as t: f(t, 0.4 * t.quantum_range, channel='red') save(t, f, True) def test_splice(self): f = wpi.splice with self.rose.clone() as t: t.gravity = 'center' f(t, t.width // 2, t.height // 2, 20, 20) save(t, f) def test_sparsecolor(self): f = wpi.sparsecolor with Image(width=100, height=100, background=Color('black')) as t: f(t, 'default_channels', 'bilinear', [0, 0, 1.0, 0.0, 0.0, 1.0, 100, 100, 0.0, 1.0, 1.0, 1.0]) save(t, f) def test_spread(self): f = wpi.spread with self.logo.clone() as t: f(t, 20) save(t, f) def test_statistic(self): f = wpi.statistic with self.rose.clone() as t: f(t, 'gradient', 4, 4) save(t, f) with self.rose.clone() as t: f(t, 'gradient', 4, 4, channel='red') save(t, f, True) def test_stegano(self): f = wpi.stegano with self.rose.clone() as t: w = 50 h = 40 offset = 15 tmpfile = 'tmp.png' with Image(width=w, height=h, background=Color('white')) as p: with Drawing() as d: d.gravity = 'center' d.fill_color = Color('black') d.text(0, 0, 'Watch\nthe\nPidgeon') d(p) with f(t, p, offset) as q: q.save(filename=tmpfile) try: with Image() as q: wpi.setsizeoffset(q, w, h, offset) q.read(filename='stegano:' + tmpfile) save(q, f) except Exception: raise finally: os.remove(tmpfile) def test_stereo(self): f = wpi.stereo with self.rose.clone() as t: with self.rose.clone() as p: p.negate() with f(t, p) as q: save(q, f) def test_swirl(self): f = wpi.swirl with self.rose.clone() as t: f(t, 180) save(t, f) def test_texture(self): f = wpi.texture with Image(width=300, height=200) as t: with self.rose.clone() as p: with f(t, p) as q: save(q, f) def test_thumbnail(self): f = wpi.thumbnail with self.logo.clone() as t: f(t, 100, 100) save(t, f) def test_tint(self): f = wpi.tint with self.rose.clone() as t: f(t, Color('rgb'), Color('gray(25%)')) save(t, f) def test_vignette(self): f = wpi.vignette with self.logo.clone() as t: wpi.minify(t) t.background_color = Color('black') f(t, 0, 10, 20, 20) save(t, f) def test_wave(self): f = wpi.wave with self.grad.clone() as t: f(t, 40, 200) save(t, f) def test_whitethreshold(self): f = wpi.whitethreshold with self.grad.clone() as t: f(t, Color('gray(50%)')) save(t, f)
# -*- coding: utf-8 -*- """ Created on Mon Apr 29 16:05:03 2019 @author: Administrator """ import io from PyPDF2 import PdfFileReader, PdfFileWriter from wand.image import Image pdfile = PdfFileReader('E:\\YJZ\work\\化工安全\\M02模块送审\\修改\\904.pdf') pageobj = pdfile.getPage(0) dst_pdf = PdfFileWriter() dst_pdf.addPage(pageobj) pdf_bytes = io.BytesIO() dst_pdf.write(pdf_bytes) pdf_bytes.seek(0) img = Image(file=pdf_bytes, resolution=500) img.format = 'jpg' img.save(filename='2.jpg') img.destroy()
with Drawing() as draw: text = ' I M Examples ' draw.font = 'Anaconda-Regular' draw.font_size = 72 (w, h) = calcSuitableImagesize(draw, text) # make text image textimg = Image(width=w, height=h, background=Color('black')) draw.gravity = 'center' draw.fill_color = Color('dodgerblue') draw.text(0, 0, text) draw(textimg) textimg.border(Color('black'), 30, 30) # make shadow image shadowimg = textimg.clone() blur(shadowimg, 0, 25) shadowimg.level(black=0.0, gamma=1.0, white=0.5) # composite all canvas = Image(width=shadowimg.width, height=shadowimg.height) canvas.composite(shadowimg, 0, 0) canvas.composite_channel('default_channels', textimg, 'screen') canvas.save(filename='sample40.png') shadowimg.destroy() textimg.destroy() canvas.destroy()
def compose_base_image(self): # compose the base image # "stop" image img_stop = Image(filename=self.path_img_stop) scale = int(img_stop.height * self.img_stop_width_target / img_stop.width) img_stop.resize(self.img_stop_width_target, scale) # "payoff" image img_payoff = Image(filename=self.path_img_payoff) scale = int(img_payoff.height * self.img_payoff_width_target / img_payoff.width) img_payoff.resize(self.img_payoff_width_target, scale) # name img_name = Image(filename=self.path_img_name) scale = int(img_name.height * self.img_name_width_target / img_name.width) img_name.resize(self.img_name_width_target, scale) # logo img_logo = Image(filename=self.path_img_logo) scale = int(img_logo.height * self.img_logo_width_target / img_logo.width) img_logo.resize(self.img_logo_width_target, scale) # calc the offsets self.stop_y_offset = int(self.height*0.11) self.stop_x_offset = 0 self.text_y_offset = int(self.stop_y_offset+img_stop.height) self.text_x_offset = 0 self.name_y_offset = int(self.height*0.88) self.name_x_offset = int(self.width*0.08) self.payoff_y_offset = int(self.height*0.888) self.payoff_x_offset = int(self.width*0.57) self.logo_y_offset = int(self.height*0.858) self.logo_x_offset = int(self.width*0.80) # compose the base image base_img = Image( height=self.height, width=self.width, background=COLOR_DARK) base_img.composite(img_stop, left=self.stop_x_offset, top=self.stop_y_offset) base_img.composite(img_name, left=self.name_x_offset, top=self.name_y_offset) base_img.composite(img_payoff, left=self.payoff_x_offset, top=self.payoff_y_offset) base_img.composite(img_logo, left=self.logo_x_offset, top=self.logo_y_offset) if self.width >= 200: with Drawing() as footer_draw: footer_draw.font = self.lzy_path_font footer_draw.font_size = 14 footer_draw.fill_color = COLOR_DIM footer_draw.gravity = "south_east" footer_draw.text(5, 5, "csigerstop.lzy.dk") footer_draw.draw(base_img) img_stop.destroy() img_payoff.destroy() img_name.destroy() img_logo.destroy() return base_img
# 2.make bump map with inputimg.clone() as tmp1: with inputimg.clone() as tmp2: tmp2.negate() tmp2.level(black=0.0, white=0.1) tmp1.composite_channel(def_ch, tmp2, 'copy_opacity') shade(tmp1, True, 315, 45) autogamma(tmp1) autolevel(tmp1) baseimg.composite_channel(def_ch, tmp1, 'overlay') # baseimg.save(filename='sample41-2.png') # 3.coloring clut(baseimg, clutimg) # baseimg.save(filename='sample41-3.png') # 4.add shadow metallicimg = baseimg.clone() metallicimg.background_color = Color(shadowcolor) shadow(metallicimg, 80, 2, 3, 3) metallicimg.composite_channel(def_ch, baseimg, 'over') # end: metallicimg.save(filename='sample41.png') # clean-up(as you like) inputimg.destroy() clutimg.destroy() baseimg.destroy() metallicimg.destroy()
async def _compose_alvise(self, bg_img, text=None, count=1, **kwargs): with Drawing() as drawing: # fill the drawing primitives drawing.font = 'assets/HelveticaNeueLTCom-Md.ttf' drawing.gravity = 'north_west' drawing.fill_color = Color('#56fdb4') text = text if text else '@Alvisepf' # try to determine what a good font size would be string_list = text.split('\n') longest_string = len(max(string_list, key=len)) line_count = len(string_list) drawing.font_size = max( min(bg_img.width / longest_string * 1.5, bg_img.height / line_count * 1.5), 4) # the drawing has some padding so ascenders and descenders do not get truncated metrics = drawing.get_font_metrics(bg_img, text, '\n' in text) mask_w_orig, mask_h_orig = metrics.text_width, metrics.text_height + metrics.descender mask_w, mask_h = int(mask_w_orig * 1.02), int(mask_h_orig * 1.1) drawing.text(int((mask_w - mask_w_orig) / 2), int((mask_h - mask_h_orig) / 2), text) # create a mask image to draw the text on to, and... with Image(width=mask_w, height=mask_h) as mask_img: # draw the text into the mask image drawing.draw(mask_img) original_mask_img = Image(mask_img) frames = [] for i in range(count): mask_img = Image(original_mask_img) # rotate the mask mask_img.rotate(random.uniform(-35, -5)) # calculate what a smaller background image would look like scaling_factor = random.uniform(.5, .7) bg_img_scaled_w = bg_img.width * scaling_factor bg_img_scaled_h = bg_img.height * scaling_factor # scale the mask to fit into that smaller background image mask_img.transform(resize='%dx%d' % (bg_img_scaled_w, bg_img_scaled_h)) # calculate a random position inside the background image for it offset_left = random.randint(0, bg_img.width - mask_img.width) offset_top = random.randint( 0, bg_img.height - mask_img.height) # and put the mask in the image bg_img.composite(mask_img, left=offset_left, top=offset_top) frames.append( self.save_image( self.generate_filename(self.filename, i))) if kwargs.get('callback') and kwargs.get('callback_args'): await kwargs.get('callback')( kwargs.get('callback_args')[0], i, count) original_mask_img.destroy() return frames