def create_thumbnail (path, thumbpath, uri, type="large"): """Create a thumbnail at path and return path""" mtime = os.stat(path)[8] size = os.path.getsize(path) if int(size) > MAX_THUMBSIZE: debug('File too large!',0) return None try: im = Image.open(path) except: return None w,h = im.size if type=='large': geo = (256,256) else: geo = (128,128) im.thumbnail(geo) # set thumbnail attributes info={} info['Thumb::MTime']=str(mtime) info['Thumb::Image::Width']=str(w) info['Thumb::Image::Height'] =str(h) info['Software']='Gourmet Recipe Manager' info['URI']=str(uri) # now we must create our image guy import PngImagePlugin pnginfo = PngImagePlugin.PngInfo() for k,v in info.items(): pnginfo.add_text(k,v) im.save(thumbpath, pnginfo=pnginfo) # we must make all thumbnails permissions 700 os.chmod(thumbpath,0700) return thumbpath
def get_freedesktop_pnginfo(filename, image=None, thumb_info=None): """Gets png metadata for the thumbnail. :param filename: image filename :type filename: string :returns: png info :rtype: PngImagePlugin.PngInfo """ full_info = THUMB_INFO.copy() if thumb_info: full_info.update(thumb_info) file_stat = os.stat(filename) info = PngImagePlugin.PngInfo() info.add_text('Thumb::URI', get_uri(filename)) info.add_text('Thumb::MTime', str(get_mtime(filename, file_stat))) info.add_text('Thumb::Size', str(get_filesize(filename, file_stat))) if 'software' in full_info: info.add_text('Thumb::Software', full_info['software']) if 'height' in full_info: info.add_text('Thumb::Image::Height', str(full_info['height'])) elif image: info.add_text('Thumb::Image::Height', str(image.size[1])) if 'width' in full_info: info.add_text('Thumb::Image::Width', str(full_info['width'])) elif image: info.add_text('Thumb::Image::Width', str(image.size[0])) return info
def interlace(output, inputs): frames = [Image.open(fn).convert("RGB") for fn in inputs] assert len(frames) > 0, "Must have at least one input frame." sizes = set() for fr in frames: sizes.add(fr.size) assert len(sizes) == 1, "All input images must have the same size." w, h = sizes.pop() N = len(frames) out = Image.new("RGB", (w, h * N)) for j in range(h): for i in range(w): for fn, f in enumerate(frames): out.putpixel((i, j * N + fn), f.getpixel((i, j))) # When loading this image, the graphics library expects to find a text # chunk that specifies how many frames this animation represents. If # you post-process the output of this script with some kind of # optimizer tool (eg pngcrush or zopflipng) make sure that your # optimizer preserves this text chunk. meta = PngImagePlugin.PngInfo() meta.add_text("Frames", str(N)) out.save(output, pnginfo=meta)
def onSaveTexture(event): if not gPlanetSourceImage or gGenerateThread.isAlive(): return if event.widget.cget("highlightbackground") == gNonHoverColor: return # generate meta information meta = PngImagePlugin.PngInfo() for key in gParamsMap.keys(): meta.add_text(key, str(gParamsMap[key].get())) for i in range(0, len(gColorMapItems), 2): meta.add_text("color%d" % (i // 2), gColorMapItems[i].cget("bg")) # save image gPlanetSourceImage.convert("RGB").save(OUTPUT_FILE, pnginfo=meta) showStatus("Saved to " + OUTPUT_FILE) # start 3d sphere process global gSphereProc if gSphereProc: gSphereProc.kill() w, h = gRoot.winfo_reqwidth(), gRoot.winfo_reqheight() top = gRoot.winfo_children()[0] gSphereProc = subprocess.Popen([ "python", "space.py", "--texture", OUTPUT_FILE, "--winsize", "{0};{0}".format(h), "--winpos", "{0};{1}".format(gRoot.winfo_x() + w, top.winfo_rooty()) ])
def PngSave(im, file): # From http://blog.client9.com/2007/08/28/python-pil-and-png-metadata-take-2.html # these can be automatically added to Image.info dict # they are not user-added metadata reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') # undocumented class import PngImagePlugin meta = PngImagePlugin.PngInfo() # copy metadata into new object for k, v in im.info.iteritems(): if k in reserved: continue meta.add_text(k, v, 0) # and save im.save(file, "PNG", pnginfo=meta)
class IconImporter(object): def __init__(self, feed, page_data=None, force=False): self.feed = feed self.force = force self.page_data = page_data self.feed_icon, _ = MFeedIcon.objects.get_or_create(feed_id=self.feed.pk) def save(self): if not self.force and self.feed.favicon_not_found: # print 'Not found, skipping...' return if not self.force and not self.feed.favicon_not_found and self.feed_icon.icon_url: # print 'Found, but skipping...' return image, image_file, icon_url = self.fetch_image_from_page_data() if not image: image, image_file, icon_url = self.fetch_image_from_path(force=self.force) if image: try: ico_image = self.load_icon(image_file) if ico_image: image = ico_image except ValueError: # print "Bad .ICO" pass image = self.normalize_image(image) color = self.determine_dominant_color_in_image(image) image_str = self.string_from_image(image) if (self.feed_icon.color != color or self.feed_icon.data != image_str or self.feed_icon.icon_url != icon_url or self.feed_icon.not_found): self.feed_icon.data = image_str self.feed_icon.icon_url = icon_url self.feed_icon.color = color self.feed_icon.not_found = False self.feed_icon.save() self.feed.favicon_color = color self.feed.favicon_not_found = False else: self.feed_icon.not_found = True self.feed.favicon_not_found = True self.feed.save() return not self.feed.favicon_not_found def load_icon(self, image_file, index=None): ''' Load Windows ICO image. See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format description. Cribbed and modified from http://djangosnippets.org/snippets/1287/ ''' try: image_file.seek(0) header = struct.unpack('<3H', image_file.read(6)) except Exception, e: return # Check magic if header[:2] != (0, 1): return # Collect icon directories directories = [] for i in xrange(header[2]): directory = list(struct.unpack('<4B2H2I', image_file.read(16))) for j in xrange(3): if not directory[j]: directory[j] = 256 directories.append(directory) if index is None: # Select best icon directory = max(directories, key=operator.itemgetter(slice(0, 3))) else: directory = directories[index] # Seek to the bitmap data image_file.seek(directory[7]) prefix = image_file.read(16) image_file.seek(-16, 1) if PngImagePlugin._accept(prefix): # Windows Vista icon with PNG inside try: image = PngImagePlugin.PngImageFile(image_file) except IOError: return else: # Load XOR bitmap image = BmpImagePlugin.DibImageFile(image_file) if image.mode == 'RGBA': # Windows XP 32-bit color depth icon without AND bitmap pass else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0] image.tile[0] = d, (0, 0) + image.size, o, a # Calculate AND bitmap dimensions. See # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage # for description offset = o + a[1] * image.size[1] stride = ((image.size[0] + 31) >> 5) << 2 size = stride * image.size[1] # Load AND bitmap image_file.seek(offset) string = image_file.read(size) mask = Image.fromstring('1', image.size, string, 'raw', ('1;I', stride, -1)) image = image.convert('RGBA') image.putalpha(mask) return image
except ImportError: print "This script requires the Python Imaging Library to be installed." sys.exit(1) frames = [Image.open(fn).convert("RGB") for fn in sys.argv[1:-1]] assert len(frames) > 0, "Must have at least one input frame." sizes = set() for fr in frames: sizes.add(fr.size) assert len(sizes) == 1, "All input images must have the same size." w, h = sizes.pop() N = len(frames) out = Image.new("RGB", (w, h * N)) for j in range(h): for i in range(w): for fn, f in enumerate(frames): out.putpixel((i, j * N + fn), f.getpixel((i, j))) # When loading this image, the graphics library expects to find a text # chunk that specifies how many frames this animation represents. If # you post-process the output of this script with some kind of # optimizer tool (eg pngcrush or zopflipng) make sure that your # optimizer preserves this text chunk. meta = PngImagePlugin.PngInfo() meta.add_text("Frames", str(N)) out.save(sys.argv[-1], pnginfo=meta)
def get_pnginfo(file_path): info = PngImagePlugin.PngInfo() info.add_text("Thumb::URI", self.get_uri(file_path)) mtime = str(os.path.getmtime(file_path)) info.add_text("Thumb::MTime", mtime) return info