Python Image.new() Examples

The following are 30 code examples of Image.new(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Image , or try the search function .
Example #1
Source File: base.py    From webterminal with GNU General Public License v3.0 6 votes vote down vote up
def move(self, src, dst, name):
        """
        Move file. Return new file path or raise an Exception.
        """

        stat = self.stat(src)
        
        if not stat['read'] or (stat['mime'] == 'directory' and self.command_disabled('rmdir')):
            raise PermissionDeniedError

        stat['realpath'] = src
        self._rm_tmb(stat) #can not do rmTmb() after _move()
        
        try:
            self._move(src, dst, name)
        except:
            raise NamedError(ElfinderErrorMessages.ERROR_MOVE, self._path(src))
        
        self._clear_cached_dir(self._dirname(src))
        self._clear_cached_stat(src)
        self._clear_cached_dir(dst)
        self._removed.append(stat)
        
        return self._join_path(dst, name) 
Example #2
Source File: ImageChops.py    From mxnet-lambda with Apache License 2.0 6 votes vote down vote up
def invert(image):
    "Invert a channel"

    image.load()
    return image._new(image.im.chop_invert())

##
# Compare images, and return lighter pixel value
# (max(image1, image2)).
# <p>
# Compares the two images, pixel by pixel, and returns a new image
# containing the lighter values.
#
# @param image1 First image.
# @param image1 Second image.
# @return An image object. 
Example #3
Source File: ImageChops.py    From CNCGToolKit with MIT License 6 votes vote down vote up
def lighter(image1, image2):
    "Select the lighter pixels from each image"

    image1.load()
    image2.load()
    return image1._new(image1.im.chop_lighter(image2.im))

##
# Compare images, and return darker pixel value
# (min(image1, image2)).
# <p>
# Compares the two images, pixel by pixel, and returns a new image
# containing the darker values.
#
# @param image1 First image.
# @param image1 Second image.
# @return An image object. 
Example #4
Source File: ImageMath.py    From CNCGToolKit with MIT License 6 votes vote down vote up
def __fixup(self, im1):
        # convert image to suitable mode
        if isinstance(im1, _Operand):
            # argument was an image.
            if im1.im.mode in ("1", "L"):
                return im1.im.convert("I")
            elif im1.im.mode in ("I", "F"):
                return im1.im
            else:
                raise ValueError, "unsupported mode: %s" % im1.im.mode
        else:
            # argument was a constant
            if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
                return Image.new("I", self.im.size, im1)
            else:
                return Image.new("F", self.im.size, im1) 
Example #5
Source File: ImageMath.py    From mxnet-lambda with Apache License 2.0 6 votes vote down vote up
def __fixup(self, im1):
        # convert image to suitable mode
        if isinstance(im1, _Operand):
            # argument was an image.
            if im1.im.mode in ("1", "L"):
                return im1.im.convert("I")
            elif im1.im.mode in ("I", "F"):
                return im1.im
            else:
                raise ValueError, "unsupported mode: %s" % im1.im.mode
        else:
            # argument was a constant
            if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
                return Image.new("I", self.im.size, im1)
            else:
                return Image.new("F", self.im.size, im1) 
Example #6
Source File: interval.py    From miasm with GNU General Public License v2.0 6 votes vote down vote up
def show(self, img_x=1350, img_y=20, dry_run=False):
        """
        show image representing the interval
        """
        try:
            import Image
            import ImageDraw
        except ImportError:
            print('cannot import python PIL imaging')
            return

        img = Image.new('RGB', (img_x, img_y), (100, 100, 100))
        draw = ImageDraw.Draw(img)
        i_min, i_max = self.hull()

        print(hex(i_min), hex(i_max))

        addr2x = lambda addr: ((addr - i_min) * img_x) // (i_max - i_min)
        for a, b in self.intervals:
            draw.rectangle((addr2x(a), 0, addr2x(b), img_y), (200, 0, 0))

        if dry_run is False:
            img.show() 
Example #7
Source File: sample.py    From wpgtk with GNU General Public License v2.0 6 votes vote down vote up
def create_sample(colors, f=os.path.join(WALL_DIR, ".tmp.sample.png")):
    im = Image.new("RGB", (480, 50), "white")
    pix = im.load()
    width_sample = im.size[0]//(len(colors)//2)

    for i, c in enumerate(colors[:8]):
        for j in range(width_sample*i, width_sample*i+width_sample):
            for k in range(0, 25):
                pix[j, k] = pywal.util.hex_to_rgb(c)

    for i, c in enumerate(colors[8:16]):
        for j in range(width_sample*i, width_sample*i+width_sample):
            for k in range(25, 50):
                pix[j, k] = pywal.util.hex_to_rgb(c)

    im.save(f) 
Example #8
Source File: mkfont.py    From spidriver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encode(font, c):
    im = Image.new("L", (128, 160))
    dr = ImageDraw.Draw(im)
    dr.text((10,40), c, font=font1, fill=255)
    # print im.getbbox()
    im = im.crop((10, 44, 16, 51))
    (w,h) = im.size
    nyb = (np.array(im).flatten() * 10 / 255).tolist()
    return nyb

    print c, "".join(["%x" % x for x in nyb])
    saved = 0
    for i in range(len(nyb)):
        if nyb[i:i+3] == [0,0,0]:
            saved += 1
    # print c, "saved", saved
    return len(nyb) - saved 
Example #9
Source File: pil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def new_image(self, **kwargs):
        back_color = kwargs.get("back_color", "white")
        fill_color = kwargs.get("fill_color", "black")

        if fill_color.lower() != "black" or back_color.lower() != "white":
            if back_color.lower() == "transparent":
                mode = "RGBA"
                back_color = None
            else:
                mode = "RGB"
        else:
            mode = "1"
            # L mode (1 mode) color = (r*299 + g*587 + b*114)//1000
            if fill_color.lower() == "black": fill_color = 0
            if back_color.lower() == "white": back_color = 255

        img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
        self.fill_color = fill_color
        self._idr = ImageDraw.Draw(img)
        return img 
Example #10
Source File: pil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def new_image(self, **kwargs):
        back_color = kwargs.get("back_color", "white")
        fill_color = kwargs.get("fill_color", "black")

        if fill_color.lower() != "black" or back_color.lower() != "white":
            if back_color.lower() == "transparent":
                mode = "RGBA"
                back_color = None
            else:
                mode = "RGB"
        else:
            mode = "1"
            # L mode (1 mode) color = (r*299 + g*587 + b*114)//1000
            if fill_color.lower() == "black": fill_color = 0
            if back_color.lower() == "white": back_color = 255

        img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
        self.fill_color = fill_color
        self._idr = ImageDraw.Draw(img)
        return img 
Example #11
Source File: pil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def new_image(self, **kwargs):
        back_color = kwargs.get("back_color", "white")
        fill_color = kwargs.get("fill_color", "black")

        if fill_color.lower() != "black" or back_color.lower() != "white":
            if back_color.lower() == "transparent":
                mode = "RGBA"
                back_color = None
            else:
                mode = "RGB"
        else:
            mode = "1"
            # L mode (1 mode) color = (r*299 + g*587 + b*114)//1000
            if fill_color.lower() == "black": fill_color = 0
            if back_color.lower() == "white": back_color = 255

        img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
        self.fill_color = fill_color
        self._idr = ImageDraw.Draw(img)
        return img 
Example #12
Source File: pil.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def new_image(self, **kwargs):
        back_color = kwargs.get("back_color", "white")
        fill_color = kwargs.get("fill_color", "black")

        if fill_color.lower() != "black" or back_color.lower() != "white":
            if back_color.lower() == "transparent":
                mode = "RGBA"
                back_color = None
            else:
                mode = "RGB"
        else:
            mode = "1"
            # L mode (1 mode) color = (r*299 + g*587 + b*114)//1000
            if fill_color.lower() == "black": fill_color = 0
            if back_color.lower() == "white": back_color = 255

        img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
        self.fill_color = fill_color
        self._idr = ImageDraw.Draw(img)
        return img 
Example #13
Source File: main.py    From rpi-magicmirror-eink with MIT License 6 votes vote down vote up
def main():
    epd = epd7in5b.EPD()
    epd.init()

    # For simplicity, the arguments are explicit numerical coordinates
    # image_red = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 255)    # 255: clear the frame
    # draw_red = ImageDraw.Draw(image_red)
    # image_black = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 255)    # 255: clear the frame
    # draw_black = ImageDraw.Draw(image_black)
    # font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24)
    # draw_red.rectangle((0, 6, 640, 40), fill = 0)
    # draw_red.text((200, 10), 'e-Paper demo', font = font, fill = 255)
    # draw_red.rectangle((200, 80, 600, 280), fill = 0)
    # draw_red.chord((240, 120, 580, 220), 0, 360, fill = 255)
    # draw_black.rectangle((20, 80, 160, 280), fill = 0)
    # draw_red.chord((40, 80, 180, 220), 0, 360, fill = 0)
    # epd.display_frame(epd.get_frame_buffer(image_black),epd.get_frame_buffer(image_red))

    # display images
    frame_black = epd.get_frame_buffer(Image.open('black.png'))
    frame_red = epd.get_frame_buffer(Image.open('white.png'))
    epd.display_frame(frame_black, frame_red) 
Example #14
Source File: gauge.py    From Reinforcement-Learning-for-Self-Driving-Cars with Apache License 2.0 6 votes vote down vote up
def render_simple_gauge(self, value=None, major_ticks=None, minor_ticks=None, label=None, font=None):
        """Helper function to create gauges with minimal code, eg:

            import Image
            import gauges

            im = Image.new("RGB", (200, 200), (255, 255, 255))
            g = gauges.GaugeDraw(im, 0, 100)
            g.render_simple_gauge(value=25, major_ticks=10, minor_ticks=2, label="25")
            im.save("simple_gauge_image.png", "PNG")

        Does not support dial labels, histogram dial background or setting colors..
        """
        if value is not None:
            self.add_needle(value)

        if major_ticks is not None:
            self.add_dial(major_ticks, minor_ticks, dial_font=font)

        if label is not None:
            self.add_text(text_list=label, text_font=font)

        self.render() 
Example #15
Source File: base.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def _unique_name(self, dir_, name, suffix = ' copy', check_num=True):
        """
        Return new unique name based on file name and suffix
        """
        
        ext  = ''
        m = re.search(r'\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$', name, re.IGNORECASE)
        if m:
            ext  = '.%s' % m.group(1)
            name = name[0:len(name)-len(m.group(0))] 
        
        m = re.search('(%s)(\d*)$' % suffix, name, re.IGNORECASE)
        if check_num and m and m.group(2):
            i = int(m.group(2))
            name = name[0:len(name)-len(m.group(2))]
        else:
            i = 1
            name += suffix

        return self._get_available_name(dir_, name, ext, i) 
Example #16
Source File: base.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def _img_square_fit(self, im, target, width, height, bgcolor = '#ffffff', destformat = None):
        """
        Put image to square
        """

        bg = Image.new('RGB', (width, height), bgcolor)

        if im.mode == 'RGBA':
            bg.paste(im, ((width-im.size[0])/2, (height-im.size[1])/2), im)
        else: #do not use a mask if file is not in RGBA mode.
            bg.paste(im, ((width-im.size[0])/2, (height-im.size[1])/2))

        if target:
            self._saveimage(bg, target, destformat if destformat else im.format)

        return bg 
Example #17
Source File: base.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def move(self, src, dst, name):
        """
        Move file. Return new file path or raise an Exception.
        """

        stat = self.stat(src)
        
        if not stat['read'] or (stat['mime'] == 'directory' and self.command_disabled('rmdir')):
            raise PermissionDeniedError

        stat['realpath'] = src
        self._rm_tmb(stat) #can not do rmTmb() after _move()
        
        try:
            self._move(src, dst, name)
        except:
            raise NamedError(ElfinderErrorMessages.ERROR_MOVE, self._path(src))
        
        self._clear_cached_dir(self._dirname(src))
        self._clear_cached_stat(src)
        self._clear_cached_dir(dst)
        self._removed.append(stat)
        
        return self._join_path(dst, name) 
Example #18
Source File: gen_rst.py    From deeppy with MIT License 5 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    # local import to avoid testing dependency on PIL:
    try:
        from PIL import Image
    except ImportError:
        import Image
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = width / float(width_in)
    scale_h = height / float(height_in)

    if height_in * scale_w <= height:
        scale = scale_w
    else:
        scale = scale_h

    width_sc = int(round(scale * width_in))
    height_sc = int(round(scale * height_in))

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # insert centered
    thumb = Image.new('RGB', (width, height), (255, 255, 255))
    pos_insert = ((width - width_sc) // 2, (height - height_sc) // 2)
    thumb.paste(img, pos_insert)

    thumb.save(out_fname) 
Example #19
Source File: base.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def _move(self, source, target_dir, name):
        """
        Move file into another parent directory.
        Return the new file path or raise ``os.error``.
        
        .. warning::
        
            **Not implemented**, each driver must provide its own
            imlementation.
        """
        raise NotImplementedError 
Example #20
Source File: Base.py    From captchacker2 with GNU General Public License v3.0 5 votes vote down vote up
def render(self, size=None):
        """Render this CAPTCHA, returning a PIL image"""
        if size is None:
            size = self.defaultSize
        img = Image.new("RGB", size)
        return self._renderList(self._layers, Image.new("RGB", size)) 
Example #21
Source File: gen_rst.py    From polylearn with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    # local import to avoid testing dependency on PIL:
    try:
        from PIL import Image
    except ImportError:
        import Image
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = width / float(width_in)
    scale_h = height / float(height_in)

    if height_in * scale_w <= height:
        scale = scale_w
    else:
        scale = scale_h

    width_sc = int(round(scale * width_in))
    height_sc = int(round(scale * height_in))

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # insert centered
    thumb = Image.new('RGB', (width, height), (255, 255, 255))
    pos_insert = ((width - width_sc) // 2, (height - height_sc) // 2)
    thumb.paste(img, pos_insert)

    thumb.save(out_fname)
    # Use optipng to perform lossless compression on the resized image if
    # software is installed
    if os.environ.get('SKLEARN_DOC_OPTIPNG', False):
        try:
            subprocess.call(["optipng", "-quiet", "-o", "9", out_fname])
        except Exception:
            warnings.warn('Install optipng to reduce the size of the generated images') 
Example #22
Source File: barcode.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def _init(self, code):
            size = self.calculate_size(len(code[0]), len(code), self.dpi)
            self._image = Image.new("RGB", size, self.background)
            self._draw = ImageDraw.Draw(self._image) 
Example #23
Source File: images_stub.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _EncodeImage(self, image, output_encoding, substitution_rgb=None):
    """Encode the given image and return it in string form.

    Args:
      image: PIL Image object, image to encode.
      output_encoding: ImagesTransformRequest.OutputSettings object.
      substitution_rgb: The color to use for transparent pixels if the output
        format does not support transparency.

    Returns:
      str - Encoded image information in given encoding format.  Default is PNG.
    """
    image_string = StringIO.StringIO()
    image_encoding = PNG

    if output_encoding.mime_type() == images_service_pb.OutputSettings.WEBP:
      image_encoding = WEBP

    if output_encoding.mime_type() == images_service_pb.OutputSettings.JPEG:
      image_encoding = JPEG






      if substitution_rgb:



        blue = substitution_rgb & 0xFF
        green = (substitution_rgb >> 8) & 0xFF
        red = (substitution_rgb >> 16) & 0xFF
        background = Image.new(RGB, image.size, (red, green, blue))
        background.paste(image, mask=image.convert(RGBA).split()[3])
        image = background
      else:
        image = image.convert(RGB)

    image.save(image_string, image_encoding)
    return image_string.getvalue() 
Example #24
Source File: __init__.py    From 3DGCN with MIT License 5 votes vote down vote up
def MolsToImage(mols, subImgSize=(200, 200), legends=None, **kwargs):
    """
    """
    try:
        import Image
    except ImportError:
        from PIL import Image
    if legends is None:
        legends = [None] * len(mols)
    res = Image.new("RGBA", (subImgSize[0] * len(mols), subImgSize[1]))
    for i, mol in enumerate(mols):
        res.paste(MolToImage(mol, subImgSize, legend=legends[i], **kwargs), (i * subImgSize[0], 0))
    return res 
Example #25
Source File: ImageTk.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def _pilbitmap_check():
    global _pilbitmap_ok
    if _pilbitmap_ok is None:
        try:
            im = Image.new("1", (1,1))
            Tkinter.BitmapImage(data="PIL:%d" % im.im.id)
            _pilbitmap_ok = 1
        except Tkinter.TclError:
            _pilbitmap_ok = 0
    return _pilbitmap_ok

# --------------------------------------------------------------------
# PhotoImage

##
# Creates a Tkinter-compatible photo image.  This can be used
# everywhere Tkinter expects an image object.  If the image is an RGBA
# image, pixels having alpha 0 are treated as transparent. 
Example #26
Source File: base.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def _img_resize(self, im, target, width, height, keepProportions = False, resizeByBiggerSide = True, destformat = None):
        """
        Resize image and return the new image.
        """
    
        s = im.size
        size_w = width
        size_h = height

        if keepProportions:
            orig_w, orig_h = s[0], s[1]
            
            #Resizing by biggest side
            if resizeByBiggerSide:
                if (orig_w > orig_h):
                    size_h = orig_h * width / orig_w
                    size_w = width
                else:
                    size_w = orig_w * height / orig_h
                    size_h = height
            elif orig_w > orig_h:
                size_w = orig_w * height / orig_h
                size_h = height
            else:
                size_h = orig_h * width / orig_w
                size_w = width

        resized = im.resize((size_w, size_h), Image.ANTIALIAS)
        
        if target:
            self._saveimage(resized, target, destformat if destformat else im.format)
        
        return resized 
Example #27
Source File: cloudpickle.py    From spark-cluster-deployment with Apache License 2.0 5 votes vote down vote up
def _generateImage(size, mode, str_rep):
    """Generate image from string representation"""
    import Image
    i = Image.new(mode, size)
    i.fromstring(str_rep)
    return i 
Example #28
Source File: cloudpickle.py    From spark-cluster-deployment with Apache License 2.0 5 votes vote down vote up
def _change_cell_value(cell, newval):
    """ Changes the contents of 'cell' object to newval """
    return new.function(cell_changer_code, {}, None, (), (cell,))(newval) 
Example #29
Source File: base.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def _save_uploaded(self, uploaded_file, dir_, name, **kwargs):
        """
        Save the Django 
        `UploadedFile <https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#django.core.files.uploadedfile.UploadedFile>`_
        object and return its new path.
        
        .. warning::
        
            **Not implemented**, each driver must provide its own
            imlementation.
        """
        raise NotImplementedError 
Example #30
Source File: base.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def _save(self, fp, dir_, name):
        """
        Create new file and write into it from file pointer.
        Return the new file path or raise an py:class:`Exception`.
        
        .. warning::
        
            **Not implemented**, each driver must provide its own
            imlementation.
        """
        raise NotImplementedError