Python PIL.Image 模块,new() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.new()

项目:moo    作者:no-context    | 项目源码 | 文件源码
def _normalize(self):
        # costumes
        if self.costume:
            # Make sure it's in costumes
            if self.costume not in self.costumes:
                self.costumes.append(self.costume)
        else:
            # No costume!
            if self.costumes:
                self.costume = self.costumes[0]
            else:
                BLACK = (0, 0, 0)
                self.costume = Costume("blank", Image.new((1, 1), BLACK))
                self.costumes = [self.costume]

        # scripts
        for script in self.scripts:
            script._normalize()

        # sort scripts by y position
        have_position = [s for s in self.scripts if s.pos]
        no_position = [s for s in self.scripts if not s.pos]
        have_position.sort(key=lambda s: (s.pos[1], s.pos[0]))
        self.scripts = have_position + no_position
项目:Archur    作者:Foxboron    | 项目源码 | 文件源码
def generate_img(output="", theme={}, text="", resolution=(1920,1080)):

    # img = Image.open(backdrop)
    img = Image.new("RGB", resolution, theme["background"])
    W, H = img.size

    logo = Image.open(DEFAULT_DIR+"/assets/logo.png")
    colorized_img = ImageOps.colorize(logo.convert("L"), theme["text"], theme["background"])
    size = int((W/100)*17)
    logo_newsize = colorized_img.resize((size, size), Image.ANTIALIAS)
    img.paste(logo_newsize, (int((W-size)/2), int((H-size)/2)))

    draw = ImageDraw.Draw(img)

    base_font_pixle = int((56/1920)*resolution[0])

    font = ImageFont.truetype("DejaVuSansMono.ttf", base_font_pixle)
    w, h = font.getsize(text)

    text_draw(draw, text, base_font_pixle, img.size, theme)

    img.save(output, quality=100)
项目:meme_get    作者:memegen    | 项目源码 | 文件源码
def makeglyphs():

    for i in range(0, len(C)):
        im = Image.new("RGB", (100, 110))
        dr = ImageDraw.Draw(im)
        font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124)
        dr.text((0, -25), C[i], (255, 255, 255), font=font)

        fwx = firstwhitex(im)

        im = Image.new("RGB", (100, 110))
        dr = ImageDraw.Draw(im)
        font = ImageFont.truetype(os.path.join(os.path.dirname(__file__),"fonts/Impact.ttf"), 124)
        dr.text((-fwx, -26), C[i], (255, 255, 255), font=font)

        cimgs.append(im)

# make threshold image
项目:BayerMatrix    作者:tromero    | 项目源码 | 文件源码
def MakeBayer(matrixSize, savePng, pngTileCount):
    pngFilename = 'bayer%d.png' % matrixSize
    if (pngTileCount > 1):
        pngFilename = 'bayer%dtile%d.png' % (matrixSize, pngTileCount)

    matrix = InitBayer(0, 0, matrixSize, 0, 1)

    if (savePng):
        from PIL import Image
        brightnessMultiplier = {16:1,8:4,4:16,2:64}
        img = Image.new('RGB', (matrixSize*pngTileCount,
                                matrixSize*pngTileCount))
        imgData = img.load()
        for y in range(img.height):
            for x in range(img.width):
                value = matrix[y % matrixSize][x % matrixSize]
                value *= brightnessMultiplier[matrixSize]
                color = (value, value, value)
                imgData[x,y] = color
        img.save(pngFilename, "PNG")
        print('Saved %s' % pngFilename)
    else:
        print('Bayer Matrix %s' % matrixSize)
        print(matrix)
项目:Programming-Collective-Intelligence    作者:clyyuanzi    | 项目源码 | 文件源码
def draw2d(data,labels,jpeg='mds2d.jpg'):
    img=Image.new('RGB',(2000,2000),(255,255,255))
    draw=ImageDraw.Draw(img)
    for i in range(len(data)):
        x=(data[i][0]+0.5)*1000
        y=(data[i][1]+0.5)*1000
        draw.text((x,y),labels[i],(0,0,0))
    img.save(jpeg,'JPEG')
项目:imagepaste    作者:robinchenyu    | 项目源码 | 文件源码
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)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, master, text, foreground="black", truetype_font=None, font_path=None, family=None, size=None, **kwargs):   
        if truetype_font is None:
            if font_path is None:
                raise ValueError("Font path can't be None")

            # Initialize font
            truetype_font = ImageFont.truetype(font_path, size)

        width, height = truetype_font.getsize(text)

        image = Image.new("RGBA", (width, height), color=(0,0,0,0))
        draw = ImageDraw.Draw(image)

        draw.text((0, 0), text, font=truetype_font, fill=foreground)

        self._photoimage = ImageTk.PhotoImage(image)
        Label.__init__(self, master, image=self._photoimage, **kwargs)
项目:HugoPhotoSwipe    作者:GjjvdBurg    | 项目源码 | 文件源码
def create_thumb_js(self, mode=None, pth=None):
        """ Create the thumbnail using SmartCrop.js """
        if pth is None:
            raise ValueError("path can't be None")

        # save a copy of the image with the correct orientation in a temporary 
        # file
        _, tmpfname = tempfile.mkstemp(suffix='.'+settings.output_format)
        self.original_image.save(tmpfname, quality=95)

        # Load smartcrop and set options
        nwidth, nheight = self.resize_dims(mode)
        logging.info("[%s] SmartCrop.js new dimensions: %ix%i" % (self.name, 
            nwidth, nheight))
        command = [settings.smartcrop_js_path, '--width', str(nwidth), 
                '--height', str(nheight), tmpfname, pth]
        logging.info("[%s] SmartCrop.js running crop command." % self.name)
        check_output(command)

        # remove the temporary file
        os.remove(tmpfname)

        return pth
项目:Instagram-API    作者:danleyb2    | 项目源码 | 文件源码
def createIconGD(file, size=100, raw=True):
        """
        Implements the actual logic behind creating the icon/thumbnail

        :type file: str
        :param file: path to the file name
        :rtype: image
        :return: icon/thumbnail for the video
        """
        image = Image.open(file)
        width, height = image.size

        if width > height:
            y = 0
            x = (width - height) / 2
            smallestSide = height
        else:
            x = 0
            y = (height - width) / 2
            smallestSide = width

        # image_p = Image.new('RGB',(size, size))
        # image = Image.frombytes('RGBa',(size,size),file_get_contents(file))

        image.thumbnail((size, size))

        ##todo convert to jpeg
        i = image.tobytes()
        image.close()
        # image_p.close()
        return i
项目:document_clipper    作者:reclamador    | 项目源码 | 文件源码
def image_to_pdf(self, img, pdf_path=None, **kwargs):
        """
        Convert image to pdf.
        :param img: image file opened by PIL
        :param pdf_path: path to save pdf
        :param kwargs: any parameter accepted by Image.save i.e. quality
        :return:
        """
        processor = ResizeToFit(width=self.max_size_in_pixels[0], height=self.max_size_in_pixels[1])
        img = processor.process(img)
        # Create a white canvas and paste the image
        final_img_width = min(img.size[0], self.max_size_in_pixels[0])
        final_img_height = min(img.size[1], self.max_size_in_pixels[1])
        tmp_image = Image.new("RGB", (final_img_width, final_img_height), "white")
        margin_left = 0
        margin_top = 0
        tmp_image.paste(img, (margin_left, margin_top,
                              final_img_width, final_img_height))

        # Save the image as .pdf file
        if not pdf_path:
            f = NamedTemporaryFile(delete=False)
            pdf_path = f.name
        tmp_image.save(pdf_path, "PDF", resolution=100.0, **kwargs)
        return pdf_path
项目:neural-fonts    作者:periannath    | 项目源码 | 文件源码
def drawChars(charset, font, char_size):
    src_font = ImageFont.truetype(font, 150)
    canvas = Image.new("RGB", (char_size*21, char_size*19), (255, 255, 255))  # 42 -> 21
    x_pos = 0
    y_pos = 0
    for c in charset:
        e = draw_single_char(c, src_font, char_size, x_offset=50, y_offset=20)
        canvas.paste(e, (x_pos * char_size, y_pos * char_size))
        x_pos = x_pos + 1
        if x_pos >= 21: # 42 -> 21
            x_pos = 0
            y_pos = y_pos + 1
    draw = ImageDraw.Draw(canvas)
    for i in range(20): # 41 -> 20
      draw.line([((i+1)*char_size,0), ((i+1)*char_size, char_size*19)], fill = (0, 0, 0), width=5)
    for i in range(18):
      draw.line([(0, (i+1)*char_size), (char_size*21, (i+1)*char_size)], fill = (0, 0, 0), width=5) # 42 -> 21

    canvas.save("399_image.png")
项目:Material-Design-Avatar    作者:today4king    | 项目源码 | 文件源码
def avatar_gen_img(self):
        font_size = int(self.size / 10 * 8)
        pic_size = self.size
        an, is_letter = self.avatar_name()
        font = self.zh_font_file_name
        if is_letter:
            font = self.en_font_file_name
            font_size = int(self.size / 10 * 11)

        font_file = os.path.abspath(os.path.join(self.font_dir, font))
        pygame.init()
        f = pygame.font.Font(font_file, font_size)
        is_light=self.is_light_color(self.avatar_background_color())
        rtext = f.render(an.upper(), True, (0,0,0) if is_light else (255, 255, 255))
        # pygame.image.save(rtext, '%s.png' % an)
        mode = 'RGBA'
        astr = pygame.image.tostring(rtext, 'RGBA')
        circle = Image.new("RGBA", (self.size, self.size))
        word = Image.frombytes(mode, f.size(an), astr)
        word_x = int((pic_size - word.size[0]) / 2)
        word_y = int(word_x * 0.9)
        if is_letter:
            word_y = int((pic_size - word.size[1]) / 2)
        draw = ImageDraw.Draw(circle)
        draw.ellipse((0, 0, self.size , self.size ),
                     fill=self.avatar_background_color(), outline=self.avatar_background_color())
        draw.point((100, 100), 'red')
        r, g, b, a = word.split()
        circle.paste(word, (word_x, word_y), a)
        sharpness = ImageEnhance.Sharpness(circle)
        # circle = sharpness.enhance(7.0)

        # im.show()

        # circle.show()

        # print(circle)
        return circle
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def test_crop(self):
        """Test UPLOADER crop works."""
        u = Uploader()
        size = (100, 100)
        im = Image.new('RGB', size)
        folder = tempfile.mkdtemp()
        u.upload_folder = folder
        im.save(os.path.join(folder, 'image.png'))
        coordinates = (0, 0, 50, 50)
        file = FileStorage(filename=os.path.join(folder, 'image.png'))
        with patch('pybossa.uploader.Image', return_value=True):
            err_msg = "It should crop the image"
            assert u.crop(file, coordinates) is True, err_msg

        with patch('pybossa.uploader.Image.open', side_effect=IOError):
            err_msg = "It should return false"
            assert u.crop(file, coordinates) is False, err_msg
项目:tensorflow-study    作者:bob-chen    | 项目源码 | 文件源码
def read_image(filename):
    f = open(filename, 'rb')
    index = 0
    buf = f.read()
    f.close()

    magic, images, rows, columns = struct.unpack_from('>IIII' , buf , index)
    index += struct.calcsize('>IIII')
    for i in xrange(images):
        #for i in xrange(2000):
        image = Image.new('L', (columns, rows))

        for x in xrange(rows):
            for y in xrange(columns):
                image.putpixel((y, x), int(struct.unpack_from('>B', buf, index)[0]))
                index += struct.calcsize('>B')


        print 'save ' + str(i) + 'image'
        image.save('./test/' + str(i) + '.png')
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def new_image(self, **kwargs):
        back_color = kwargs.get("fill_color", "white")
        fill_color = kwargs.get("back_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"

        img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
        self.fill_color = fill_color
        self._idr = ImageDraw.Draw(img)
        return img
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def whitespace(image, size, whitespace=False, whitespace_color=None, **kwargs):
    if not whitespace:
        return image

    if whitespace_color is None:
        whitespace_color = FILER_WHITESPACE_COLOR
    if whitespace_color is None:
        whitespace_color = '#fff'

    old_image = image
    source_x, source_y = image.size
    target_x, target_y = size

    image = Image.new('RGBA', (target_x, target_y), whitespace_color)
    if source_x < target_x and source_y < target_y:  # whitespace all around
        image.paste(old_image, (
            (target_x - source_x) / 2, (target_y - source_y) / 2))
    elif source_x < target_x:  # whitespace on top and bottom only
        image.paste(old_image, ((target_x - source_x) / 2, 0))
    elif source_y < target_y:  # whitespace on sides only
        image.paste(old_image, (0, (target_y - source_y) / 2))
    else:  # no whitespace needed
        image = old_image

    return image
项目:deeplab_v1_tf1.0    作者:automan000    | 项目源码 | 文件源码
def decode_labels(mask):
    """Decode batch of segmentation masks.

    Args:
      label_batch: result of inference after taking argmax.

    Returns:
      An batch of RGB images of the same size
    """
    img = Image.new('RGB', (len(mask[0]), len(mask)))
    pixels = img.load()
    for j_, j in enumerate(mask):
        for k_, k in enumerate(j):
            if k < 21:
                pixels[k_,j_] = label_colours[k]
    return np.array(img)
项目:meme_get    作者:memegen    | 项目源码 | 文件源码
def thres(pil_Image):
    """ Thresholding the image
    """
    w, h = pil_Image.size
    thim = Image.new("RGB", (w, h))
    thdr = ImageDraw.Draw(thim)
    PX = pil_Image.load()
    # make threshold image
    for x in range(0, w):
        for y in range(0, h):
            r, g, b = PX[x, y][:3]
            hsv = rgb2hsv(r, g, b)
            if hsv[2] > 0.9 and hsv[1] < 0.1:
                thdr.point([x, y], fill=(0, 0, 0))
            else:
                thdr.point([x, y], fill=(255, 255, 255))
    thim.show()
    return thim
项目:pydrm    作者:notro    | 项目源码 | 文件源码
def demo(drm, start):
    """simple partial update demo - draw random shapes"""

    # Use a monochrome image to force 0/1 values
    image = Image.new('1', drm.image.size)

    # prepare for drawing
    draw = ImageDraw.Draw(image)
    width, height = drm.image.size

    font = ImageFont.truetype(FONT_FILE, FONT_SIZE)

    counter = start & 0xffff

    while True:
        draw.rectangle((0, 0, width, height), fill='black', outline='black')
        draw.text((0, 0), '{c:04X}'.format(c=counter), fill='white', font=font)
        counter = (counter + 1) & 0xffff

        # display image on the panel
        image.convert('RGBX')
        drm.image.paste(image)
        drm.flush()

# main
项目:SecureSnaps    作者:NITDgpOS    | 项目源码 | 文件源码
def shred(self,args):
        image_path = args.path
        SHREDS = 250
        image = Image.open(image_path)
        # shredded = Image.new("1", image.size)
        width, height = image.size
        shred_width = width // SHREDS
        size = shred_width * SHREDS
        shredded = Image.new("RGB", (size, height))
        sequence = list(range(0, SHREDS))
        shuffle(sequence)
        for i, shred_index in enumerate(sequence):
            shred_x1, shred_y1 = shred_width * shred_index, 0
            shred_x2, shred_y2 = shred_x1 + shred_width, height
            region = image.crop((shred_x1, shred_y1, shred_x2, shred_y2))
            shredded.paste(region, (shred_width * i, 0))
            shredded.save(image_path)
项目:reddit-iambic-pentameter    作者:pmichel31415    | 项目源码 | 文件源码
def make_image(text, fontsize=45, output_file='tmp.png', fontname='HamletOrNot.ttf'):
    """Make an image out of a poem"""
    # Get font
    font = ImageFont.truetype(fontname, fontsize * factor)
    # Compute height
    num_lines = (1 + text.strip().count('\n'))
    height = num_lines * font.getsize(text[:10])[1] / factor + 2 * pad
    # Compute width
    font_length = max(font.getsize(line)[0] for line in text.split('\n'))
    width = font_length / factor + 2 * pad
    # Create big image and draw text
    image = Image.new("RGBA", (width * factor, height * factor), (241, 241, 212))
    draw = ImageDraw.Draw(image)
    draw.text((pad * factor, pad * factor), text, (0, 0, 0), font=font)
    # Resize with antialiasing
    img_resized = image.resize((width, height), Image.ANTIALIAS)
    # Save to file
    img_resized.save(output_file)
项目:moo    作者:no-context    | 项目源码 | 文件源码
def convert(self, *formats):
        """Return an Image instance with the first matching format.

        For each format in ``*args``: If the image's :attr:`format` attribute
        is the same as the format, return self, otherwise try the next format.

        If none of the formats match, return a new Image instance with the
        last format.

        """
        for format in formats:
            format = Image.image_format(format)
            if self.format == format:
                return self
        else:
            return self._convert(format)
项目:Software-Architecture-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def mandelbrot_calc_set(w, h, max_iteration=10000, output='mandelbrot_mp.png'):
    """ Calculate a mandelbrot set given the width, height and
    maximum number of iterations """

    image = Image.new("RGB", (w, h))
    image_rows = pymp.shared.dict()

    with pymp.Parallel(4) as p:
        for y in p.range(0, h):
            mandelbrot_calc_row(y, w, h, image_rows, max_iteration)

    for i in range(w*h):
        x,y = i % w, i // w
        image.putpixel((x,y), image_rows[i])

    image.save(output, "PNG")
    print('Saved to',output)
项目:Software-Architecture-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def mandelbrot_main(w, h, max_iterations=1000, output='mandelbrot_celery.png'):
    """ Main function for mandelbrot program with celery """

    job = group([mandelbrot_calc_row.s(y, w, h, max_iterations) for y in range(h)])
    result = job.apply_async()

    image = Image.new('RGB', (w, h))

    for image_rows in result.join():
        for k,v in image_rows.items():
            k = int(k)
            v = tuple(map(int, v))
            x,y = k % args.width, k // args.width
            image.putpixel((x,y), v)

    image.save(output, 'PNG')
    print('Saved to',output)
项目:Software-Architecture-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def mandelbrot_calc_set(w, h, max_iteration=10000, output='mandelbrot_mp.png'):
    """ Calculate a mandelbrot set given the width, height and
    maximum number of iterations """

    image = Image.new("RGB", (w, h))
    image_rows = pymp.shared.dict()

    with pymp.Parallel(4) as p:
        for y in p.range(0, h):
            mandelbrot_calc_row(y, w, h, image_rows, max_iteration)

    for i in range(w*h):
        x,y = i % w, i // w
        image.putpixel((x,y), image_rows[i])

    image.save(output, "PNG")
    print('Saved to',output)
项目:PSPNet-Keras-tensorflow    作者:Vladkryvoruchko    | 项目源码 | 文件源码
def drawSimpleSegment(self):

        #Drawing module
        im_Width, im_Height = self.pred_size
        prediction_image = Image.new("RGB", (im_Width, im_Height) ,(0,0,0))
        prediction_imageDraw = ImageDraw.Draw(prediction_image)

        #BASE all image segmentation
        for i in range(im_Width):
            for j in range(im_Height):
                #get matrix element class(0-149)
                px_Class = self.predicted_classes[j][i]
                #assign color from .mat list
                put_Px_Color = tuple(self.class_colors['colors'][px_Class])

                #drawing
                prediction_imageDraw.point((i,j), fill=put_Px_Color)

        #Resize to original size and save
        self.coef, self.h_pad, self.w_pad = self.calculateResize()
        FullHdOutImage = self.resizeToOutput(prediction_image, self.coef, self.h_pad, self.w_pad)
        FullHdOutImage = Image.blend(FullHdOutImage, self.im, 0.5)

        return FullHdOutImage
项目:MiniTWOW-Tools    作者:hanss314    | 项目源码 | 文件源码
def make_book(name,dir):
    orig = name
    if len(name)<2:
        name += name

    left = Image.open('./resources/left.png').convert('RGBA')
    right = Image.open('./resources/right.png').convert('RGBA')
    face = Image.open('./resources/face.png').convert('RGBA')

    left = ImageChops.multiply(left, Image.new('HSV', left.size, makeLetterTint(name[0])).convert('RGBA'))
    right = ImageChops.multiply(right, Image.new('HSV', right.size, makeLetterTint(name[1])).convert('RGBA'))

    left.paste(right,(0,0),right)
    left.paste(face,(0,0),face)

    left.save('{}/{}.png'.format(dir,orig))
项目:MiniTWOW-Tools    作者:hanss314    | 项目源码 | 文件源码
def main():
    global should_draw
    start = time.time()
    print('Gathering Data')
    path, prompt, scores, votes, twowers, twower_count, top_number, elim_number = parse_args()

    print('Processing Scores')
    scores = process_votes(votes, scores, path)

    if should_draw:
        print('Drawing Image')
        base = Image.new('RGBA',(1368,1368),color=(255,255,255))
        drawer = ImageDraw.Draw(base)
        prompt, base, drawer, header_height = draw_header(prompt, base, drawer,scores)
        scores = draw_rankings(scores,top_number,elim_number,twower_count,base,drawer,header_height,twowers)
        base.save('./twows/{}/results.png'.format(path))

    print('Recording Data')
    write_csv(scores,path)
    write_history(path)
    end = time.time()

    print('Time taken {} seconds'.format(end-start))
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def displayImageFileOnLCD(filename):
    print 'displays ', filename
    title = 'Review Mode'
    # resize/dither to screen resolution and send to LCD
    image = Image.open(filename)
    im_width, im_height = image.size
    if im_width < im_height:
        image = image.rotate(90)
    image.thumbnail(S_SIZE, Image.ANTIALIAS)
    image_sized = Image.new('RGB', S_SIZE, (0, 0, 0))
    image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
    # draw filename
    draw = ImageDraw.Draw(image_sized)
    font = ImageFont.truetype('arial.ttf', 18)
    draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0))
    draw.text((2, 2), title, fill='black', font=font)
    draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0))
    draw.text((290, 218), filename, fill='black', font=font)
    # display on LCD
    image_sized = ImageOps.invert(image_sized)
    image_sized = image_sized.convert('1') # convert image to black and white
    lcd.write(image_sized.tobytes())
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def displayImageFileOnLCD(filename):
    print 'displays ', filename
    title = 'Review Mode'
    # resize/dither to screen resolution and send to LCD
    image = Image.open(filename)
    im_width, im_height = image.size
    if im_width < im_height:
        image = image.rotate(90)
    image.thumbnail(S_SIZE, Image.ANTIALIAS)
    image_sized = Image.new('RGB', S_SIZE, (0, 0, 0))
    image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
    # draw filename
    draw = ImageDraw.Draw(image_sized)
    font = ImageFont.truetype('arial.ttf', 18)
    draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0))
    draw.text((2, 2), title, fill='black', font=font)
    draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0))
    draw.text((290, 218), filename, fill='black', font=font)
    # display on LCD
    image_sized = ImageOps.invert(image_sized)
    image_sized = image_sized.convert('1') # convert image to black and white
    lcd.write(image_sized.tobytes())
项目:File-Maker    作者:RiiConnect24    | 项目源码 | 文件源码
def shrink_image(data, resize):
    picture = requests.get(data).content
    image = Image.open(StringIO(picture))

    if resize == True: image = resizeimage.resize_width(image, 200)

    data = list(image.getdata())
    image_without_exif = Image.new(image.mode, image.size)
    image_without_exif.putdata(data)

    picture_number = 1

    buffer = StringIO()
    image_without_exif.save(buffer, format='jpeg')

    return buffer.getvalue()
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
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)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
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)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def apply_watermark(im, mark, position, opacity=1):
    """Adds a watermark to an image."""
    if opacity < 1:
        mark = reduce_opacity(mark, opacity)
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
    if position == 'tile':
        for y in range(0, im.size[1], mark.size[1]):
            for x in range(0, im.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    elif position == 'scale':
        # scale, but preserve the aspect ratio
        ratio = min(
            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
        w = int(mark.size[0] * ratio)
        h = int(mark.size[1] * ratio)
        mark = mark.resize((w, h))
        layer.paste(mark, (round((im.size[0] - w) / 2), round((im.size[1] - h) / 2)))
    else:
        layer.paste(mark, position)
    # composite the watermark with the layer
    return Image.composite(layer, im, layer)
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def __call__(self, value):
        if isinstance(value, str) and len(value) == 0:
            return (value, None)
        from PIL import Image
        from io import BytesIO
        try:
            img = Image.open(value.file)
            img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
            s = BytesIO()
            if self.padding:
                background = Image.new('RGBA', (self.nx, self.ny), (255, 255, 255, 0))
                background.paste(
                    img,
                    ((self.nx - img.size[0]) // 2, (self.ny - img.size[1]) // 2))
                background.save(s, 'JPEG', quality=self.quality)
            else:
                img.save(s, 'JPEG', quality=self.quality)
            s.seek(0)
            value.file = s
        except:
            return (value, self.error_message)
        else:
            return (value, None)
项目:TWOWBot    作者:Noahkiq    | 项目源码 | 文件源码
def make_book(name,dir):
    orig = name
    if len(name)<2:
        name += name

    left = Image.open('./resources/left.png').convert('RGBA')
    right = Image.open('./resources/right.png').convert('RGBA')
    face = Image.open('./resources/face.png').convert('RGBA')

    left = ImageChops.multiply(left, Image.new('HSV', left.size, makeLetterTint(name[0])).convert('RGBA'))
    right = ImageChops.multiply(right, Image.new('HSV', right.size, makeLetterTint(name[1])).convert('RGBA'))

    left.paste(right,(0,0),right)
    left.paste(face,(0,0),face)

    left.save('{}/{}.png'.format(dir,orig))
项目:Octoslack    作者:fraschetti    | 项目源码 | 文件源码
def process_zheight_change(self, payload):
        if not self._printer.is_printing():
            return False
        if not "new" in payload:
            return False

        height_interval = float(self._settings.get(['supported_events'], merged=True).get('Progress').get('IntervalHeight'))
        if height_interval <= 0:
            return False

        new = payload["new"]
        if new <= self.last_trigger_height:
            return False

        if new >= (self.last_trigger_height + height_interval):
            self._logger.debug("ZChange interval: " + str(height_interval) + ", Last trigger height: " + str(self.last_trigger_height) + ", Payload: " + json.dumps(payload))
            self.last_trigger_height = new
            return True

        return False
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_resized_images_updated(self):
        """
        thumbnails should be updated if image is already present and updated when update_image=True
        """
        assert self.profile.image
        assert self.profile.image_small
        assert self.profile.image_medium

        # create a dummy image file in memory for upload
        image_file = BytesIO()
        image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
        image.save(image_file, 'png')
        image_file.seek(0)

        self.profile.image = UploadedFile(image_file, "filename.png", "image/png", len(image_file.getvalue()))
        self.profile.save(update_image=True)
        image_file_bytes = image_file.read()
        assert self.profile.image_small.file.read() != image_file_bytes
        assert self.profile.image_medium.file.read() != image_file_bytes
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_upload_image(self):
        """
        An image upload should not delete education or work history entries
        """
        with mute_signals(post_save):
            profile = ProfileFactory.create(user=self.user1)
        EducationFactory.create(profile=profile)
        EmploymentFactory.create(profile=profile)
        self.client.force_login(self.user1)

        # create a dummy image file in memory for upload
        image_file = BytesIO()
        image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
        image.save(image_file, 'png')
        image_file.seek(0)

        # format patch using multipart upload
        resp = self.client.patch(self.url1, data={
            'image': image_file
        }, format='multipart')
        assert resp.status_code == 200, resp.content.decode('utf-8')
        assert profile.education.count() == 1
        assert profile.work_history.count() == 1
项目:congress-headshots-lambda    作者:datadesk    | 项目源码 | 文件源码
def convert(img_path,name):
    print img_path,name
    name = name.split('.')[0]

    png = Image.open(img_path).convert('RGBA')

    print 'creating images (%s)' % name
    for x in range(0,len(sizes)):
        resized = png.resize((sizes[x],sizes[x]), Image.ANTIALIAS)
        resized.save('/tmp/transparent.png', quality=100)
        upload_path = '%s/%s' % (name,sizes[x])
        s3_client.put_object(Key='%s/transparent.png' % (upload_path), Bucket=output_bucket, Body=open('/tmp/transparent.png','rb'), ContentType='image/png')
        for color in colors:
            background = Image.new("RGBA",(sizes[x],sizes[x]),ImageColor.getrgb(colors[color]))
            background.paste(resized ,(0,0), resized)
            filename = '/tmp/%s%s.jpg' % (sizes[x],color)
            background.save(filename, quality=95)
            s3_client.put_object(Key='%s/%s.jpg' % (upload_path,color), Bucket=output_bucket, Body=open(filename,'rb'), ContentType='image/jpeg')
项目:base_function    作者:Rockyzsu    | 项目源码 | 文件源码
def general_image(self, image_format='PNG'):
        fm_width = self.cleaned_data['width']
        fm_height = self.cleaned_data['height']

        key = '{}.{}.{}'.format(fm_width, fm_height, image_format)
        content = cache.get(key)
        if content is None:
            image = Image.new('RGB', (fm_width, fm_height), color=122)

            draw = ImageDraw.Draw(image)
            text = '{}x{}'.format(fm_width, fm_height)
            text_width, text_height = draw.textsize(text)

            if text_width < fm_width and text_height < fm_height:
                text_top = (fm_height - text_height) // 2
                text_left = (fm_width - text_width) // 2

                draw.text((text_top, text_left), text, fill=(255, 255, 255))

            content = BytesIO()
            image.save(content, image_format)
            content.seek(0)
            cache.set(key, content, 60 * 60)

        return content
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def get_mask(self, fill=1, outline=0):
        """
        Get a mask that is nonzero within the object.
        :param fill:  A color to use on the object's interior
        :param outline: A color to use on the object's edge (single pixel)
        :return: A 2D numpy array of uint8
        """
        if self.type in (TYPE_POLYGON, TYPE_BOUNDING_BOX):
            (top, left, bottom, right) = self.polygon.bounds()
            w = right-left
            h = bottom-top
            mask = Image.new("I", (w, h))
            d = ImageDraw.Draw(mask)
            d.polygon([(px-left, py-top) for (px, py) in self.polygon.points],
                        fill=fill, outline=outline)
            del d
            return np.asarray(mask)
        else:
            assert False, "Unhandled Type"
项目:facade-segmentation    作者:jfemiani    | 项目源码 | 文件源码
def __init__(self, annotation, nrows=512, ncols=None):
        super(SingleLayerLabels, self).__init__()
        self.annotation = annotation

        assert annotation.imagesize.nrows is not None, "Must know the image size first (see update_image_size)"

        self.aspect = annotation.imagesize.ncols/float(annotation.imagesize.nrows)
        self.y_scale = nrows / float(annotation.imagesize.nrows)
        self.nrows = nrows
        if ncols is None:
            self.x_scale = self.y_scale
            self.ncols = int(self.x_scale*annotation.imagesize.ncols)
        else:
            self.x_scale = ncols / float(annotation.imagesize.ncols)
            self.ncols = ncols

        self.image = Image.new('L', (self.ncols, self.nrows), LABEL_NEGATIVE)
        self.artist = ImageDraw.Draw(self.image)
项目:flickr-crawler    作者:chenusc11    | 项目源码 | 文件源码
def create_wallpaper(screen, urls, size=(100, 100), randomise=False):
    if randomise:
        random.shuffle(urls)

    wallpaper = Image.new("RGB", screen, "blue")

    width = int(math.ceil(float(screen[0]) / size[0]))
    height = int(math.ceil(float(screen[1]) / size[1]))

    offset = [0,0]
    for i in xrange(height):
        y = size[1] * i
        for j in xrange(width):
            x = size[0] * j
            photo = load_photo(urls.pop())
            if photo.size != size:
                photo = photo.resize(size, Image.BICUBIC)
            wallpaper.paste(photo, (x, y))
            del photo
    return wallpaper
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def get_temp_image():
        image = Image.new("RGB", (100, 100))
        tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg")
        image.save(tmp_file)
        tmp_file.seek(0)
        return tmp_file
项目:robot-arena    作者:kenganong    | 项目源码 | 文件源码
def make_iteration_image(state):
  pixel_size = 9
  image = Image.new('RGB', (state.board.cols * pixel_size, state.board.rows * pixel_size))
  for row in range(state.board.rows):
    for col in range(state.board.cols):
      cell_image = get_cell_image(state.board.get_item((row, col)))
      image.paste(cell_image, (col * pixel_size, row * pixel_size))
  return image
项目:visual-search    作者:GYXie    | 项目源码 | 文件源码
def crop(np_img):
    image = Image.fromarray(np_img)
    width, height = image.size
    box = (width * 0.2, height * 0.2, width * 0.8, height * 0.8)
    crop = image.crop(box)
    image = Image.new('RGBA', crop.size)
    box = (0, 0, crop.size[0], crop.size[1])
    image.paste(crop, box)
    return np.asarray(image)
项目:visual-search    作者:GYXie    | 项目源码 | 文件源码
def main():
    image = Image.open(args.input_path)
    width, height = image.size
    box = (width * 0.1, height * 0.1, width * 0.9, height * 0.9)
    crop = image.crop(box)
    print(crop.size)
    image = Image.new('RGBA', crop.size)
    box = (0, 0, crop.size[0], crop.size[1])
    image.paste(crop, box)
    image.save(args.output_path)
项目:RasterFairy    作者:Quasimondo    | 项目源码 | 文件源码
def paletteImage(self):
        """ PIL weird interface for making a paletted image: create an image which
            already has the palette, and use that in Image.quantize. This function
            returns this palette image. """
        if self.pimage is None:
            palette = []
            for i in range(self.NETSIZE):
                palette.extend(self.colormap[i][:3])

            palette.extend([0]*(256-self.NETSIZE)*3)

            # a palette image to use for quant
            self.pimage = Image.new("P", (1, 1), 0)
            self.pimage.putpalette(palette)
        return self.pimage
项目:geo-pyprint    作者:ioda-net    | 项目源码 | 文件源码
def _create_map_image(self):
        images = self._get_images()

        self._map_image = Image.new('RGBA', self._map_size)

        for img in images:
            if not isinstance(img, Image.Image):
                img = Image.open(BytesIO(img.content)).convert('RGBA')

            self._map_image = Image.alpha_composite(self._map_image, img)