def to_animated_gif(self, filename, zoom = 1): if not any(self.frames): raise Exception("tried to output animated GIF with no frames") with wi.Image() as anim: for frame in self.frames: with wi.Image(width=self.width*zoom, height=self.height*zoom) as img: frame.draw(img, zoom) anim.sequence.append(img) anim.sequence[-1].delay = (frame.duration if frame.duration else 0) // 10 # ms --> 1/100s of a second anim.type = 'optimize' anim.save(filename=filename)
def getsepia(image: BytesIO): io =BytesIO(image) io.seek(0) with wi.Image() as dst_image: with wi.Image(blob=io) as src_image: for frame in src_image.sequence: frame.sepia_tone(threshold=0.8) dst_image.sequence.append(frame) bts = dst_image.make_blob() i = BytesIO(bts) i.seek(0) return(i)
def getpaint(image: BytesIO): io =BytesIO(image) io.seek(0) with wi.Image() as dst_image: with wi.Image(blob=io) as src_image: for frame in src_image.sequence: frame.oil_paint(sigma=3) dst_image.sequence.append(frame) bts = dst_image.make_blob() i = BytesIO(bts) i.seek(0) return(i)
def getcharc(image: BytesIO): io =BytesIO(image) io.seek(0) with wi.Image() as dst_image: with wi.Image(blob=io) as src_image: for frame in src_image.sequence: frame.transform_colorspace("gray") frame.sketch(0.5, 0.0, 98.0) dst_image.sequence.append(frame) bts = dst_image.make_blob() i = BytesIO(bts) i.seek(0) return(i)
def replaceStringInFile(f_): head, tail = os.path.split(f_) name, ext = os.path.splitext(tail) png = head + name + '.png' with image.Image(filename=f_) as img: img.compression = "no" img.save(filename=png)
def index(): if f.request.method == 'GET': objects = get_ramens(0, 9) return f.render_template('list.html', objects=objects) else: ## Process incoming args img = f.request.files['image'] desc = f.request.form['description'].strip() ## Save incoming file to Flask-Uploads collection and local disk. localname = str(uuid.uuid4()) + os.path.splitext( img.filename)[1].lower() images.save(img, None, localname) ## Resize print os.path.splitext(img.filename)[1].lower() if os.path.splitext(img.filename)[1].lower() != '.gif': wimg = wi.Image(filename=images.path(localname)) wimg.transform(resize='1024x1024>') wimg.save(filename=images.path(localname)) ## Move file to S3 k.key = os.path.basename(localname) k.set_contents_from_filename(images.path(localname)) os.remove(images.path(localname)) ## Store in DB key = 'ramen:' + str(r.incr('key')) r.lpush('keys', key) r.lpush('ramens', localname) # DELETE? r.hmset(key, { 'filename': localname, 'description': desc, 'inserted': now() }) objects = get_ramens(0, 9) return f.render_template('list.html', objects=objects)
def generate(self, avatars, text, usernames, kwargs): avatar = BytesIO(http.get_content_raw(avatars[0])) try: img = image.Image(file=avatar) except Exception as e: raise BadRequest(f'The image could not be loaded: {e}') if img.animation: img = img.convert('png') img.transform(resize='400x400') try: multiplier = int(text) except ValueError: multiplier = 1 else: multiplier = max(min(multiplier, 10), 1) img.liquid_rescale(width=int(img.width * 0.5), height=int(img.height * 0.5), delta_x=0.5 * multiplier, rigidity=0) img.liquid_rescale(width=int(img.width * 1.5), height=int(img.height * 1.5), delta_x=2 * multiplier, rigidity=0) b = BytesIO() img.save(file=b) b.seek(0) img.destroy() return send_file(b, mimetype='image/png')
async def magic(self, ctx, scale=3): try: if scale > 10: await ctx.send( tr("The scale argument can't be more than 10", ctx=ctx)) scale = 1 to_send = "Images/Temp/magic.png" url = await self._get_images(ctx) response = requests.get(url) img = Image.open(BytesIO(response.content)) img.save(to_send, "PNG") img = image.Image(filename=to_send) img.liquid_rescale(width=int(img.width * 0.5), height=int(img.height * 0.5), delta_x=int(0.5 * scale) if scale else 1, rigidity=0) img.liquid_rescale(width=int(img.width * 1.5), height=int(img.height * 1.5), delta_x=scale if scale else 2, rigidity=0) img.save(filename=to_send) await ctx.send(file=discord.File(to_send)) os.remove(to_send) except Exception as e: await ctx.send(tr("I pooped myself", ctx=ctx, err=e))
def main(): args = parser.parse_args() for root, dirs, files in os.walk(args.asset_path): for f in files: if f.endswith('.dds'): in_file = os.path.join(root, f) out_file = os.path.splitext(in_file)[0] + ".bmp" try: print("Converting {}...".format(in_file)) with image.Image(filename=in_file) as img: img.compression = "no" img.save(filename=out_file) os.remove(in_file) except Exception as e: print("Corrupted DDS file: {}".format(in_file)) elif f.endswith('.mp3'): in_file = os.path.join(root, f) out_file = os.path.join(root, os.path.splitext(f)[0] + ".wav") print("Converting {}...".format(in_file)) subprocess.run( ["ffmpeg", "-v", "quiet", "-i", in_file, out_file]) os.remove(in_file) else: print("Not converting {}".format(os.path.join(root, f)))
def make_zip(orig_path, new_name, use_apple_names): path, ext = os.path.splitext(new_name) zip_name = path + '.zip' orig_name = os.path.splitext(orig_path)[0] ## Write original into new zipfile. zf = zipfile.ZipFile(zip_name, 'a') zf.write(new_name, orig_path) ## Create image Object. orig = wi.Image(filename=new_name) os.remove(new_name) for w, h, apple_name, name in variants: ## Figure out what to name the files in the zip if use_apple_names: arcname = apple_name + ext else: arcname = orig_name + '-' + name + ext variant_name = path + '-' + name + ext ## Write variants to disk clone = orig.clone() clone.resize(w, h) clone.save(filename=variant_name) ## Move variants to zip zf.write(variant_name, arcname) os.remove(variant_name) zf.close() return zip_name
def __emote(): image_resized = image.resize((int(resize_value * image.width), int(resize_value * image.height)), resample=Image.HAMMING) image_resized.save(outfile_path, format='PNG', quality=100) # Laziness, rewrite webp with composition in place. if webp: # Outdated. Should say 'tg' — compose emote import os from wand import image as wandimg with wandimg.Image(filename=outfile_path) as img_precomposite: img_comp = wandimg.Image(width=512, height=512) img_comp.composite(img_precomposite, gravity='center') img_comp.save(filename=outfile_path) # Upload sticker to telegram from emotes.wsgi import tg, app from emotes.app import models if resized_image.image.emote_id == None: # Local emote nmsp = models.Namespace.get(models.Namespace.slug == "") # Global namespace else: nmsp = resized_image.image.emote.namespace # TODO handle global emotes here resp = tg.bot.upload_sticker_file( user_id=app.config["TG_USERID"], png_sticker=open(outfile_path, 'rb') ) print(resp) tg.bot.add_sticker_to_set( user_id=app.config["TG_USERID"], name=nmsp.tg_stickerpack_name, png_sticker=resp['file_id'], emojis="\N{thinking face}" ) stickerset = tg.bot.get_sticker_set(name=nmsp.tg_stickerpack_name) for sticker in stickerset.stickers: # print("s", sticker) print("sfl", sticker.get_file()) resized_image.tg_file_id = stickerset.stickers[-1].file_id
def transform_file(di: str, fi: str): base = fi[:-4] fipng = base + ".png" print("transforming {} --> {}".format(fi, fipng)) with wim.Image(filename=osp.join(di, fi)) as img: img.format = 'png' img.save(filename=osp.join(di, fipng))
def convert(): from wand import image with image.Image(filename="31_21.png") as img: img.strip() img.flip() image.library.MagickSetOption(img.wand, b"dds:mipmaps", b"0") image.library.MagickSetOption(img.wand, b"dds:compression", b"none") img.save(filename="31_21.dds")
def scale_file(di: str, fi: str): print("scaling {}".format(fi)) with wim.Image(filename=osp.join(di, fi)) as img: k = 100.0 / img.height w1 = int(k * img.width) h1 = int(k * img.height) print("resize {} to {} x {}".format(fi, w1, h1)) img.resize(w1, h1) img.save(filename=osp.join(di, fi))
def create_file(path): destination_path = os.path.join( "static_dist", *path.split(os.sep)[1:]) destination_root = destination_path[:-3] destination_path = destination_root + "dds" with image.Image(filename=path) as img: img.flip() img.compression = "dxt3" img.save(filename=destination_path)
def _operateBaozhangPDF(self, file_in): '''将PDF文件变更为JPG格式后处理报账单''' print(' > 开始将PDF版的报账单转化为JPG格式') image_pdf = wand_image.Image(filename=file_in, resolution=300) image_jpeg = image_pdf.convert('jpg') # wand已经将PDF中所有的独立页面都转成了独立的二进制图像对象。我们可以遍历这个大对象,并把它们加入到req_image序列中去。 if len(image_jpeg.sequence) != 1: print(' > PDF报账单文件页数不为1,请核实') return '' img = image_jpeg.sequence[0] img_page = wand_image.Image(image=img) img_ok = img_page.make_blob('jpg') file_out = file_in.replace('.pdf', '.jpg') ff = open(file_out, 'wb') ff.write(img_ok) ff.close() image_pdf.clear() print(' > 已将PDF版的报账单转化为JPG格式') return file_out
def slice_pages(fname, pages, out_path=None, resolution=300, use_convert=True): """Use ImageMagick to slice the PDF into individual PNG pages. For example:: >>> from bocho import slice_pages >>> pngs = slice_pages('/path/to/my-file.pdf', [1,2,3]) >>> print pngs [ '/path/to/my-file-Gq_Yw1-1.png', '/path/to/my-file-Gq_Yw1-2.png', '/path/to/my-file-Gq_Yw1-3.png', ] If ``out_path`` isn't provided, we use the :mod:`tempfile` module to generate one. Args: fname (str): The PDF to split pages (list): Pages to slice Kwargs: out_path (str): Output file name format (passed to ImageMagick) resolution (int): Required DPI (passed to ImageMagick) use_convert (bool): If False, we use Wand (if available) Returns: list: Paths to page PNG files """ if not out_path: prefix = '%s-' % fname[:-4] fd, out_path = tempfile.mkstemp(prefix=prefix, suffix='.png') os.close(fd) os.remove(out_path) fname = '%s[%s]' % (fname, ','.join(str(x - 1) for x in pages)) if use_convert or not WAND_AVAILABLE: command = "convert -density %d '%s' %s" command = command % (resolution, fname, out_path) sh_args = shlex.split(str(command)) ret = subprocess.call(sh_args) if ret > 0: raise Exception('Non-zero return code: "%s"' % command) else: from wand import image page_image_files = image.Image( filename=fname, resolution=resolution, ) with page_image_files.convert('png') as f: f.save(filename=out_path) return glob.glob('%s*' % out_path[:-4])
def _crop(self, scorefn: str): if self._magick_home: old_magick_home = os.environ["MAGICK_HOME"] os.environ["DEBUSSY"] = self._magick_home with image.Image(filename=scorefn) as i: i.trim() i.save(filename=scorefn) if self._magick_home: if old_magick_home: os.environ["MAGICK_HOME"] = old_magick_home else: del os.environ["MAGICK_HOME"]
def create_jpg(f): """Create multipage JPG from PDF. Create a JPG object from a local PDF file Input: f: Local path to PDF file Output: d: Dictionary of JPG objects """ d = dict() filepath = f assert os.path.exists(f) with wd.Image(filename=f, resolution=200) as img: page_images = [] for page_wand_image_seq in img.sequence: page_wand_image = wd.Image(page_wand_image_seq) page_jpeg_bytes = page_wand_image.make_blob(format="jpeg") page_jpeg_data = io.BytesIO(page_jpeg_bytes) page_image = Image.open(page_jpeg_data) page_images.append(page_image) d['page_count'] = len(page_images) d['pages'] = page_images return d
def pdf_page_to_png(src_pdf, pagenum = 0, resolution = 100,): ''' convert the each page in pdf to image''' dst_pdf = PyPDF2.PdfFileWriter() dst_pdf1 = PyPDF2.PdfFileWriter() dst_pdf.addPage(src_pdf.getPage(pagenum)) dst_pdf1.addPage(src_pdf.getPage(pagenum)) pdf_bytes = io.BytesIO() dst_pdf1.write(pdf_bytes) pdf_bytes.seek(0) img =image.Image(file = pdf_bytes, resolution = resolution) img.background_color = Color('white') img.alpha_channel = 'remove' img.convert("jpg") return img
def getwasted(image: BytesIO): io = BytesIO(image) io.seek(0) with wi.Image() as dst_image: with wi.Image(blob=io) as src_image: for frame in src_image.sequence: frame.transform_colorspace('gray') dst_image.sequence.append(frame) bts = dst_image.make_blob() i = BytesIO(bts) i.seek(0) im = Image.open(i) fil = Image.open('wasted.png') w, h = im.size filr = fil.resize((w, h), 5) flist = [] for frame in ImageSequence.Iterator(im): ci = im.convert('RGBA') ci.paste(filr, mask=filr) flist.append(ci) retimg = BytesIO() flist[0].save(retimg,format='gif', save_all=True, append_images=flist) retimg.seek(0) return(retimg)
def convert_image(path, frames): if os.path.exists(path): fname = os.path.splitext(path)[0] with image.Image(filename=path) as img: if frames > 1: print("%s has %d frames, cropping..." % (fname, frames)) img.crop(0, 0, width=img.width // frames, height=img.height) library.MagickSetCompressionQuality(img.wand, 00) new_fname = fname + '.png' print("Saving %s..." % (new_fname)) img.save(filename=new_fname) return new_fname else: print("%s does not exist!" % path) return None
def __MakeHighResolutionImage(self, img, cnt, res=300): #open the image first try: with wimage.Image(filename=img, resolution=res) as img_pdf: #change the background color to white img_pdf.background_color = Color('white') #remove the alpha channel -> RGBA to RGB img_pdf.alpha_channel = 'remove' #resize the image img_pdf.resize(960, 1376) #save the image img_pdf.save(filename=os.getcwd() + "/EndPoint/data/HighRes" + str(cnt) + ".jpg") except Exception as e: e.args print("error in making the image high res")
def generate(self, avatars, text, usernames): avatar = BytesIO(http.get_image_raw(avatars[0])) with image.Image(file=avatar) as img: img.transform(resize='400x400') img.liquid_rescale(width=int(img.width * 0.5), height=int(img.height * 0.5), delta_x=0.5, rigidity=0) img.liquid_rescale(width=int(img.width * 1.5), height=int(img.height * 1.5), delta_x=2, rigidity=0) b = BytesIO() img.save(file=b) b.seek(0) return send_file(b, mimetype='image/png')
def from_other_image(filename, format = None): with wi.Image(filename=filename) as wimg: # Auto-detect format if not specified if format is None: format = FORMAT_RGB if (wimg.colorspace != 'gray') else FORMAT_BW img = TBFImage(format, wimg.width, wimg.height) if wimg.sequence is not None: for i in range(len(wimg.sequence)): with wimg.sequence[i] as si: with si.clone() as sic: f = img.start_frame() _populate_frame_from_image(f, sic, format) f.duration = si.delay * 10 # 1/100s --> ms else: f = img.start_frame() _populate_frame_from_image(f, wimg, format) return img
def _render_thumbnail(self): from cStringIO import StringIO size = 200, 150 try: from PIL import Image, ImageOps except: logger.error( '%s: Pillow not installed, cannot generate thumbnails.' % e) return None try: # if wand is installed, than use it for pdf thumbnailing from wand import image except: wand_available = False else: wand_available = True if wand_available and self.extension and self.extension.lower( ) == 'pdf' and self.doc_file: logger.debug('Generating a thumbnail for document: {0}'.format( self.title)) with image.Image(filename=self.doc_file.path) as img: img.sample(*size) return img.make_blob('png') elif self.extension and self.extension.lower( ) in IMGTYPES and self.doc_file: img = Image.open(self.doc_file.path) img = ImageOps.fit(img, size, Image.ANTIALIAS) else: filename = finders.find('documents/{0}-placeholder.png'.format(self.extension), False) or \ finders.find('documents/generic-placeholder.png', False) if not filename: return None img = Image.open(filename) imgfile = StringIO() img.save(imgfile, format='PNG') return imgfile.getvalue()
def rescaler(self, img): blob = io.BytesIO() with WndImage.Image(blob=img) as img: img.format = 'jpeg' size = img.size coefBounds = range(self.lowerBound, self.upperBound) coef_x = random.choice(coefBounds) coef_y = random.choice(coefBounds) if random.choice((0, 1)) == 0: ch = ('div', 'mul') x_size = size[0] // coef_x y_size = size[1] // coef_y else: ch = ('mul', 'div') x_size = size[0] // coef_x y_size = size[1] // coef_y img.liquid_rescale(x_size, y_size) img.sample(size[0], size[1]) print(size[0], size[1]) img_bin = img.make_blob('jpeg') blob = io.BytesIO(b'{}'.format(img_bin)) return blob
def work(filename): print('\n' + filename) img = Image.open(filename) print(img.format) with image.Image(filename=filename.encode()) as iimage: print(iimage.compression) print('size', img.size) for tag, value in img.info.items(): print('{0} {1}'.format(tag, value)) try: exif_data = img._getexif() if exif_data: exif = { ExifTags.TAGS[k]: v for k, v in exif_data.items() if k in ExifTags.TAGS } for tag, value in exif.items(): print('Tag: {0} \t\t\t Value: {1}'.format(tag, value)) else: print('No EXIF data') except AttributeError: print('No EXIF data')
def create_chunk(wrapping, min, mag, flip, compress, full_path, index, name): if compress == "png": tmp = 'tmp.png' else: tmp = 'tmp.dds' imsize = () with image.Image(filename=full_path) as img: imsize = img.size if compress != "png": img.compression = compress img.save(filename=tmp) chunk = [] with open(tmp, mode='rb') as file: chunk += cm.int32tobytes(index) chunk += cm.int8tobytes(1) chunk += cm.int16tobytes(len(name)) chunk += name.encode("utf-8") chunk += cm.int32tobytes(imsize[0]) chunk += cm.int32tobytes(imsize[1]) chunk += cm.int8tobytes(compression_dict[compress]) chunk += cm.int8tobytes(texture_wrapping_dict[wrapping]) chunk += cm.int8tobytes(min_dict[min]) chunk += cm.int8tobytes(mag_dict[mag]) chunk += cm.int8tobytes(flip) b = file.read() chunk += cm.int32tobytes(len(b)) chunk += b os.remove(tmp) chunk = cm.create_chunk(chunk, cm.TEXTURE_CHUNK_TYPE) return chunk
class Document(ResourceBase): """ A document is any kind of information that can be attached to a map such as pdf, images, videos, xls... """ # Relation to the resource model content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) resource = generic.GenericForeignKey('content_type', 'object_id') doc_file = models.FileField(upload_to='documents', null=True, blank=True, verbose_name=_('File')) extension = models.CharField(max_length=128, blank=True, null=True) doc_type = models.CharField(max_length=128, blank=True, null=True) doc_url = models.URLField( blank=True, null=True, help_text=_('The URL of the document if it is external.'), verbose_name=_('URL')) def __unicode__(self): return self.title def get_absolute_url(self): return reverse('document_detail', args=(self.id, )) @property def name_long(self): if not self.title: return str(self.id) else: return '%s (%s)' % (self.title, self.id) def _render_thumbnail(self): from cStringIO import StringIO size = 200, 150 try: from PIL import Image, ImageOps except ImportError, e: logger.error( '%s: Pillow not installed, cannot generate thumbnails.' % e) return None try: # if wand is installed, than use it for pdf thumbnailing from wand import image except: wand_available = False else: wand_available = True if wand_available and self.extension and self.extension.lower( ) == 'pdf' and self.doc_file: logger.debug(u'Generating a thumbnail for document: {0}'.format( self.title)) try: with image.Image(filename=self.doc_file.path) as img: img.sample(*size) return img.make_blob('png') except: logger.debug( 'Error generating the thumbnail with Wand, cascading to a default image...' ) # if we are still here, we use a default image thumb if self.extension and self.extension.lower( ) in IMGTYPES and self.doc_file: img = Image.open(self.doc_file.path) img = ImageOps.fit(img, size, Image.ANTIALIAS) else: filename = finders.find('documents/{0}-placeholder.png'.format(self.extension), False) or \ finders.find('documents/generic-placeholder.png', False) if not filename: return None img = Image.open(filename) imgfile = StringIO() img.save(imgfile, format='PNG') return imgfile.getvalue()