def overlay_icon_to_vim(icon, cache):
    bg = Image.open(VIMICON)
    overlay_size = 10
    overlay = Image.open(icon).resize((overlay_size, overlay_size), Image.ANTIALIAS)
    fg = Image.new("RGBA", (16, 16))
    fg.paste(overlay, (16 - overlay_size, 16 - overlay_size, 16, 16))
    Image.alpha_composite(bg, fg).save(cache)
Example #2
0
    def diff(self):
        self.run_ss = [run for run in os.listdir(self.run_dir)]
        self.gold_ss = [gold for gold in os.listdir(self.gold_dir)]
        if self.mask_dir:
            self.mask_ss = [mask for mask in os.listdir(self.mask_dir)]

        if self.run_ss != self.gold_ss:
            print 'Missing screenshots: %s' % str(list(set(self.gold_ss).difference(self.run_ss)))
            print 'Extra screenshots: %s' % str(list(set(self.run_ss).difference(self.gold_ss)))

        # Diff all the images common to run and gold directories
        for ss in list(set(self.run_ss).intersection(self.gold_ss)):
            try:
                # Apply the mask, if it exists
                if self.mask_dir and (ss in self.mask_ss):
                    base = Image.open(self.run_dir + ss)
                    mask = Image.open(self.mask_dir + ss)
                    Image.alpha_composite(base, mask).save(self.run_dir+ss)
                if not self.images_identical(self.gold_dir + ss, self.run_dir + ss):
                    rms = self.image_diff(self.gold_dir + ss, self.run_dir + ss, self.diff_dir + ss, (255, 0, 0))[0]
                    # Experimentally found value, "fuzziness factor"
                    if rms < self.fuzzy:
                        pass
                    else:
                        print 'Diff failed! %s is not identical enough.' % ss
            except AssertionError:
                print "Diff failed! %s. Images have different dimensions or pixel modes." % ss
Example #3
0
def map_wards(data):
    accumulator = 1

    frames = set_frames(data)
    for e in range(len(data)):
        index = round(data[e]["time"] / 60000) - 1
        im = Image.new('RGBA', (512, 512))
        draw = ImageDraw.Draw(im, "RGBA")

        if data[e]["team"] == 100:
            color = (0, 0, 126, 200)
        elif data[e]["team"] == 200:
            color = (126, 0, 0, 200)

        x = data[e]["position"]["x"] + x_off
        y = data[e]["position"]["y"] + y_off

        draw.ellipse([x / scale - d, y / scale - d, x / scale + d, y / scale + d], fill=color)
        del draw

        frames[index] = Image.alpha_composite(frames[index], im)

    for image in frames:
        canvas = Image.open('minimap-mh.png').convert("RGBA")
        Image.alpha_composite(canvas, image.transpose(Image.FLIP_TOP_BOTTOM)).save(
            "C:/Users/Eddie/PycharmProjects/WardScan/frames/{}.png".format(accumulator), "PNG")
        accumulator += 1
Example #4
0
def snapshot(image):
    global ready
    global overlay
    global merci
    global misc
    global pos
    global live
    global camera
    
    print 'image: ', image
    print 'real image: ', str(misc['images'][image])

    filename = time.strftime('%Y%m%d') + '-' + time.strftime('%H%M%S')
    
    print 'filename: ' + filename
    
    message = 'snapshot: ' + filename
    tStatus = threading.Thread(name='status', target=status, args=(message,))
    tStatus.daemon = True
    tStatus.start()
    
    ready['capture'] = int(time.time())
    print 'camera: capture start'
    camera.capture(misc['snapshots'] + filename + misc['ext'], format='png')
    print 'camera: capture done'
    ready['capture'] = 0
    
    ready['upload'] = False
    ready['print'] = False
    
    print 'ready (upload): ', ready['upload']
    print 'ready (print): ', ready['print']
    
    print 'resize'
    
    # MERGING IMAGES
    resize_canvas(misc['snapshots'] + filename + misc['ext'],misc['snapshots'] + filename + misc['ext'],pos[misc['images'][image]]['x'],pos[misc['images'][image]]['y'])
    background = Image.open(misc['snapshots'] + filename + misc['ext'])
    foreground = Image.open(misc['cards'] + str(misc['images'][image]) + '.png')

    print 'merge'
    
    Image.alpha_composite(background, foreground).save(misc['compositions'] + filename + misc['ext'])
    
    print 'prepare'
    
    tPrepare = threading.Thread(name='prepare', target=prepare, args=(filename,misc['images'][image],))
    tPrepare.daemon = True
    tPrepare.start()
    
    merci = subprocess.Popen(['/home/pi/raspidmx/pngview/./pngview','-b','0','-l','4','/home/pi/Photobooth/merci/merci.png'])
    sleep(10)

    print 'setup'
    
    tSetup = threading.Thread(name='setup', target=setup)
    tSetup.daemon = True
    tSetup.start()
Example #5
0
def snapshot(image):
    global ready
    global misc
    global merci
    global camera
    print "image: ", image
    print "real image: ", str(misc["images"][image])

    filename = time.strftime("%Y%m%d") + "-" + time.strftime("%H%M%S")

    print "filename: ", filename

    ready["capture"] = int(time.time())
    print "camera: capture start"
    camera.capture(misc["snapshots"] + filename + misc["ext"], format="png")
    print "camera: capture done"
    ready["capture"] = 0

    ready["upload"] = False
    ready["print"] = False

    print "ready (upload): ", ready["upload"]
    print "ready (print): ", ready["print"]

    print "resize"

    # MERGING IMAGES
    resize_canvas(
        misc["snapshots"] + filename + misc["ext"],
        misc["snapshots"] + filename + misc["ext"],
        pos[misc["images"][image]]["x"],
        pos[misc["images"][image]]["y"],
    )
    background = Image.open(misc["snapshots"] + filename + misc["ext"])
    foreground = Image.open(misc["cards"] + str(misc["images"][image]) + ".png")

    print "merge"

    Image.alpha_composite(background, foreground).save(misc["compositions"] + filename + misc["ext"])

    print "prepare"

    tPrepare = threading.Thread(name="prepare", target=prepare, args=(filename, misc["images"][image]))
    tPrepare.daemon = True
    tPrepare.start()

    merci = subprocess.Popen(
        ["/home/pi/raspidmx/pngview/./pngview", "-b", "0", "-l", "4", "/home/pi/Photobooth/merci/merci.png"]
    )
    sleep(10)

    print "setup"

    tSetup = threading.Thread(name="setup", target=setup)
    tSetup.daemon = True
    tSetup.start()
Example #6
0
def meme_image(image_name, memename, serverid):
	print("Creating " + memename + " meme using " + image_name + " for server " + serverid)
	with open("info.json", "r") as info_file:
		data = info_file.read()
		data = json.loads(data)
	if not os.path.isfile("images/" + data["memes_images"][memename]["image"]):
		print("Downloading new Images")
		file_download(data["memes_images"][memename]["image_url"], "images/", data["memes_images"][memename]["image"])

	frame = Image.open("images/" + data["memes_images"][memename]["image"]).convert("RGBA")
	pic = Image.open("server/" + serverid + "/" + image_name).convert("RGBA")
	if data["memes_images"][memename]["background"] == True:
		box = data["memes_images"][memename]["box"]
		if pic.size[0] < pic.size[1]:
			scale = (box[2]/pic.size[0])
			pic = pic.resize((box[2],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS)
			if pic.size[1] < box[3] - box[1]:
				scale = (box[3]/pic.size[1])
				pic = pic.resize(((int(pic.size[0]*scale),box[3])), PIL.Image.ANTIALIAS)
		else:
			scale = (box[3]/pic.size[1])
			pic = pic.resize(((int(pic.size[0]*scale),box[3])), PIL.Image.ANTIALIAS)
			if pic.size[0] < box[2] - box[0]:
				scale = (box[2]/pic.size[0])
				pic = pic.resize((box[2],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS)
		center = [(pic.size[0]-box[2])/2, (pic.size[1]-box[3])/2]

		pic = pic.crop((center[0],center[1],center[0]+box[2],center[1]+box[3]))

		frame.paste(pic,(box[0],box[1]))
		background = Image.new('RGBA', frame.size, (data["memes_images"][memename]["backgrond_color"][0],data["memes_images"][memename]["backgrond_color"][1],data["memes_images"][memename]["backgrond_color"][2],data["memes_images"][memename]["backgrond_color"][3]))
		frame = Image.alpha_composite(background, frame)
		frame.save("server/" + serverid + "/output/"+ data["memes_images"][memename]["image"]);
	else:
		if pic.size[1] < frame.size[1]:
			scale = (frame.size[1]/pic.size[1])
			pic = pic.resize(((int(pic.size[0]*scale),frame.size[1])), PIL.Image.ANTIALIAS)
		if pic.size[0] < frame.size[0]:
			scale = (frame.size[0]/pic.size[0])
			pic = pic.resize((frame.size[0],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS)
		if pic.size[1] < frame.size[1]:
			scale = (frame.size[1]/pic.size[1])
			pic = pic.resize(((int(pic.size[0]*scale),frame.size[1])), PIL.Image.ANTIALIAS)
		if pic.size[0] < frame.size[0]:
			scale = (frame.size[0]/pic.size[0])
			pic = pic.resize((frame.size[0],int(pic.size[1]*scale)), PIL.Image.ANTIALIAS)
		pic.paste(frame, (10, pic.size[1]-frame.size[1]-30),frame)
		background = Image.new('RGBA', pic.size, (data["memes_images"][memename]["backgrond_color"][0],data["memes_images"][memename]["backgrond_color"][1],data["memes_images"][memename]["backgrond_color"][2],data["memes_images"][memename]["backgrond_color"][3]))
		pic = Image.alpha_composite(background, pic)
		pic.save("server/" + serverid + "/output/"+ data["memes_images"][memename]["image"]);

	print(memename + " meme saved to: server/" + serverid + "/output/" + data["memes_images"][memename]["image"])
	return("server/" + serverid + "/output/" + data["memes_images"][memename]["image"])
Example #7
0
def images_identical(path1, path2, mask_path):
    if not os.path.exists(path1):
        return False
    im1 = Image.open(path1)
    im2 = Image.open(path2)
    if im1.size != im2.size:
        return False
    if mask_path != None:
        mask = Image.open(mask_path)
        im1 = Image.alpha_composite(im1, mask)
        im2 = Image.alpha_composite(im2, mask)
    return ImageChops.difference(im1, im2).getbbox() is None
Example #8
0
def image_diff(path1, path2, outpath, diffcolor, mask_path):
    if not os.path.exists(path1):
        im2 = Image.open(path2)
        return (1000, im2.size[0], im2.size[1])

    im1 = Image.open(path1)
    im2 = Image.open(path2)

    if im1.size != im2.size:
        return (1000, im2.size[0], im2.size[1])

    if mask_path != None:
        mask = Image.open(mask_path)
        im1 = Image.alpha_composite(im1, mask)
        im2 = Image.alpha_composite(im2, mask)

    rmsdiff = rmsdiff_2011(im1, im2)

    pix1 = im1.load()
    pix2 = im2.load()

    if im1.mode != im2.mode:
        raise TestError('Different pixel modes between %r and %r' % (path1, path2))
    if im1.size != im2.size:
        raise TestError('Different dimensions between %r (%r) and %r (%r)' % (path1, im1.size, path2, im2.size))

    mode = im1.mode

    if mode == '1':
        value = 255
    elif mode == 'L':
        value = 255
    elif mode == 'RGB':
        value = diffcolor
    elif mode == 'RGBA':
        value = diffcolor + (255,)
    elif mode == 'P':
        raise NotImplementedError('TODO: look up nearest palette color')
    else:
        raise NotImplementedError('Unexpected PNG mode')

    width, height = im1.size

    for y in xrange(height):
        for x in xrange(width):
            if pix1[x, y] != pix2[x, y]:
                pix2[x, y] = value
    im2.save(outpath)

    return (rmsdiff, width, height)
Example #9
0
def save_sketch(request, id):
    # this saves the sketch
    canvasData = request.POST.get('canvasData', None)
    if not canvasData:
        return
    img_string = canvasData.replace("data:image/png;base64,", "")
    img_data = img_string.decode("base64")
    img_file = StringIO.StringIO(img_data)
    # now merge with the background
    backimgfn = '%s/static/case_form_background.png' % settings.BASE_DIR
    background = Image.open(backimgfn)
    foreground = Image.open(img_file)
    fn = '%s/uploads/sketch%s.png' % (settings.BASE_DIR, id)
    Image.alpha_composite(background, foreground).save(fn)
    img_file.close()
Example #10
0
def generate_stars(tasks_to_write):
    foreground = Image.open('stars.png')
    for page in tasks_to_write:
        for task in page:
            file_name = 'tmp/img/{}-star.png'.format(task['id'])

            background = Image.new('RGBA', (440, 84), (255, 255, 255, 255))

            draw = ImageDraw.Draw(background)
            draw.rectangle(
                ((0, 0), (int(round(4.4 * task['stars'])), 84)),
                fill='black')

            Image.alpha_composite(background, foreground) \
                .save(open(file_name, 'w+b'))
Example #11
0
def overlayOnPart(src_image, overlay_image, posX, posY):

    # オーバレイ画像のサイズを取得
    ol_height, ol_width = overlay_image.shape[:2]

    # OpenCVの画像データをPILに変換
    # BGRAからRGBAへ変換
    src_image_RGBA = cv2.cvtColor(src_image, cv2.COLOR_BGR2RGB)
    overlay_image_RGBA = cv2.cvtColor(overlay_image, cv2.COLOR_BGRA2RGBA)
    
    # PILに変換
    src_image_PIL=Image.fromarray(src_image_RGBA)
    overlay_image_PIL=Image.fromarray(overlay_image_RGBA)

    # 合成のため、RGBAモードに変更
    src_image_PIL = src_image_PIL.convert('RGBA')
    overlay_image_PIL = overlay_image_PIL.convert('RGBA')

    # 同じ大きさの透過キャンパスを用意
    tmp = Image.new('RGBA', src_image_PIL.size, (255, 255,255, 0))
    # 用意したキャンパスに上書き
    tmp.paste(overlay_image_PIL, (posX, posY), overlay_image_PIL)
    # オリジナルとキャンパスを合成して保存
    result = Image.alpha_composite(src_image_PIL, tmp)
    
    # COLOR_RGBA2BGRA から COLOR_RGBA2BGRに変更。アルファチャンネルを含んでいるとうまく動画に出力されない。
    return  cv2.cvtColor(np.asarray(result), cv2.COLOR_RGBA2BGR)
Example #12
0
def overlayOnPart(src_image, overlay_image, posX, posY, zoom):

    # オーバレイ画像を倍率に合わせて拡大縮小
    resized_overlay_image = resize_image(overlay_image, zoom)

    # オーバレイ画像のサイズを取得
    ol_height, ol_width = resized_overlay_image.shape[:2]

    # OpenCVの画像データをPILに変換
    
    # BGRAからRGBAへ変換
    src_image_RGBA = cv2.cvtColor(src_image, cv2.COLOR_BGR2RGB)
    resized_overlay_image_RGBA = cv2.cvtColor(resized_overlay_image, cv2.COLOR_BGRA2RGBA)
    
    # PILに変換
    src_image_PIL=Image.fromarray(src_image_RGBA)
    resized_overlay_image_PIL=Image.fromarray(resized_overlay_image_RGBA)

    # 合成のため、RGBAモードに変更
    src_image_PIL = src_image_PIL.convert('RGBA')
    resized_overlay_image_PIL = resized_overlay_image_PIL.convert('RGBA')

    # 同じ大きさの透過キャンパスを用意
    tmp = Image.new('RGBA', src_image_PIL.size, (255, 255,255, 0))
    # rect[0]:x, rect[1]:y, rect[2]:width, rect[3]:height
    # 用意したキャンパスに上書き
    tmp.paste(resized_overlay_image_PIL, (int(posX-ol_height/2), int(posY-ol_width/2)), resized_overlay_image_PIL)
    # オリジナルとキャンパスを合成して保存
    result = Image.alpha_composite(src_image_PIL, tmp)

    return  cv2.cvtColor(np.asarray(result), cv2.COLOR_RGBA2BGR)
Example #13
0
 def test_fit_in_rectangle_transparent_no_resize(self):
     # And with a transparent test image, check alpha blending.
     image = 'pattern-transparent-rgba.png'
     control = Image.open(get_image_path(image))
     # Create checkerboard background.
     checker_bg = Image.new('RGBA', control.size)
     checker = Image.open(get_image_path('checkerboard.png'))
     for x in range(0, control.size[0], checker.size[0]):
         for y in range(0, control.size[1], checker.size[1]):
             checker_bg.paste(checker, (x, y))
     # Create whhite background.
     white_bg = Image.new('RGBA', control.size, color='white')
     assert control.size == white_bg.size
     width, height = control.size
     for use_checker_bg in (False, True):
         prefs['checkered bg for transparent images'] = use_checker_bg
         expected = Image.alpha_composite(
             checker_bg if use_checker_bg else white_bg,
             control
         )
         for scaling_quality in range(4):
             prefs['scaling quality'] = scaling_quality
             result = image_tools.fit_in_rectangle(image_tools.pil_to_pixbuf(control),
                                                   width, height,
                                                   scaling_quality=scaling_quality)
             msg = (
                 'fit_in_rectangle("%s", scaling quality=%d, background=%s) failed; '
                 'result %%(diff_type)s differs: %%(diff)s'
                 % (image, scaling_quality, 'checker' if checker_bg else 'white')
             )
             self.assertImagesEqual(result, expected, msg=msg)
Example #14
0
    def test_alpha_composite(self):
        # http://stackoverflow.com/questions/3374878
        # Arrange
        from PIL import ImageDraw

        expected_colors = sorted([
            (1122, (128, 127, 0, 255)),
            (1089, (0, 255, 0, 255)),
            (3300, (255, 0, 0, 255)),
            (1156, (170, 85, 0, 192)),
            (1122, (0, 255, 0, 128)),
            (1122, (255, 0, 0, 128)),
            (1089, (0, 255, 0, 0))])

        dst = Image.new('RGBA', size=(100, 100), color=(0, 255, 0, 255))
        draw = ImageDraw.Draw(dst)
        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))
        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))
        src = Image.new('RGBA', size=(100, 100), color=(255, 0, 0, 255))
        draw = ImageDraw.Draw(src)
        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))
        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))

        # Act
        img = Image.alpha_composite(dst, src)

        # Assert
        img_colors = sorted(img.getcolors())
        self.assertEqual(img_colors, expected_colors)
Example #15
0
def combine_images(images):
    returnimage = None
    for i in images:
        if i:
            image = Image.open(io.BytesIO(i)).convert('RGBA')
            # make all white pixels transparent
            pixdata = image.load()
            width, height = image.size
            for y in xrange(height):
                for x in xrange(width):
                    if pixdata[x, y] == (255, 255, 255, 255):
                        pixdata[x, y] = (255, 255, 255, 0)
            if not returnimage:
                returnimage = image
            else:
                baseimage = returnimage
                imagetoadd = image
                returnimage = Image.alpha_composite(
                    baseimage,
                    imagetoadd
                )
    if returnimage:
        with io.BytesIO() as output:
            returnimage.save(output, 'PNG')
            return output.getvalue()
    return None
Example #16
0
def make_cover_image(item):
    if item.image_counter and item.compilation_cds != 1:
        base = Image.open(item.image_path).convert('RGBA')
        overlay = Image.new('RGBA', base.size, (255,255,255,0))
        fnt = ImageFont.truetype('garamond8.ttf', base.size[0] // 15)
        d = ImageDraw.Draw(overlay)
        counter = str(item.image_counter)

        textsize = d.textsize(counter, font=fnt)
        draw_position = (base.size[0] / 2, int(base.size[1] * 0.9))
        circle_radius = max(textsize) // 2
        circle_bounds = [(draw_position[0] - circle_radius, draw_position[1] - circle_radius),
            (draw_position[0] + circle_radius, draw_position[1] + circle_radius)]
        text_position = (draw_position[0] - textsize[0]/2, draw_position[1] - textsize[1]//1.5)

        d.ellipse(circle_bounds, fill=(255,255,255,64))
        #d.ellipse([(draw_position[0] - 5, draw_position[1] - 5), (draw_position[0] + 5, draw_position[1] + 5)], fill=(255,0,0,128))
        #d.ellipse([(text_position[0] - 5, text_position[1] - 5), (text_position[0] + 5, text_position[1] + 5)], fill=(0,255,0,128))
        d.text(text_position, counter, font=fnt, fill=(64,64,64,255))
        '''
        print 'draw_position;', draw_position
        print 'text_position:', text_position
        print 'fontsize:', base.size[0] // 10
        print 'base.size:', base.size
        print 'textsize:', textsize
        print 'circle_radius:', circle_radius
        '''
        out = Image.alpha_composite(base, overlay)

        label_path = os.path.join(cd_tracks_folder, item.name) + '_' + counter + '.jpg'
        out.save(label_path, 'jpeg')
    else:
        label_path = os.path.join(config.cd_tracks_folder, item.name) + '.jpg'
        shutil.copy(item.image_path, label_path)
    return label_path
Example #17
0
    def _get_image(overlay, x, y):
        """Superpose the picture of the timezone on the map"""
        def _get_x_offset():
            now = datetime.utcnow().timetuple()
            return - int((now.tm_hour * 60 + now.tm_min - 12 * 60) / (24 * 60) * MAP_SIZE[0])  # night is centered at UTC noon (12)

        im = BACK_IM.copy()
        if overlay:
            overlay_im = Image.open(TIMEZONE_RESOURCES + overlay)
            im.paste(BACK_ENHANCED_IM, overlay_im)
        night_im = ImageChops.offset(NIGHT_IM, _get_x_offset(), 0).crop(im.getbbox())
        if IS_WINTER:
            night_im = ImageOps.flip(night_im)

        # In Wheezy alpha_composite and tobytes are not implemented, yet
        try:
            im.paste(Image.alpha_composite(night_im, LIGHTS_IM), night_im)
        except:
            im.paste(Image.blend(night_im, LIGHTS_IM, 0.5), night_im)
        im.paste(DOT_IM, (int(x - DOT_IM.size[1] / 2), int(y - DOT_IM.size[0] / 2)), DOT_IM)
        try:
            data = im.tobytes()
            w, h = im.size
            data = GLib.Bytes.new(data)
            pb = GdkPixbuf.Pixbuf.new_from_bytes(data, GdkPixbuf.Colorspace.RGB,
                 False, 8, w, h, w * 3)
            return pb
        except:
            data = im.tostring()
            w, h = im.size
            pb = GdkPixbuf.Pixbuf.new_from_data(barr, GdkPixbuf.Colorspace.RGB,
                 False, 8, w, h, w * 3)
            return pb
def watermarkTest(subreddit):

	textBase = emptyBase
	# make a blank image for the text, initialized to transparent text color
	width = image.size[0]
	height = image.size[1]

	# get a font
	fnt = ImageFont.truetype(fontDirectory + "BRADHITC.ttf", size=200)
	fntHeight = fnt.getsize(subreddit)[1]
	# creates an object that will be drawn onto textBase
	draw = ImageDraw.Draw(textBase)

	# draw text, half opacity
	#print "image width:", imageWidth, "image height:", imageHeight
	#print "1/6 width", 1 * imageWidth / 6, "1/6 height", 1 * imageHeight / 6
	draw.text((width / 48, 47 * height / 48	- fntHeight), subreddit, font=fnt, fill=(255, 255, 255,255))

	# draw text, full opacity
	#print "the font width is:", draw.textsize(subreddit, font=fnt)[0]
	#d.show()
	textDimensions = draw.textsize(subreddit, font=fnt)
	out = Image.alpha_composite(image, textBase)
	#outWithLines = Image.alpha_composite(out, textPlacementTest(emptyBase, textDimensions))
	
	out.save(filepath + "test.jpg")
Example #19
0
    def render(self, context):
        assert isinstance(context, RenderContext)

        feature1 = self._nodes[0].render(context)
        if feature1 is None:
            raise RuntimeError('Render Failed, Node: %s, Context: %r',
                                self._nodes[0].name, context)
        src = feature1.data

        feature2 = self._nodes[1].render(context)
        if feature2 is None:
            raise RuntimeError('Render Failed, Node: %s, Context: %r',
                                self._nodes[1].name, context)
        dst = feature2.data

        if src.mode != dst.mode:
            if src.mode != 'RGBA':
                src = src.convert(mode='RGBA')
            if dst.mode != 'RGBA':
                dst = dst.convert(mode='RGBA')

        pil_image = Image.alpha_composite(dst, src)

        if pil_image.mode != 'RGBA':
            pil_image = pil_image.convert(mode='RGBA')

        feature = ImageFeature(
            crs=context.map_proj,
            bounds=context.map_bbox,
            size=context.map_size,
            data=pil_image
        )

        return feature
def process_tall_image(im):
    black = Image.new('RGBA', im.size, color=(0,0,0,255))
    im_on_black_background = Image.alpha_composite(black, im)
    scaling_factor = OUTPUT_RES[0] / im.width
    output_height = round(im.height * scaling_factor)
    #im_on_black_background.thumbnail((OUTPUT_RES[0], 9999999999))       #resize such that width is 1707, but height can be whatever
    return im_on_black_background.resize((OUTPUT_RES[0],output_height), resample=Image.LANCZOS)
Example #21
0
def plot_to_map(coordinates, names, colors):
	'''
	Takes as input three lists, which should all line-up:
		- names (list in which all province/state names are stored)
		- coordinates (list with coordinates formatted as (x,y))
		- colors ()

	'''
	# load basemap image and make blank image for text
	basemap = Image.open('spain_.jpg').convert('RGBA')
	txt = Image.new('RGBA', basemap.size)

	# get font
	font = ImageFont.truetype('calibri.ttf', 20)

	# get a drawing context
	draw = ImageDraw.Draw(txt)

	for i in range(len(names)):
		# draw text on map, rotate colors
		draw.text(locations[i], names[i], font=font, fill=colors[i%len(colors)])

	# draw text layer on top of image layer
	out = Image.alpha_composite(basemap, txt)

	# showtime .. 
	out.show()
def iconAssembler(basedir, button, template, colors, background):
    background = background.strip()
    template = template.strip()
    backDir = os.path.join(basedir, "themes", "backgrounds", '')
    themeDir = os.path.join(basedir, "themes")
    back = Image.open(os.path.join(backDir + str(background + ".png")))
    back = back.convert('RGBA')
    mask = Image.open(os.path.join(themeDir, template, str(button +
                                                           "Mask.png")))
    mask = mask.convert('L')
    back.putalpha(mask)
    layers = list()
    for count, color in enumerate(colors):
        color.strip()
        filename = ''
        try:
            filename = os.path.join(themeDir, template, str(button + str(
                count) + ".png"))
            layer = Image.open(filename)
        except:
            status = "Not enough colors! Can't open " + filename
            return status, None
        layer = layer.convert('RGBA')
        if color != "same":
            try:
                layer = replaceColors(layer, color)
            except:
                status = "Couldn't colorshift " + filename + " to " + color \
                         + "! Possible bad color string?"
                return status, None
        back = Image.alpha_composite(back, layer)
    status = "Successfully generated icons!"
    return status, back
Example #23
0
def body(player, *, player_skin=None, model=None, hat=True, profile_id=None, error_log=None):
    if error_log is None:
        error_log = sys.stderr
    if player_skin is None or model is None:
        player_skin, model = skin(player, profile_id=profile_id, error_log=error_log)
    result = Image.new('RGBA', (16, 32))
    result.paste(player_skin.crop((8, 8, 16, 16)), (4, 0)) # head
    result.paste(player_skin.crop((20, 20, 28, 32)), (4, 8)) # body
    result.paste(player_skin.crop((4, 20, 8, 32)), (4, 20)) # right leg
    result.paste(player_skin.crop((44, 20, 47 if model == 'alex' else 48, 32)), (1 if model == 'alex' else 0, 8)) # right arm
    if player_skin.size[1] == 32: # old-style skin
        result.paste(player_skin.crop((4, 20, 8, 32)).transpose(Image.FLIP_LEFT_RIGHT), (8, 20)) # left leg
        result.paste(player_skin.crop((44, 20, 47 if model == 'alex' else 48, 32)).transpose(Image.FLIP_LEFT_RIGHT), (12, 8)) # left arm
    else: # new-style skin
        result.paste(player_skin.crop((20, 52, 24, 64)), (8, 20)) # left leg
        result.paste(player_skin.crop((36, 52, 39 if model == 'alex' else 40, 64)), (12, 8)) # left arm
    with player_skin:
        if hat:
            hat_layer = Image.new('RGBA', (16, 32))
            hat_layer.paste(player_skin.crop((40, 8, 48, 16)), (4, 0)) # hat
            if player_skin.size[1] == 64: # new-style skin
                hat_layer.paste(player_skin.crop((20, 36, 28, 48)), (4, 8)) # jacket
                hat_layer.paste(player_skin.crop((4, 36, 8, 48)), (4, 20)) # right pants leg
                hat_layer.paste(player_skin.crop((44, 36, 47 if model == 'alex' else 48, 48)), (1 if model == 'alex' else 0, 8)) # right sleeve
                hat_layer.paste(player_skin.crop((4, 52, 8, 64)), (8, 20)) # left pants leg
                hat_layer.paste(player_skin.crop((52, 52, 55 if model == 'alex' else 56, 64)), (12, 8)) # left sleeve
            return Image.alpha_composite(result, hat_layer)
        return result
Example #24
0
        def build_lyrics(source, text):
            source = copy(source)

            width = source.size[0]
            height = source.size[1]

            process = Image.new('RGBA', (width, height), (0,0,0))

            half_width = int(math.floor(width / 2))
            half_height = int(math.floor(height / 2))

            # get a font
            fnt_b = ImageFont.truetype('data/drawing/font_bold.ttf', 40)
            # get a drawing context
            d = ImageDraw.Draw(process)

            # haax
            d.rectangle([(0,0),(width,height)], fill=(0,0,0,0))

            # calculate position
            text_pos = int(math.floor(fnt_b.getsize(text)[0] / 2))

            # draw
            d.rectangle([(10, height - 70),(width - 10, height - 10)], fill=(0,0,0,160))
            d.text((half_width - text_pos, height - 55), text, font=fnt_b, fill=(255,255,255,255))

            return Image.alpha_composite(source, process)
Example #25
0
def process_image(img):
  #open up the mask
  mask = Image.open('mask.png')
  mask = mask.convert('RGBA')
  #make sure it matches the size of the image
  mask = mask.resize(img.size)

  #make sure our image has alpha channel
  img = img.convert('RGBA')

  #unique name
  filename = uuid.uuid4().hex + '.png'
  filename = os.path.join('/tmp', filename)
  Image.alpha_composite(img, mask).save(filename, 'PNG')
  #send it back
  return filename
Example #26
0
def add_actors(out_img, actors):
    for actor in actors:
        if actor.image:
            img_path = actor.image
            img = Image.open(img_path).convert("RGBA")
                                
            shape = actor.clip
            sprite = img.crop(make_box(*shape))

            if actor.effect:
                apply_effect(sprite, actor.effect)

            x = actor.x * TILE_SIZE
            y = actor.y * TILE_SIZE
            paste_shape = [x, y] + list(sprite.size)

            if actor.zoom:
                new_x, new_y, new_w, new_h, scale = actor.zoom
                sprite = sprite.resize([new_w, new_h])
                x = new_x * TILE_SIZE
                y = new_y * TILE_SIZE
                paste_shape = [x, y] + list(sprite.size)
            
            paste_box = make_box(*paste_shape)
            bg = out_img.crop(paste_box)
            mixed = None
            if actor.effect:
                mixed = add_composite(bg, sprite)
            else:
                mixed = Image.alpha_composite(bg, sprite)
            out_img.paste(mixed, paste_box)
Example #27
0
    def resize_the_image(self, infile):
        filename = self.create_filename()
        new_file_path = os.path.join(self.destination_folder, filename)
        im = Image.open(infile)
        align = "horizontal"
        size = (self.output_width, self.output_height)
        if im.size[0] <= im.size[1]:
            size = (self.output_height, self.output_width)
            align = "vertical"
        new_image = im.resize(size, Image.ANTIALIAS)

        self.__increase_seq_value()
        self.__increase_processed_images()
        self.__resized_images += (new_file_path,)

        if self.is_copyright():
            if align == "horizontal":
                copyright_layer = self.__horizontal_copyright
            else:
                copyright_layer = self.__vertical_copyright

            new_image = new_image.convert('RGBA')
            out = Image.alpha_composite(new_image, copyright_layer)
            out.save(new_file_path)
        else:
            new_image.save(new_file_path)

        del im
        del new_image
Example #28
0
    def place_text(self, text, color, angle):

        assert len(color) == 4

        image_size = self.background.size
        txt = Image.new('RGBA', image_size, (255, 255, 255, 0))

        text_size = int((image_size[0] + image_size[1]) / 40)
        font = ImageFont.truetype("comic.ttf", text_size)

        d = ImageDraw.Draw(txt)
        d.text((0, -5), text, font=font, fill=color)
        w, h = d.textsize(text, font)

        coords = self.generate_coords(w)

        txt = txt.crop((0,0, w, h))
        txt1 = txt.rotate(angle, expand=True)

        txt = Image.new('RGBA', self.background.size, (255, 255, 255, 0))

        text_coords = (int(coords[0] - w/2), int(coords[1] - h/2))
        txt.paste(txt1, text_coords)

        self.background = Image.alpha_composite(self.background, txt)

        return self
Example #29
0
    def makeChatLine(self):

        xGapL = self.attrDict["xGapL"]
        yGapT = self.attrDict["yGapT"]
        xGapR = self.attrDict["xGapR"]

        im = Image.new("RGBA", (720, self.attrDict["totalHeight"]), self.attrDict["backgroundColor"])
        imD = ImageDraw.Draw(im, "RGBA")

        if self.person == "sender":
            imD.rectangle(
                [(xGapL, yGapT), (xGapL + self.attrDict["chatWidth"], yGapT + self.attrDict["chatHeight"])],
                self.attrDict["chatboxColor1"],
                self.attrDict["outlineColor"],
            )
        else:
            imD.rectangle(
                [(xGapR, yGapT), (xGapR + self.attrDict["chatWidth"], yGapT + self.attrDict["chatHeight"])],
                self.attrDict["chatboxColor2"],
                self.attrDict["outlineColor"],
            )

        if self.person == "sender":
            blueTick = Image.open("whatsapp_assets/bluetick.png")
            im.paste(
                blueTick, (643, self.attrDict["textHeight"] - 27)
            )  # 643 is the X-position, located 27 pixels from bottom of the chat snippet

        txt = self.textFormat()
        out = Image.alpha_composite(im, txt)
        # out.show()
        return out
Example #30
0
def photo_enhance(desc_info):
    img = Image.open('bing.jpg').convert('RGBA')
    txt = Image.new('RGBA', img.size, (255, 255, 255, 0))
    draw = ImageDraw.Draw(txt)
    font_size=16
    font = ImageFont.truetype("DejaVuSansMono.ttf", font_size, encoding='utf-8')
    for desc in desc_info:
        tempDesc = desc['desc']
        x, y = (int(19.20 * desc['locx']), int(10.80 * desc['locy']))

        # Too much dark method, as long as some hard code here.
        # w, h = font.getsize(str([' ' for i in range(0, int(desc['maxLineCount']))]))
        #w, h = font.getsize(str(['s' for i in range(0, 50)])[:int(desc['maxLineCount'] * 3.6)])
        #e=font.getsize('ssdfasdf')
        w=desc['maxLineCount']*10
        h=font_size
        rectangleoffset = 6
        draw.rectangle(
            (x - rectangleoffset, y - rectangleoffset, x + rectangleoffset + w,
             y + rectangleoffset*2 + h * desc['line']),
            fill=(30, 30, 21, 130))
        draw.text((x, y), tempDesc, fill=(255, 255, 255, 100),
                  font=font)
    result = Image.alpha_composite(img, txt)
    result.save('bing.jpg')
Example #31
0
def main():
    parser = argparse.ArgumentParser(description="Draw text on JPEG.")
    parser.add_argument(
        'input_image_file', 
        help='File name of input image. The image must be in JPEG format.', 
        type=str,
    )
    parser.add_argument(
        'text', 
        help='Text for insert to image.', 
        type=str,
    )
    parser.add_argument(
        '-of',
        '--output_file',
        help='Output image file name. default is "${input_image_file}_drawtext.jpg".', 
        type=str,
    )
    parser.add_argument(
        '-ff',
        '--font_file',
        help='Font file name for text. default is "NotoSerifCJKjp-Black.otf".', 
        type=str,
    )
    parser.add_argument(
        '-fs',
        '--font_size',
        help='Font size for text. default is 50.', 
        type=int,
        default=50,
    )
    parser.add_argument(
        '-sw',
        '--stroke_width',
        help='Stroke width for text. default is 3.', 
        type=int,
        default=3,
    )
    parser.add_argument(
        '-sp',
        '--spacing',
        help='Spacing for text line. default is 0.', 
        type=int,
        default=0,
    )
    parser.add_argument(
        '-al',
        '--align',
        help='Align for text. default is "center".', 
        type=str,
        default="center",
    )
    parser.add_argument(
        '-fc',
        '--font_color',
        help='Font color for text. default is "#FFFF00".', 
        type=str,
        default="#FFFF00",
    )
    parser.add_argument(
        '-sc',
        '--stroke_color',
        help='Stroke color for text. default is "#000000".', 
        type=str,
        default="#000000",
    )
    parser.add_argument(
        '-rc',
        '--rect_color',
        help='Rect color for background of font. default is "#FFFFFF80".', 
        type=str,
        default="#FFFFFF80",
    )
    args = parser.parse_args()

    input_image_file = args.input_image_file
    text = args.text
    stroke_width = args.stroke_width
    spacing = args.spacing
    align = args.align
    font_color = args.font_color
    stroke_color = args.stroke_color
    rect_color = args.rect_color
    black_color = (0, 0, 0)
    yellow_color = (255, 255, 25)
    rect_fill_white_color = (255, 255, 255, 128)

    # set font
    font_file = args.font_file
    font_size = args.font_size
    if font_file is None:
        absolute_path = pathlib.Path(__file__).resolve()
        script_dir_path = absolute_path.parent
        font_file = str(
            script_dir_path.joinpath(
                "NotoSerifCJKjp-Black.otf",
            )
        )
    font = ImageFont.truetype(
        font_file,
        font_size,
    )

    # Declare output file name.
    output_file = args.output_file
    if output_file is None:
        p_file = pathlib.Path(input_image_file)
        p_dir = p_file.parent
        suffix = p_file.suffix
        stem = p_file.stem
        output_file = p_dir.joinpath(
            stem + "_drawtext" + suffix,
        )
        
    ## import image
    img = Image.open(input_image_file).copy()
    text_draw = ImageDraw.Draw(img)

    # get text_size
    text_size = text_draw.textsize(
        text,
        font=font,
        stroke_width=stroke_width,
        spacing=spacing,
    )

    # get text_position
    text_position_x = int(img.size[0] / 2 - text_size[0] / 2)
    text_position_y = int(img.size[1] / 2 - text_size[1] / 2)
    text_position = (text_position_x, text_position_y)

    # get rect position
    rect_position = (
        0,
        text_position[1],
        img.size[0],
        text_position[1] + text_size[1]
    )

    # draw rectangle
    img_alpha = img.convert('RGBA')
    rectangle_alpha = Image.new('RGBA', img.size)
    rectangle_draw = ImageDraw.Draw(rectangle_alpha)
    rectangle_draw.rectangle(rect_position, fill=rect_color)
    img = Image.alpha_composite(img_alpha, rectangle_alpha)
    img = img.convert("RGB")

    # draw text
    text_draw = ImageDraw.Draw(img)
    text_draw.text(
        text_position,
        text,
        font=font,
        fill=font_color,
        stroke_width=stroke_width,
        stroke_fill=stroke_color,
        align=align,
        spacing=spacing,
    )
    img.save(output_file)
Example #32
0
    async def seasoncreate(self, data, seasondata, season, profile,
                           seasonname):
        font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf"
        bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf"
        name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8")
        header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8")
        operator = random.choice(self.bgs)

        bg_image = Image.open(
            f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA")

        profile_image = Image

        profile_avatar = BytesIO()
        profile_url = data.avatar_url_256
        async with self.session.get(profile_url) as r:
            profile_img = await r.content.read()
            profile_avatar = BytesIO(profile_img)

        profile_image = Image.open(profile_avatar).convert("RGBA")

        # set canvas
        bg_color = (255, 255, 255, 0)
        result = Image.new("RGBA", (1600, 1080), bg_color)
        process = Image.new("RGBA", (1600, 1080), bg_color)

        # draw
        draw = ImageDraw.Draw(process)

        # puts in background
        bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS)
        bg_image = bg_image.crop((0, 0, 1920, 1080))
        result.paste(bg_image, (0, 0))

        aviholder = self.add_corners(
            Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10)
        process.paste(aviholder, (1295, 15), aviholder)
        process.paste(profile_image, (1300, 20))

        # op badge

        if season >= 14:
            ranks = self.ranksember
        else:
            ranks = self.ranks
        url = self.rankurl + ranks[seasondata["rank_text"]]

        process.paste(aviholder, (995, 15), aviholder)
        im = Image.open(BytesIO(await self.getimg(url)))
        im = im.resize((256, 256), Image.ANTIALIAS)
        process.paste(im, (1000, 20))

        # data
        # draw.text((440, 40), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt)
        draw.text(
            (
                self._center(
                    440,
                    1000,
                    "Name: {}".format(self._truncate_text(data.username, 18)),
                    header_fnt,
                ),
                40,
            ),
            "Name: {}".format(self._truncate_text(data.username, 18)),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (
                self._center(440, 1000, "Platform: {}".format(
                    str(data.platform).title()), header_fnt),
                90,
            ),
            "Platform: {}".format(str(data.platform).title()),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (
                self._center(
                    440, 1000, "Region: {}".format(
                        self.regions[seasondata["region"]]), header_fnt),
                140,
            ),
            "Region: {}".format(self.regions[seasondata["region"]]),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )

        draw.text(
            (self._center(440, 1000, f"{seasonname} Statistics",
                          header_fnt), 190),
            f"{seasonname} Statistics",
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )

        draw.text(
            (520, 320),
            "Games Played: {}".format(seasondata["wins"] +
                                      seasondata["losses"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 380),
            "Wins: {}".format(seasondata["wins"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (960, 380),
            "Losses: {}".format(seasondata["losses"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 440),
            "Abandons: {}".format(seasondata["abandons"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        try:
            wlr = round(
                seasondata["wins"] /
                (seasondata["wins"] + seasondata["losses"]), 2)
        except ZeroDivisionError:
            wlr = 0
        draw.text(
            (960, 440),
            "Total W/LR: {}%".format(wlr * 100),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        draw.text(
            (520, 520),
            "Kills: {}".format(seasondata["kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (960, 520),
            "Deaths: {}".format(seasondata["deaths"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 580),
            "MMR: {}".format(seasondata["mmr"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 640),
            "Max MMR: {}".format(seasondata["max_mmr"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 700),
            "Previous Rank MMR: {}".format(seasondata["prev_rank_mmr"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 760),
            "Next Rank MMR: {}".format(seasondata["next_rank_mmr"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 820),
            "Rank: {}".format(seasondata["rank_text"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        if seasondata["rank_text"] == "Champions":
            draw.text(
                (960, 820),
                "Champion Rank Position: {}".format(
                    seasondata["champions_rank_position"]),
                fill=(255, 255, 255, 255),
                font=name_fnt,
            )
        draw.text(
            (520, 880),
            "Max Rank: {}".format(seasondata["max_rank_text"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        result = Image.alpha_composite(result, process)
        file = BytesIO()
        result.save(file, "png")
        file.name = f"season-{data.username}.png"
        file.seek(0)
        image = discord.File(file)
        return image
Example #33
0
print("Imposing heatmap over map")
#impose heatmap over map image
top = Image.open('images/heatmap.png')
bottom = map.mapImage
top = top.convert("RGBA")
top.putalpha(128)
datas = top.getdata()

newData = []
colormap = matplotlib.cm.get_cmap(colormap)
rgba = colormap(0.0)
rgba = (int(rgba[0] * 255), int(rgba[1] * 255), int(rgba[2] * 255),
        int(rgba[3] * 255))
for item in datas:
    if item[0] == rgba[0] and item[1] == rgba[1] and item[2] == rgba[2]:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)

top.putdata(newData)
bottom = bottom.convert("RGBA")
bottom.putalpha(255)
top = top.resize(bottom.size)
final = Image.alpha_composite(bottom, top)
final = final.convert("RGB")
if len(sys.argv) > 3:
    final.save("images/" + sys.argv[3])
else:
    final.show()
Example #34
0
 def _draw_legend(self, img, marks, rows, position):
     legend = Legend(self._config).draw(img.size, position, marks, rows)
     return Image.alpha_composite(img, legend)
Example #35
0
def apply_watermark(doc):
    if not is_image_path(doc.file_url):
        return
    image_settings = frappe.get_doc("Renovation Image Settings",
                                    "Renovation Image Settings")

    if not image_settings.wm_image:
        return  # No watermark

    if doc.file_url == image_settings.wm_image \
            or doc.attached_to_doctype == "Renovation Image Settings":
        return  # dont apply watermark on watermark :p

    if not os.path.exists(get_file_path(image_settings.wm_image)):
        return  # file not found

    og_folder = get_watermarks_og_folder_path()
    if not os.path.isdir(og_folder):
        os.makedirs(og_folder)

    extn = get_extension(doc.file_url)
    # check if og_folder has doc.name already
    # if not copy file_url there
    og_file = os.path.join(og_folder, doc.name + '.' + extn)
    if not os.path.exists(og_file):
        # copy file_url to og_folder
        im = Image.open(get_file_path(doc.file_url)).convert("RGBA")
        saveImage(im, og_file, extn)
    else:
        im = Image.open(og_file).convert("RGBA")

    wt_im = Image.open(get_file_path(image_settings.wm_image))
    wt_w, wt_h = wt_im.size
    width, height = im.size

    # scale watermark down according to size specified
    wm_p = image_settings.wm_percent / 100
    wt_size = (cint(width * wm_p), cint(wt_h * width * wm_p / wt_w))
    # resize using thumbnail
    wt_im.thumbnail(wt_size, Image.ANTIALIAS)
    wt_im = wt_im.convert("RGBA")
    wt_im_copy = wt_im.copy()

    # opacity
    # thresh = 200
    # fn = lambda x : 255 if x > thresh else 0
    # mask = wt_im.convert("L").point(fn, mode='1') # 8-bit per pixel
    # mask = mask.convert("L")
    # this will have the transparent part a bit dark
    wt_im.putalpha(cint(256 * image_settings.wm_opacity / 100))
    # wt_im.putalpha(mask)

    # wt_pos
    pos = image_settings.wm_position
    margin = width * image_settings.wm_margin_percent / 100
    # calculate lft and top seperately
    if "Left" in pos:
        lft = margin
    elif "Right" in pos:
        lft = width - wt_size[0] - margin
    else:
        lft = (width - wt_size[0]) // 2  # Center

    if "Top" in pos:
        top = margin
    elif "Bottom" in pos:
        top = height - wt_size[1] - margin
    else:
        top = (height - wt_size[1]) // 2

    # make wt same size
    wt_scaled = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    wt_scaled.paste(wt_im, (cint(lft), cint(top)), mask=wt_im_copy)

    b = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    b = Image.alpha_composite(b, im)
    b = Image.alpha_composite(b, wt_scaled)

    saveImage(b, get_file_path(doc.file_url), extn)
Example #36
0
def ticket_changer(base_img, paste_img, header_color, font_header, font_main,
                   font_bold, passenger_info):
    # я понимаю, что делать функцию с таким колличеством параметров это не есть хорошо, но неужели лучше принять
    # всю инфу каким нибудь одним параметром и делить потом ее внутри функции?
    # TODO Вообще да, было бы удобно собрать данные по группам хотя бы
    # TODO например передавать сюда словарь "данные_о_пассажире", который бы хранил всю информацию,
    # TODO которая надо разместить на билете
    # TODO А какие-то системные параметры вроде base_img, paste_img, header_color, font_header
    # TODO можно оставить и так.
    base = Image.open(base_img).convert("RGBA")
    paste = Image.open(paste_img).convert("RGBA")
    fnt = ImageFont.truetype(font_main, 30)
    font_bold = ImageFont.truetype(font_bold, 30)
    fnt_small = ImageFont.truetype(font_main, 20)
    fnt_small_2 = ImageFont.truetype(font_main, 13)
    fnt2 = ImageFont.truetype(font_header, 30)
    draw = ImageDraw.Draw(base)

    seat = random_seat_generator()
    gate = gate_generator()
    flight = random_flight_generator()

    correct_split = passenger_info['correct_flight'].split(' ')
    correct_time = correct_split[2].replace('.', ':')
    correct_date = correct_split[1]
    boarding = datetime.strptime(correct_time, "%H:%M") - timedelta(minutes=40)
    boarding_str = boarding.strftime("%H:%M")
    end_of_boarding = datetime.strptime(correct_time,
                                        "%H:%M") - timedelta(minutes=20)
    end_of_boarding_str = end_of_boarding.strftime("%H:%M")
    passenger = passenger_info['name'] + ' ' + passenger_info['surname']
    departure = passenger_info['departure_city'] + airport_generator(
        passenger_info['departure_city'])
    arrival = passenger_info['destination_city'] + airport_generator(
        passenger_info['destination_city'])

    draw.polygon(((0, 0), (1009, 0), (1009, 81), (0, 81)),
                 outline=header_color,
                 fill=header_color)
    base.paste(paste, (0, 0))
    base.paste(paste, (743, 0))

    txt = Image.new("RGBA", base.size, (255, 255, 255, 0))
    d = ImageDraw.Draw(txt)

    d.text((250, 25), 'Посадочный талон', font=font_bold, fill=(0, 0, 0, 240))
    d.text((550, 29), 'Boarding pass', font=fnt2, fill=(0, 0, 0, 240))

    d.text((108, 132), gate, font=fnt, fill=(0, 0, 0, 240))
    d.text((108, 210), boarding_str, font=fnt, fill=(0, 0, 0, 240))
    d.text((108, 300), end_of_boarding_str, font=fnt, fill=(0, 0, 0, 240))
    d.text((332, 125), passenger, font=fnt_small, fill=(0, 0, 0, 240))
    d.text((332, 187), departure, font=fnt_small, fill=(0, 0, 0, 240))
    d.text((535, 187), arrival, font=fnt_small, fill=(0, 0, 0, 240))
    d.text((332, 250), correct_date, font=fnt_small, fill=(0, 0, 0, 240))
    d.text((535, 250), correct_time, font=fnt_small, fill=(0, 0, 0, 240))
    d.text((332, 310), seat, font=fnt, fill=(0, 0, 0, 240))
    d.text((535, 310), flight, font=fnt, fill=(0, 0, 0, 240))

    d.text((782, 125), passenger, font=fnt_small_2, fill=(0, 0, 0, 240))
    d.text((782, 187), correct_time, font=fnt_small_2, fill=(0, 0, 0, 240))
    d.text((782, 250), flight, font=fnt_small_2, fill=(0, 0, 0, 240))
    d.text((782, 310), seat, font=fnt_small, fill=(0, 0, 0, 240))

    d.text((900, 187), correct_date, font=fnt_small_2, fill=(0, 0, 0, 240))
    d.text((900, 250), departure, font=fnt_small_2, fill=(0, 0, 0, 240))
    d.text((900, 310), arrival, font=fnt_small_2, fill=(0, 0, 0, 240))

    out = Image.alpha_composite(base, txt)
    # with open ('temp_ticket.png', 'wb') as f:
    #     out.save(f, 'png')

    temp_file = BytesIO()
    out.save(temp_file, 'png')
    temp_file.seek(0)

    return temp_file
Example #37
0
def draw_status_log(status_log: List[LogEntry], *, timezone: datetime.timezone =
                    datetime.timezone.utc, show_labels: bool = False, num_days: int = 30) -> BytesIO:

    row_count = 1 + num_days + show_labels
    image, draw = base_image(IMAGE_SIZE * row_count, 1)

    # Set consts
    day_width = IMAGE_SIZE / (60 * 60 * 24)
    day_height = IMAGE_SIZE // row_count

    now = datetime.datetime.now(timezone)
    time_offset = now.utcoffset().total_seconds()  # type: ignore
    total_duration = 0.0

    if show_labels:
        time_offset += 60 * 60 * 24

    # Draw status log entries
    for status, _, timespan in status_log:
        duration: float = timespan.total_seconds()
        total_duration += duration
        new_time_offset = time_offset + duration

        start_x = round(time_offset * day_width)
        end_x = round(new_time_offset * day_width)
        draw.rectangle(((start_x, 0), (end_x, 1)), fill=COLOURS[status])

        time_offset = new_time_offset

    # Reshape Image
    pixels = numpy.array(image)
    # pixels = pixels[:, IMAGE_SIZE:]
    pixels = pixels.reshape(row_count, IMAGE_SIZE, 4)
    pixels = pixels.repeat(day_height, 0)
    image = Image.fromarray(pixels, 'RGBA')

    if show_labels:
        overlay = Image.new('RGBA', image.size, (0, 0, 0, 0))
        draw = ImageDraw.Draw(overlay)

        # Set offsets based on font size
        font = ImageFont.truetype('res/roboto-bold.ttf', IMAGE_SIZE // int(1.66 * num_days))
        text_width, text_height = draw.textsize('\N{FULL BLOCK}' * 2, font=font)
        height_offset = (day_height - text_height) // 2

        x_offset = text_width
        y_offset = day_height

        # Add date labels
        date = now - datetime.timedelta(seconds=total_duration)
        for _ in range(int(total_duration // ONE_DAY) + 2):  # 2 because of timezone offset woes

            # if weekend draw signifier
            if date.weekday() == 5:
                draw.rectangle((0, y_offset, IMAGE_SIZE, y_offset + (2 * day_height)), fill=TRANSLUCENT)

            # Add date
            _, text_height = draw.textsize(date.strftime('%b. %d'), font=font)
            draw.text((x_offset, y_offset + height_offset), date.strftime('%b. %d'), font=font, align='left', fill=WHITE)
            y_offset += day_height
            date += datetime.timedelta(days=1)

        # Add timezone label
        draw.text((x_offset, height_offset), str(timezone), font=font, align='left', fill='WHITE')

        # Add hour lines
        for i in range(1, 24):
            x_offset = ONE_HOUR * i
            colour = WHITE if not i % 6 else OPAQUE
            draw.line((x_offset, day_height, x_offset, IMAGE_SIZE), fill=colour, width=DOWNSAMPLE * 4)

        image = Image.alpha_composite(image, overlay)
        draw = ImageDraw.Draw(image)

        # Add time labels
        time = start_of_day(now)
        for x_offset in (ONE_HOUR * 6, ONE_HOUR * 12, ONE_HOUR * 18):
            time += datetime.timedelta(hours=6)
            text_width, _ = draw.textsize(time.strftime('%H:00'), font=font)
            draw.text((x_offset - (text_width // 2), height_offset), time.strftime('%H:00'), font=font, align='left', fill=WHITE)

    return as_bytes(resample(image))
Example #38
0
    async def operatorstatscreate(self, data, index, profile):
        font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf"
        bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf"
        name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8")
        header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8")
        operator = random.choice(self.bgs)
        opdata = data.operators[index]

        bg_image = Image.open(
            f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA")

        profile_image = Image

        profile_avatar = BytesIO()
        profile_url = data.avatar_url_256
        async with self.session.get(profile_url) as r:
            profile_img = await r.content.read()
            profile_avatar = BytesIO(profile_img)

        profile_image = Image.open(profile_avatar).convert("RGBA")

        # set canvas
        bg_color = (255, 255, 255, 0)
        result = Image.new("RGBA", (1600, 1080), bg_color)
        process = Image.new("RGBA", (1600, 1080), bg_color)

        # draw
        draw = ImageDraw.Draw(process)

        # puts in background
        bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS)
        bg_image = bg_image.crop((0, 0, 1920, 1080))
        result.paste(bg_image, (0, 0))

        aviholder = self.add_corners(
            Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10)
        process.paste(aviholder, (1295, 15), aviholder)
        process.paste(profile_image, (1300, 20))

        # op badge
        url = opdata["badge_image"]
        process.paste(aviholder, (995, 15), aviholder)
        im = Image.open(BytesIO(await self.getimg(url)))
        im = im.resize((256, 256), Image.ANTIALIAS)
        process.paste(im, (1000, 20))

        # data
        # draw.text((440, 40), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt)
        draw.text(
            (
                self._center(
                    440,
                    1000,
                    "Name: {}".format(self._truncate_text(data.username, 18)),
                    header_fnt,
                ),
                40,
            ),
            "Name: {}".format(self._truncate_text(data.username, 18)),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (
                self._center(440, 1000, "Platform: {}".format(
                    str(data.platform).title()), header_fnt),
                90,
            ),
            "Platform: {}".format(str(data.platform).title()),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (self._center(440, 1000, f"{opdata['name']} Statistics",
                          header_fnt), 140),
            f"{opdata['name']} Statistics",
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )

        draw.text(
            (520, 320),
            "Games Played: {}".format(opdata["wins"] + opdata["losses"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text((520, 380),
                  "Wins: {}".format(opdata["wins"]),
                  fill=(255, 255, 255, 255),
                  font=name_fnt)
        draw.text(
            (920, 380),
            "Losses: {}".format(opdata["losses"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        try:
            wlr = round(opdata["wins"] / (opdata["wins"] + opdata["losses"]),
                        2)
        except ZeroDivisionError:
            wlr = 0
        draw.text(
            (520, 440),
            "Total W/LR: {}%".format(wlr * 100),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        draw.text(
            (520, 520),
            "Kills: {}".format(opdata["kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 520),
            "Deaths: {}".format(opdata["deaths"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text((520, 580),
                  "KDR: {}".format(opdata["kd"]),
                  fill=(255, 255, 255, 255),
                  font=name_fnt)
        draw.text(
            (520, 640),
            "Headshots: {}".format(opdata["headshots"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        y = 760
        for ability in opdata["abilities"]:

            draw.text(
                (520, y),
                "{}: {}".format(ability["ability"], ability["value"]),
                fill=(255, 255, 255, 255),
                font=name_fnt,
            )
            y += 80

        m, _ = divmod(opdata["playtime"], 60)
        h, m = divmod(m, 60)
        d, h = divmod(h, 24)
        draw.text(
            (520, 700),
            f"Playtime: {d:d}d {h:d}h {m:02d}m",
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        result = Image.alpha_composite(result, process)
        result = result.crop((500, 0, 1600, 1080))
        file = BytesIO()
        result.save(file, "png")
        file.name = f"operator-{data.username}.png"
        file.seek(0)
        image = discord.File(file)
        return image
Example #39
0
    async def profilecreate(self, data):
        font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf"
        bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf"
        name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8")
        header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8")
        operator = random.choice(self.bgs)

        bg_image = Image.open(
            f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA")

        profile_image = Image

        profile_avatar = BytesIO()
        profile_url = data.avatar_url_256
        async with self.session.get(profile_url) as r:
            profile_img = await r.content.read()
            profile_avatar = BytesIO(profile_img)

        profile_image = Image.open(profile_avatar).convert("RGBA")

        # set canvas
        bg_color = (255, 255, 255, 0)
        result = Image.new("RGBA", (1280, 1080), bg_color)
        process = Image.new("RGBA", (1280, 1080), bg_color)

        # draw
        draw = ImageDraw.Draw(process)

        # puts in background
        bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS)
        bg_image = bg_image.crop((0, 0, 1920, 1080))
        result.paste(bg_image, (0, 0))

        aviholder = self.add_corners(
            Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10)
        process.paste(aviholder, (995, 15), aviholder)
        process.paste(profile_image, (1000, 20))

        # data
        draw.text(
            (
                self._center(
                    440,
                    1000,
                    "Name: {}".format(self._truncate_text(data.username, 18)),
                    header_fnt,
                ),
                40,
            ),
            "Name: {}".format(self._truncate_text(data.username, 18)),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (
                self._center(440, 1000, "Platform: {}".format(
                    str(data.platform).title()), header_fnt),
                90,
            ),
            "Platform: {}".format(str(data.platform).title()),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (self._center(440, 1000, "General Statistics", header_fnt), 140),
            "General Statistics",
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )

        draw.text(
            (self._center(1000, 1256, f"Level: {data.level}",
                          header_fnt), 300),
            f"Level: {data.level}",
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (520, 400),
            "Wins: {}".format(data.general_stats["wins"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 400),
            "Losses: {}".format(data.general_stats["losses"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 470),
            "Draws: {}".format(data.general_stats["draws"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 470),
            "Total W/LR: {}%".format(
                round(
                    data.general_stats["wins"] /
                    data.general_stats["games_played"], 2) * 100),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 540),
            "Lootbox %: {}%".format(data.lootbox_probability),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 610),
            "Kills: {}".format(data.general_stats["kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 610),
            "Deaths: {}".format(data.general_stats["deaths"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 680),
            "Assists: {}".format(data.general_stats["assists"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 680),
            "KDR: {}".format(data.general_stats["kd"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 750),
            "Revives: {}".format(data.general_stats["revives"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 750),
            "Suicides: {}".format(data.general_stats["suicides"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 820),
            "Blind Kills: {}".format(data.general_stats["blind_kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 820),
            "Melee Kills: {}".format(data.general_stats["melee_kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 890),
            "Pentration Kills: {}".format(
                data.general_stats["penetration_kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 890),
            "DBNOs: {}".format(data.general_stats["dbnos"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        m, _ = divmod(data.general_stats["playtime"], 60)
        h, m = divmod(m, 60)
        d, h = divmod(h, 24)
        draw.text(
            (520, 1010),
            f"Playtime: {d:d}d {h:d}h {m:02d}m",
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        result = Image.alpha_composite(result, process)
        file = BytesIO()
        result.save(file, "png")
        file.name = f"general-{data.username}.png"
        file.seek(0)
        image = discord.File(file)
        return image
Example #40
0
def img_bottom_text_draw(pic_obj, exif):
    # get an image
    base_img = pic_obj.convert("RGBA")

    total_size = (base_img.size[0] + 20, base_img.size[1] + 40)

    base_layer = pillowImage.new("RGBA", total_size, (255, 255, 255, 0))

    # 计算位置和大小
    base_img_position = (10, 10)

    # draw logo
    base_layer.paste(base_img, box=base_img_position)

    # make a blank image for the text, initialized to transparent text color
    text_layer = pillowImage.new("RGBA", total_size, (255, 255, 255, 0))

    # get a font
    font_size = 19

    font_name = "NotoSansHans-Light.otf"
    # font_name = "NotoSansHans-Thin-Windows.otf"
    # font_name ="点点像素体-方形.ttf"

    text_font = ImageFont.truetype(font_name, font_size)

    # get a drawing context
    draw_obj = ImageDraw.Draw(text_layer)

    # set text color
    text_color = (
        0  # R
        ,
        0  # G
        ,
        0  # B
        ,
        255)  # A

    # draw date
    photo_date = exif['Exif.Photo.DateTimeOriginal'].split(" ")[0].replace(
        ":", "-")
    text_position = TextPosition.TextPosition("r", 10, "b", 10, 4, "right")
    text_xy = text_position.position(text_layer, photo_date, text_font)
    draw_obj.text(text_xy,
                  photo_date,
                  font=text_font,
                  fill=text_color,
                  align="right")

    # draw film type
    film = exif["Exif.Photo.UserComment"][14:]
    text_position = TextPosition.TextPosition("m", 0, "b", 10, 4, "center")
    text_xy = text_position.position(text_layer, film, text_font)
    draw_obj.text(text_xy,
                  film,
                  font=text_font,
                  fill=text_color,
                  align="center")

    # draw Camera
    camera = exif["Exif.Image.Model"]
    text_position = TextPosition.TextPosition("l", 10, "b", 10, 4, "right")
    text_xy = text_position.position(text_layer, camera, text_font)
    draw_obj.text(text_xy,
                  camera,
                  font=text_font,
                  fill=text_color,
                  align="right")

    # 后处理,与原始图像合并再转回RGB
    out = pillowImage.alpha_composite(base_layer, text_layer)
    out_jpg = out.convert('RGB')

    return out_jpg
def add_watermark(input_image_path,
                    watermark,
                    text=True,
                    fntsize=30,
                    watermark_width=150,
                    position='center',
                    location_min=0.25,
                    location_max=0.75,
                    alpha_composite=True,
                    alpha=0.25,
                    val=False):
    

    val_transform = transforms.Compose([
                                transforms.Resize(256),
                                transforms.CenterCrop(224)])
    
    if text:        # watermark is a string
        # get an image
        base = Image.open(input_image_path).convert("RGBA")

        # make a blank image for the text, initialized to transparent text color
        txt = Image.new("RGBA", base.size, (255,255,255,0))

        # get a font
        fnt = ImageFont.truetype("fonts/FreeMonoBold.ttf", fntsize)
        # get a drawing context
        d = ImageDraw.Draw(txt)

        # draw text, half opacity
        if position == 'center':
            w = int(base.size[0]*0.5)
            h = int(base.size[1]*0.5)
            d.text((w, h), watermark, font=fnt, fill=(0,0,0,128), anchor='mm')
        elif position == 'multiple':
            for w in [int(base.size[0]*i) for i in [0.25, 0.5, 0.75]]:
                for h in [int(base.size[1]*i) for i in [0.25, 0.5, 0.75]]:
                    d.text((w, h), watermark, font=fnt, fill=(0,0,0,128), anchor='mm')                
        elif position == 'random':
            w = random.randint(int(base.size[0]*0.25), int(base.size[0]*0.75))
            h = random.randint(int(base.size[1]*0.25), int(base.size[1]*0.75))
            d.text((w, h), watermark, font=fnt, fill=(0,0,0,128), anchor='mm')  
        else:
            logging.info("Invalid position argument")
            return

        out = Image.alpha_composite(base, txt)
        out = out.convert("RGB")
        # out.show()	
        return out
    
    else:       # watermark is an RGB image
        if alpha_composite:
            img_watermark = Image.open(watermark).convert('RGBA')
            base_image = Image.open(input_image_path).convert('RGBA')

            if val:
                # preprocess validation images
                base_image = val_transform(base_image)
            # watermark = Image.open(watermark_image_path)
            width, height = base_image.size

            # let's say pasted watermark is 150 pixels wide
            # w_width, w_height = img_watermark.size
            w_width, w_height = watermark_width, int(img_watermark.size[1]*watermark_width/img_watermark.size[0])
            img_watermark = img_watermark.resize((w_width, w_height))                 
            transparent = Image.new('RGBA', (width, height), (0,0,0,0))
            # transparent.paste(base_image, (0, 0))
            if position == 'center':            
                location = (int((width - w_width)/2), int((height - w_height)/2))
                # location = (450, 100)
                # print(location)
                transparent.paste(img_watermark, location)
                # transparent.show()
                # use numpy
                na = np.array(transparent).astype(np.float)
                # Halve all alpha values
                # na[..., 3] *=0.5
                transparent = Image.fromarray(na.astype(np.uint8))
                # transparent.show()
                
                # change alpha of base image at corresponding locations
                na = np.array(base_image).astype(np.float)
                # Halve all alpha values
                # location = (max(0, min(location[0], na.shape[1])), max(0, min(location[1], na.shape[0]))) # if location is negative, clip at 0
                # TODO: Aniruddha I ensure that left upper location will never be negative. So I removed clipping.
                na[..., 3][location[1]: (location[1]+w_height), location[0]: (location[0]+w_width)] *=alpha
                base_image = Image.fromarray(na.astype(np.uint8))
                # base_image.show()
                transparent = Image.alpha_composite(transparent, base_image)
            
            elif position == 'multiple':
                na = np.array(base_image).astype(np.float)
                for w in [int(base_image.size[0]*i) for i in [0.25, 0.5, 0.75]]:
                    for h in [int(base_image.size[1]*i) for i in [0.25, 0.5, 0.75]]:
                        location = (int(w - w_width/2), int(h - w_height/2))  
                        transparent.paste(img_watermark, location)
                        
                        # change alpha of base image at corresponding locations                    
                        # Halve all alpha values
                        location = (max(0, min(location[0], na.shape[1])), max(0, min(location[1], na.shape[0]))) # if location is negative, clip at 0
                        na[..., 3][location[1]: (location[1]+w_height), location[0]: (location[0]+w_width)] *=alpha
                base_image = Image.fromarray(na.astype(np.uint8))
                # use numpy
                na = np.array(transparent).astype(np.float)
                # Halve all alpha values
                # na[..., 3] *=0.5
                transparent = Image.fromarray(na.astype(np.uint8))
                # transparent.show()                    
                # base_image.show()
                transparent = Image.alpha_composite(transparent, base_image)
                
            elif position == 'random':
                # print(base_image.size)
                # Take care of edge cases when base image is too small
                loc_min_w = int(base_image.size[0]*location_min)
                loc_max_w = int(base_image.size[0]*location_max - w_width)
                if loc_max_w<loc_min_w:
                    loc_max_w = loc_min_w

                loc_min_h = int(base_image.size[1]*location_min)
                loc_max_h = int(base_image.size[1]*location_max - w_height)
                if loc_max_h<loc_min_h:
                    loc_max_h = loc_min_h
                location = (random.randint(loc_min_w, loc_max_w), 
                            random.randint(loc_min_h, loc_max_h))
                # print(position)
                transparent.paste(img_watermark, location)
                # transparent.show()
                # use numpy
                na = np.array(transparent).astype(np.float)
                # Halve all alpha values
                # na[..., 3] *=0.5
                transparent = Image.fromarray(na.astype(np.uint8))
                # transparent.show()
                
                # change alpha of base image at corresponding locations
                na = np.array(base_image).astype(np.float)
                # Halve all alpha values
                # location = (max(0, min(location[0], na.shape[1])), max(0, min(location[1], na.shape[0]))) # if location is negative, clip at 0
                # TODO: Aniruddha I ensure that left upper location will never be negative. So I removed clipping.
                na[..., 3][location[1]: (location[1]+w_height), location[0]: (location[0]+w_width)] *= alpha
                base_image = Image.fromarray(na.astype(np.uint8))
                # base_image.show()
                transparent = Image.alpha_composite(transparent, base_image)
            
            else:
                logging.info("Invalid position argument")
                return

            transparent = transparent.convert('RGB')
            # transparent.show()
            if val:
                return transparent
            else:
                return transparent, location, (w_width, w_height)
                
        else:                       # pasting            
            img_watermark = Image.open(watermark).convert('RGBA')
            base_image = Image.open(input_image_path)
            # watermark = Image.open(watermark_image_path)
            width, height = base_image.size

            # let's say pasted watermark is 150 pixels wide
            # w_width, w_height = img_watermark.size
            w_width, w_height = watermark_width, int(img_watermark.size[1]*watermark_width/img_watermark.size[0])
            img_watermark = img_watermark.resize((w_width, w_height))                 
            transparent = Image.new('RGBA', (width, height), (0,0,0,0))
            transparent.paste(base_image, (0, 0))
            if position == 'center':
                location = (int((width - w_width)/2), int((height - w_height)/2))
                transparent.paste(img_watermark, location, mask=img_watermark)
            elif position == 'multiple':
                for w in [int(base_image.size[0]*i) for i in [0.25, 0.5, 0.75]]:
                    for h in [int(base_image.size[1]*i) for i in [0.25, 0.5, 0.75]]:
                        location = (int(w - w_width/2), int(h - w_height/2))  
                        transparent.paste(img_watermark, location, mask=img_watermark)
            elif position == 'random':
                location = (random.randint(int(base_image.size[0]*0.25 - w_width/2), int(base_image.size[0]*0.75 - w_width/2)), 
                            random.randint(int(base_image.size[1]*0.25 - w_height/2), int(base_image.size[1]*0.75 - w_height/2)))
                transparent.paste(img_watermark, location, mask=img_watermark)
            else:
                logging.info("Invalid position argument")
                return
            
            transparent = transparent.convert('RGB')
            # transparent.show()
            if val:
                return transparent
            else:
                return transparent, location, (w_width, w_height)
Example #42
0
def dither_image_to_web_palette(img, bgcolor):

    if bgcolor is not None:
        # We know the background color so flatten the image and bg color together, thus getting rid of alpha
        # This is important because as discussed below, dithering alpha doesn't work correctly.
        img = Image.alpha_composite(
            Image.new("RGBA", img.size, bgcolor),
            img)  # alpha blend onto image filled with bgcolor
        dithered_img = floydsteinberg_dither_to_web_palette(img)
    else:
        """
        It is not possible to correctly dither in the presence of transparency without knowing the background
        that the image will be composed onto. This is because dithering works by propagating error that is introduced 
        when we select _available_ colors that don't match the _desired_ colors. Without knowing the final color value 
        for a pixel, it is not possible to compute the error that must be propagated FROM it. If a pixel is fully or 
        partially transparent, we must know the background to determine the final color value. We can't even record
        the incoming error for the pixel, and then later when/if we know the background compute the full error and 
        propagate that, because that error needs to propagate into the original color selection decisions for the other
        pixels. Those decisions absorb error and are lossy. You can't later apply more error on top of those color
        decisions and necessarily get the same results as applying that error INTO those decisions in the first place.   
        
        So having established that we could only handle transparency correctly at final draw-time, shouldn't we just 
        dither there instead of here? Well, if we don't know the background color here we don't know it there either. 
        So we can either not dither at all if we don't know the bg color, or make some approximation. We've chosen 
        the latter. We'll handle it here to make the drawing code simpler. So what is our approximation? We basically
        just ignore any color changes dithering makes to pixels that have transparency, and prevent any error from being 
        propagated from those pixels. This is done by setting them all to black before dithering (using an exact-match 
        color in Floyd Steinberg dithering with a web-safe-palette will never cause a pixel to receive enough inbound error
        to change color and thus will not propagate error), and then afterwards we set them back to their original values. 
        This means that transparent pixels are essentially not dithered - they ignore (and absorb) inbound error but they
        keep their original colors. We could alternately play games with the alpha channel to try to propagate the error 
        values for transparent pixels through to when we do final drawing but it only works in certain cases and just isn't 
        worth the effort (which involves writing the dithering code ourselves for one thing).
        """

        # Force image to RGBA if it isn't already - simplifies the rest of the code
        if img.mode != 'RGBA':
            img = img.convert('RGBA')

        rgb_img = img.convert('RGB')

        orig_pixels = img.load()
        rgb_pixels = rgb_img.load()
        width, height = img.size

        for h in range(height):  # set transparent pixels to black
            for w in range(width):
                if (orig_pixels[w, h])[3] != 255:
                    rgb_pixels[w, h] = (0, 0, 0
                                        )  # bashing in a new value changes it!

        dithered_img = floydsteinberg_dither_to_web_palette(rgb_img)

        dithered_pixels = dithered_img.load()  # must do it again

        for h in range(height):  # restore original RGBA for transparent pixels
            for w in range(width):
                if (orig_pixels[w, h])[3] != 255:
                    dithered_pixels[w, h] = orig_pixels[
                        w, h]  # bashing in a new value changes it!

    return dithered_img
Example #43
0
    def make_hourly(self, data, lang):
        city = data['city']
        temp = str(round(data['temperature'])) + '°'
        temp_chart = [
            data['temperature'], data['+2'], data['+4'], data['+6'],
            data['+8'], data['+10'], data['+12']
        ]
        weather = data['summary'].lower()
        wind = str(round(data['wind'])) + messages['ms'][lang]
        humidity = str(int(data['humidity'] * 100)) + '%'
        feels_like = messages['feels_like'][lang] + str(
            round(data['apparentTemperature'])) + '°'
        bw_divs = [79, 186, 293, 400, 507, 614, 721]

        im = Image.new('RGBA', (800, 656), (255, 255, 255, 0))
        bg = Image.open(f'{self.path}/resources/backgrounds/' + data['icon'] +
                        '.png').convert("RGBA")
        card = Image.open(f'{self.path}/resources/card/card.png')
        ic = Image.open(f'{self.path}/resources/icons/' + data['icon'] +
                        '.png')
        ic.thumbnail((999, 180), resample=Image.ANTIALIAS)
        wind_ic = Image.open(f'{self.path}/resources/icons/wind_ic.png')
        hum_ic = Image.open(f'{self.path}/resources/icons/hum_ic.png')
        txt = Image.new('RGBA', im.size, (255, 255, 255, 0))
        graph = self.make_graph(temp_chart, data['icon'])

        font_h = f'{self.path}/resources/fonts/ObjectSans-Heavy.otf'
        font_l = f'{self.path}/resources/fonts/ObjectSans-Regular.otf'

        temp_font = ImageFont.truetype(font=font_h, size=108)
        temp_chart_font_now = ImageFont.truetype(font=font_h, size=25)
        temp_chart_font = ImageFont.truetype(font=font_l, size=25)
        city_font = ImageFont.truetype(font=font_l, size=32)
        feels_like_font = ImageFont.truetype(font=font_l, size=30)
        weather_font = ImageFont.truetype(font=font_h, size=43)
        weather_font_big = ImageFont.truetype(font=font_h, size=58)
        wind_font = ImageFont.truetype(font=font_l, size=29)
        time_font = ImageFont.truetype(font=font_l, size=24)
        time_font_now = ImageFont.truetype(font=font_h, size=24)

        im.paste(bg)
        im.paste(ic, (64, 36), ic)
        im.paste(card, (0, im.height - card.height), card)
        im.paste(graph, (24, im.height - graph.height - 20), graph)
        draw = ImageDraw.Draw(txt)
        text_size = ImageDraw.Draw(txt).textsize

        draw.text((im.width - text_size(city, city_font)[0] - 77, 47),
                  city,
                  font=city_font)
        draw.text((im.width - text_size(temp, temp_font)[0] - 77, 102),
                  text=temp,
                  font=temp_font)
        draw.text(
            (im.width - text_size(feels_like, feels_like_font)[0] - 77, 197),
            text=feels_like,
            font=feels_like_font,
            fill=(255, 255, 255, 221))
        draw.text(((im.width - text_size(wind, wind_font)[0] - 77), 283),
                  text=wind,
                  font=wind_font,
                  fill=(255, 255, 255, 221))
        draw.text(((im.width - text_size(humidity, wind_font)[0] - 77), 244),
                  text=humidity,
                  font=wind_font,
                  fill=(255, 255, 255, 221))
        im.paste(wind_ic, (im.width - text_size(wind, wind_font)[0] - 77 - 10 -
                           wind_ic.width, 282), wind_ic)
        im.paste(hum_ic, (im.width - text_size(humidity, wind_font)[0] - 77 -
                          10 - hum_ic.width, 240), hum_ic)

        for x in bw_divs:
            for y in range(430, im.height - 1):
                yl, yc, yr = 0, 0, 0

                if im.getpixel((x, y)) == (255, 255, 255, 255):
                    continue
                else:
                    yc = y

                    for yy in range(430, im.height - 1):
                        if im.getpixel((x - 15, yy)) != (255, 255, 255, 255):
                            yl = yy
                            break
                        else:
                            continue

                    for yy in range(430, im.height - 1):
                        if im.getpixel((x + 15, yy)) != (255, 255, 255, 255):
                            yr = yy
                            break
                        else:
                            continue

                    if bw_divs.index(x) == 0:
                        draw.text(
                            ((x + 10 -
                              text_size(str(temp_chart[bw_divs.index(x)]),
                                        temp_chart_font_now)[0] / 2),
                             min(yl, yc, yr) - 38),
                            text=str(round(temp_chart[bw_divs.index(x)])) +
                            '°',
                            font=temp_chart_font_now,
                            fill=(64, 64, 64, 255))
                    else:
                        draw.text(
                            ((x + 10 -
                              text_size(str(temp_chart[bw_divs.index(x)]),
                                        temp_chart_font)[0] / 2),
                             min(yl, yc, yr) - 38),
                            text=str(round(temp_chart[bw_divs.index(x)])) +
                            '°',
                            font=temp_chart_font,
                            fill=(64, 64, 64, 221))
                    break

        time = data['time'].split(':')
        time_list = list()
        time_list.append(data['time'])
        hours = time[0]
        minutes = time[1]

        if int(hours) + 3 > 23:
            if int(hours) == 22:
                if int(minutes) > 30:
                    hours = '01'
                    time[1] = '00'
                    time_list.append('01:00')
                else:
                    hours = '00'
                    time[1] = '00'
                    time_list.append('00:00')

            elif int(hours) == 23:
                if int(minutes) > 30:
                    hours = '02'
                    time[1] = '00'
                    time_list.append('02:00')
                else:
                    hours = '01'
                    time[1] = '00'
                    time_list.append('01:00')

            else:
                if int(minutes) > 30:
                    hours = '00'
                    time[1] = '00'
                    time_list.append('00:00')
                else:
                    hours = '23'
                    time[1] = '00'
                    time_list.append('23:00')

        else:
            if int(minutes) > 30:
                hours = str(int(hours) + 3)
                time[0] = hours
                time[1] = '00'
                time_list.append(':'.join(time))
            else:
                hours = str(int(hours) + 2)
                time[0] = hours
                time[1] = '00'
                time_list.append(':'.join(time))

        for i in range(0, 5):
            if int(hours) + 2 > 23:
                if int(hours) % 2 == 0:
                    hours = '00'
                else:
                    hours = '01'
            else:
                hours = str(int(hours) + 2)
            time_plus = [hours, '00']
            time_list.append(':'.join(time_plus))

        for i in range(0, 7):
            if i:
                draw.text((bw_divs[i] - text_size(time_list[i])[0], 370),
                          text=time_list[i],
                          font=time_font,
                          fill=(48, 48, 48, 163))
            else:
                draw.text((bw_divs[i] - text_size(time_list[i])[0], 370),
                          text=time_list[i],
                          font=time_font_now,
                          fill=(64, 64, 64, 255))

        lines = textwrap.wrap(weather, width=17)
        if len(weather) < 13:
            draw.text((64, 253), text=lines[0], font=weather_font_big)
        else:
            if len(lines) > 2:
                liness = textwrap.wrap(weather, width=23)
                draw.text((64, 230),
                          text=liness[0],
                          font=ImageFont.truetype(font=font_h, size=32))
                try:
                    draw.text(
                        (64, text_size(liness[0], weather_font)[1] + 230 + 3),
                        text=liness[1],
                        font=ImageFont.truetype(font=font_h, size=32))
                except:
                    pass
                try:
                    draw.text(
                        (64,
                         text_size(liness[0], weather_font)[1] * 2 + 230 + 3),
                        text=liness[2],
                        font=ImageFont.truetype(font=font_h, size=32))
                except:
                    pass
            elif len(lines) > 1:
                draw.text((64, 245), text=lines[0], font=weather_font)
                draw.text((64, text_size(lines[0], weather_font)[1] + 245 + 5),
                          text=lines[1],
                          font=weather_font)
            else:
                draw.text((64, 253), text=lines[0], font=weather_font)

        im = Image.alpha_composite(im, txt)
        im.show()

        bio = BytesIO()
        bio.name = 'image.png'
        im.save(bio, 'png')
        bio.seek(0)

        return bio
Example #44
0
    async def casualstatscreate(self, data):
        font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf"
        bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf"
        name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8")
        header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8")
        operator = random.choice(self.bgs)

        bg_image = Image.open(
            f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA")

        profile_image = Image

        profile_avatar = BytesIO()
        profile_url = data.avatar_url_256
        async with self.session.get(profile_url) as r:
            profile_img = await r.content.read()
            profile_avatar = BytesIO(profile_img)

        profile_image = Image.open(profile_avatar).convert("RGBA")

        # set canvas
        bg_color = (255, 255, 255, 0)
        result = Image.new("RGBA", (1280, 1080), bg_color)
        process = Image.new("RGBA", (1280, 1080), bg_color)

        # draw
        draw = ImageDraw.Draw(process)

        # puts in background
        bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS)
        bg_image = bg_image.crop((0, 0, 1920, 1080))
        result.paste(bg_image, (0, 0))

        aviholder = self.add_corners(
            Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10)
        process.paste(aviholder, (995, 15), aviholder)
        process.paste(profile_image, (1000, 20))

        # data
        # draw.text((440, 40), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt)
        draw.text(
            (
                self._center(
                    440,
                    1000,
                    "Name: {}".format(self._truncate_text(data.username, 18)),
                    header_fnt,
                ),
                40,
            ),
            "Name: {}".format(self._truncate_text(data.username, 18)),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (
                self._center(440, 1000, "Platform: {}".format(
                    str(data.platform).title()), header_fnt),
                90,
            ),
            "Platform: {}".format(str(data.platform).title()),
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )
        draw.text(
            (self._center(440, 1000, "Alltime Ranked Statistics",
                          header_fnt), 140),
            "Alltime Casual Statistics",
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )

        draw.text(
            (self._center(1000, 1256, f"Level: {data.level}",
                          header_fnt), 300),
            f"Level: {data.level}",
            fill=(255, 255, 255, 255),
            font=header_fnt,
        )

        draw.text(
            (520, 400),
            "Games Played: {}".format(
                data.queue_stats["casual"]["games_played"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 480),
            "Wins: {}".format(data.queue_stats["casual"]["wins"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 480),
            "Losses: {}".format(data.queue_stats["casual"]["losses"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 560),
            "Draws: {}".format(data.queue_stats["casual"]["draws"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        try:
            wlr = (round(
                data.queue_stats["casual"]["wins"] /
                data.queue_stats["casual"]["games_played"],
                2,
            ) * 100)
        except ZeroDivisionError:
            wlr = 0
        draw.text((520, 640),
                  "Total W/LR: {}%".format(wlr),
                  fill=(255, 255, 255, 255),
                  font=name_fnt)

        draw.text(
            (520, 800),
            "Kills: {}".format(data.queue_stats["casual"]["kills"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (920, 800),
            "Deaths: {}".format(data.queue_stats["casual"]["deaths"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )
        draw.text(
            (520, 880),
            "KDR: {}".format(data.queue_stats["casual"]["kd"]),
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        m, _ = divmod(data.queue_stats["casual"]["playtime"], 60)
        h, m = divmod(m, 60)
        d, h = divmod(h, 24)
        draw.text(
            (520, 960),
            f"Playtime: {d:d}d {h:d}h {m:02d}m",
            fill=(255, 255, 255, 255),
            font=name_fnt,
        )

        result = Image.alpha_composite(result, process)
        file = BytesIO()
        result.save(file, "png")
        file.name = f"casual-{data.username}.png"
        file.seek(0)
        image = discord.File(file)
        return image
Example #45
0
    if os.path.isdir(os.path.join(config.EYES_DIR, dir)):
        eyes[dir] = []
        print(dir)
        for infile in glob.glob(os.path.join(config.EYES_DIR, dir, '*.tga')):
            eyes[dir].append(Image.open(infile).convert('RGBA'))
            if dir.islower():
                eyes['default'].append(Image.open(infile).convert('RGBA'))

print('Eyes OK')

#Create new flags
for key in flags:
    print("Creating %s flag." % key)
    #add eyes to image
    i = Image.alpha_composite(
        flags[key], eyes['default'][randint(0,
                                            len(eyes['default']) - 1)])
    #add shadow to image
    o = Image.alpha_composite(i, shw)
    print("Saving %s" % os.path.join(config.OUTPUT_DIR, key + ".tga"))
    #save image
    o.save(os.path.join(config.OUTPUT_DIR, key + ".tga"))

    #If culture filter is on check to see if it fits the criteria
    if config.use_culture:
        for filter in config.culture_filters:
            for ct in config.culture_filters[filter]:
                #Ignore rebels
                if key.isupper():
                    #Separate culture and culture groups
                    if ct.islower():
Example #46
0
    async def profile(self, ctx: aoi.AoiContext, member: discord.Member = None):
        member = member or ctx.author
        try:
            _, _, _, _, bg = await self.bot.db.get_badges_titles(member)
            if not bg:
                card_bg = self.default_bg.copy()
            else:
                _buf = io.BytesIO()
                async with aiohttp.ClientSession() as sess:
                    async with sess.get(bg) as resp:
                        resp.raise_for_status()
                        _buf.write(await resp.content.read())
                _buf.seek(0)
                card_bg = Im.open(_buf)
                card_bg = crop_max_square(card_bg)
                card_bg = card_bg.resize((512, 512))
        except Exception as error:  # noqa
            card_bg = self.default_bg.copy()
            traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
        card_bg = card_bg.convert("RGBA")
        await self.bot.db.ensure_xp_entry(member)
        global_xp = self.bot.db.global_xp[member.id]
        server_xp = self.bot.db.xp[ctx.guild.id][member.id]
        global_level, global_rem = _level(global_xp)
        server_level, server_rem = _level(server_xp)
        avatar_buf = io.BytesIO()
        await member.avatar.save(avatar_buf)
        avatar_buf.seek(0)
        img = self.background.copy()
        avatar_img = Im.open(avatar_buf)
        avatar_img = avatar_img.resize((128, 128))
        img_draw = Dw.Draw(img)
        img.paste(avatar_img, (32, 32))
        avatar_buf.close()

        # create overlays for the xp bars
        global_width = 330.66672 * global_rem / _xp_per_level(global_level + 1)
        global_xp_poly = (133.33328, 192), \
                         (133.33328 + global_width, 192), \
                         (117.33328 + global_width, 240), \
                         (117.33328, 240)

        server_width = 330.66672 * server_rem / _xp_per_level(server_level + 1)
        server_xp_poly = (112, 256), \
                         (112 + server_width, 256), \
                         (96 + server_width, 304), \
                         (96, 304)
        overlay = Im.new("RGBA", img.size, (0, 0, 0, 0))
        Dw.Draw(overlay).polygon(global_xp_poly, fill=(0, 0, 0) + (120,))
        Dw.Draw(overlay).polygon(server_xp_poly, fill=(0, 0, 0) + (120,))
        img = PIL.Image.alpha_composite(img, overlay)
        img_draw = Dw.Draw(img)

        # draw text
        await self.bot.db.ensure_user_entry(member)
        x, y, _, _, sz = _center_and_fit(454, 162, 190, 111, (await self.bot.db.get_titles(member))[0], 32, img_draw,
                                         w_pad=24)
        img_draw.text((x, y), (await self.bot.db.get_titles(member))[0], font=_font(sz))

        x, y, _, _, sz = _center_and_fit(217.6, 80, 480, 32, member.name, 32, img_draw,
                                         w_pad=24)
        img_draw.text((x, y), member.name, font=_font(sz))

        x, y, _, _, sz = _center_and_fit(115.8, 191, 480, 242,
                                         f"Level {global_level} - # {self._get_global_rank(member)}",
                                         32, img_draw, w_pad=24)
        img_draw.text((x, y), f"Level {global_level} - # {self._get_global_rank(member)}",
                      font=_font(sz))

        x, y, _, _, sz = _center_and_fit(95, 255, 459.2, 306,
                                         f"Level {server_level} - # {self._get_rank(member)}",
                                         32, img_draw, w_pad=24)
        img_draw.text((x, y), f"Level {server_level} - # {self._get_rank(member)}",
                      font=_font(sz))

        x, y, _, _, sz = _center_and_fit(115.8, 319, 257.5, 370,
                                         f"{_cur_string(await self.bot.db.get_global_currency(member))}",
                                         32, img_draw, w_pad=24)
        img_draw.text((x, y), f"{_cur_string(await self.bot.db.get_global_currency(member))}",
                      font=_font(sz))

        x, y, _, _, sz = _center_and_fit(94.5, 383, 236.2, 434,
                                         f"{_cur_string(await self.bot.db.get_guild_currency(member))}",
                                         32, img_draw, w_pad=24)
        img_draw.text((x, y), f"{_cur_string(await self.bot.db.get_guild_currency(member))}",
                      font=_font(sz))
        card_bg = card_bg.convert("RGBA")
        img = Im.alpha_composite(card_bg, img)
        buf = io.BytesIO()
        img.save(fp=buf, format="png")
        buf.seek(0)
        await ctx.send(file=(discord.File(buf, "profile.png")))
Example #47
0
def image_to_ascii_generator(request):
    """
    Generate ascii from image.
    :param request: Request with data.
    :return: JsonResponse in case of error or dictionary with "file_name", "num_cols", "brightness", "contrast" and "arts".
    """
    file_name = request.POST.get('file_name', None)
    num_cols = request.POST.get('num_cols', 90)
    brightness = request.POST.get('brightness', 100)
    contrast = request.POST.get('contrast', 100)

    # Validating user's input
    try:
        brightness = float(brightness) / 100
    except:
        brightness = 1.
    try:
        contrast = float(contrast) / 100
    except:
        contrast = 1.
    try:
        num_cols = int(num_cols)
    except:
        num_cols = 90
    # if we are in DEBUG = False, restrict num_cols to desired number
    NUM_COLS_MAX = 300
    if not settings.DEBUG and num_cols > NUM_COLS_MAX:
        num_cols = NUM_COLS_MAX
    img = request.FILES.get('img', None)

    # CACHING
    if file_name:
        cache_key = '_'.join((
            'image_to_ascii_generator',
            str(file_name),
            str(num_cols),
            str(brightness),
            str(contrast),
        ))
        response = cache.get(cache_key)
        if response:
            return response
    else:
        cache_key = None

    if file_name is not None:  # If we are already having image saved - just need to re-generate arts
        path = os.path.join(settings.TEMPORARY_IMAGES, file_name)
        if not os.path.exists(path):
            path = os.path.join(settings.MEDIA_ROOT, file_name)
            if not os.path.exists(path):
                return JsonResponse(
                    {
                        'error':
                        'This image file does not exist or it was deleted from the server.'
                    },
                    status=410)
    elif img is not None:  # If we are uploading new image
        # Getting extension of image
        unused_fn, file_extension = os.path.splitext(img.name)

        # If .bmp or .gif uploaded, convert it to .png
        converted_to_png = False
        if file_extension in '.bmp .gif':
            file_extension = '.png'
            converted_to_png = True

        # Generating unique full path to image (None if many recursions for some reason)
        path, file_name = _generate_unique_image_path(file_extension)
        if path is None:
            return JsonResponse({}, status=400)

        #  Trying to open user's image (and convert it if needed)
        try:
            input_img = Image.open(img)
            if converted_to_png:
                if file_extension == '.bmp':
                    input_img = input_img.convert('RGB')
                elif file_extension == '.gif':
                    input_img = input_img.convert("RGBA")
                    bg = Image.new("RGBA", input_img.size)
                    input_img = Image.composite(input_img, bg, input_img)
        except Exception as error:
            # print(error)
            return JsonResponse({'error': error.args}, status=400)

        # Saving image to defined path with some compression and removing transparency from png
        if file_extension == '.png':
            try:
                image = input_img.convert('RGBA')
                background = Image.new('RGBA', image.size, (255, 255, 255))
                image = Image.alpha_composite(background, image)
            except:
                image = input_img
        else:
            image = input_img
        if image.height > 1000 or image.width > 1000:
            image.thumbnail((1000, 1000), Image.ANTIALIAS)
        image.save(path, optimize=True, quality=95)
    else:
        return JsonResponse({}, status=400)

    # Calculating optimal num_cols for small images
    num_cols = _calculate_num_cols(path, num_cols)

    # Calling image_to_ascii generators in 2 threads, giving them full path to image and options
    args = [path]
    kwargs = {
        'num_cols': num_cols,
        'contrast': contrast,
        'brightness': brightness
    }

    # ---- Thread 1
    arts_1_list = [None, None]
    kwargs1 = {'mode': 'simple'}
    kwargs2 = {'mode': 'bars'}
    arts_1_thread = threading.Thread(target=_generator_thread_1_hub,
                                     daemon=True,
                                     args=(arts_1_list, args, kwargs, kwargs1,
                                           kwargs2))
    arts_1_thread.start()

    # ---- Thread 2
    arts_2_list = [None, None]
    arts_2_thread = threading.Thread(target=_generator_thread_2_hub,
                                     daemon=True,
                                     args=(arts_2_list, args, kwargs))
    arts_2_thread.start()

    # Converting some options back to percentage
    brightness = int(brightness * 100)
    contrast = int(contrast * 100)

    # ---- Wait Wait for threads to join here
    arts_1_thread.join()
    arts_2_thread.join()

    response = {
        'file_name': file_name,
        'num_cols': num_cols,
        'brightness': brightness,
        'contrast': contrast,
        'arts': [*arts_1_list, *arts_2_list]
    }

    # CACHING
    if cache_key:
        cache.set(cache_key, response, settings.CACHE_TIMEOUT_SHORT)

    return response
Example #48
0
background_image = background_image.convert("RGBA")
image = Image.new("RGBA", background_image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
txt1_size = draw.textsize(txt1, font=font)
txt2_size = draw.textsize(txt2, font=font)
draw.text((5, int(image.height - txt1_size[1] - 5)),
          txt1,
          font=font,
          fill=(255, 165, 0, 255))
draw.text((int(image.width - txt2_size[0] - 10),
           int(image.height - txt2_size[1] - 5)),
          txt2,
          font=font,
          fill=(255, 165, 0, 255))

if len(sys.argv) > 3:
    #paste the other stuff onto the thing.
    logo = Image.open(sys.argv[2])
    logo.load()
    phase = Image.open(sys.argv[3])
    phase.load
    image.paste(logo, ((int(image.width / 2) - int(logo.width / 2), 18)))
    image.paste(phase, ((int(image.width / 2) - int(phase.width / 2)),
                        int(image.height - phase.height - 30)))
    outfile_name = sys.argv[4]
else:
    outfile_name = sys.argv[2]

image = Image.alpha_composite(background_image, image)
image.save(outfile_name)
Example #49
0
def waterMarkImages(imageFile,
                    imageOutputPath,
                    text,
                    fontName="Bangers",
                    size="M",
                    opacity=255,
                    position="BR"):
    # TODO : Try to have color as an argument as well
    """
    Watermarks your images based on whatever arguments you've provided.

        Args:
            imageFile(str): Name of the image file
            imageOutputPath(str): Specify the output folder, not the name
            fontName(str): Put the path of the font of your choice,
                            or one of those available
            size(str): Size must be in XS, S, M, L, XL, XXL
            opacity(int): Opacity must be between 0 and 255 (inclusive)
            position(str): Position must be in BR, BL, TR, TL

        Returns:
            str - Filename of your output file

    """
    fileName = imageFile.split(os.path.sep)[-1]
    try:
        photo = Image.open(imageFile).convert("RGBA")
    except IOError:
        raise WatermarkException(4, val=imageFile)

    width, height = photo.size

    COLOR = (255, 255, 255)

    textImage = Image.new('RGBA', (width, height), COLOR + (0, ))

    fontsize = _setSize(width, height, size)

    drawing = ImageDraw.Draw(textImage)

    if fontName in FONT_MAP:
        # * fontPath = "PyWaterMark\\fonts\\" + FONT_MAP[fontName] - ONLY DEVS
        fontPath = pkg_resources.resource_filename(
            'PyWatermark', 'fonts/' + FONT_MAP[fontName])
        if not os.path.isfile(fontPath):
            raise WatermarkException(2, val=fontName)
    else:
        if not os.path.isfile(fontName):
            raise WatermarkException(3, val=fontName)

    font = ImageFont.truetype(fontPath, fontsize)

    textWidth, textHeight = drawing.textsize(text, font)

    pos = _setPosition(width, height, textWidth, textHeight, position)

    drawing.text(pos, text, fill=COLOR + (opacity, ), font=font)

    combined = Image.alpha_composite(photo, textImage)

    filenameSave = fileName.split('.')
    filenameSave[1] = 'wm.png'
    filenameSave = ''.join(filenameSave)
    # * Why you can't store JPEG images with transparency
    # * https://stackoverflow.com/questions/41413956/pil-unable-to-change-the-transparency-level-for-jpeg-image
    combined.save(imageOutputPath + '\\' + filenameSave)

    return filenameSave
Example #50
0
def paste_alpha(background, foreground):
    return Image.alpha_composite(background, foreground)
Example #51
0
def render_map(directory, data_directory, input_):
    try:
        i = input_['i']
        length = input_['length']
        eclipse_path_data = input_['eclipse_path_data']
        movie_frame = input_['movie_frame']
        poly = input_['poly']
        poly_dt = input_['poly_dt']
        path = input_['path']
        path_data = input_['path_data']


        # point = path.center_line.interpolate(bin_value, normalized=True)
        # bin_lat, bin_lon = point.x, point.y

        dpi = 300
        width = 321
        height = 204
        scaled_width = width / float(dpi)
        scaled_height = height / float(dpi)
        fig = plt.figure(dpi=dpi, figsize=(scaled_width, scaled_height))
        map = Basemap(
            llcrnrlon=-119.5, llcrnrlat=24.5,
            urcrnrlon=-66, urcrnrlat=47,
            projection='lcc',
            lat_1=33, lat_2=45,
            lat_0=39.828, lon_0=-98.579)
        base_color = 'white'
        border_color = 'black'
        boundary_color = 'none'
        map.drawmapboundary(color=boundary_color)
        # map.plot(path_data[1], path_data[0], color='green', marker='.', markersize=0.0001, latlon=True, zorder=1)
        ax = fig.gca()
        if movie_frame is not None:
            photo_lat = movie_frame[1]
            photo_lon = movie_frame[2]
            draw_photo_pin(data_directory, ax, map, photo_lon, photo_lat)
        draw_eclipse_umbra(ax, map, poly)

        fig.subplots_adjust(bottom=0, left=0, right=1, top=1, wspace=0, hspace=0)
        plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0)
        # plt.show()
        fname = os.path.join(directory, "marker.%05d.png" % i)
        fig.savefig(fname, dpi=dpi, transparent=True)
        plt.close(fig)

        map_fname = os.path.join(data_directory, "Grey_map_withline.png")
        im1 = Image.open(map_fname)
        im2 = Image.open(fname)

        a = 1
        b = 0
        c = +7 #left/right (i.e. 5/-5)
        d = 0
        e = 1
        f = -7 #up/down (i.e. 5/-5)
        im2_tx = im2.transform(im2.size, Image.AFFINE, (a, b, c, d, e, f))

        comp = Image.alpha_composite(im1, im2_tx)
        fname = os.path.join(directory, "map.%05d.png" % i)
        comp.save(fname)

    except Exception as e:
        print "exception in render_map on", i
        traceback.print_exc(limit=50)
Example #52
0
def makecomposite(ts, destdir):
    date = ts[:8]
    time = ts[8:12]

    # Put the tiles into a canvas, overlay the map, filet to HD size, then adorn w/ timestamp & logos
    compositedir = "%s/%s/%s" % (rootdir, "composite", date)
    compositefn = "%s/%s_%s_%s_%s.png" % (compositedir, prefix, urldir, region,
                                          ts)

    hdtvdir = "%s/%s/%s" % (rootdir, "hdtv", date)
    if reprocess:
        hdtvdir = "%s/%s/%s" % (rootdir, "reprocess", date)
    hdfn = "%s/%s_%s_%s_%s.png" % (hdtvdir, prefix, urldir, region, ts)

    if os.path.isfile(compositefn) and os.path.isfile(hdfn) and not force:
        logging.info("Composites Exist: %s %s" % (date, time))
        return

    if composite and not os.path.exists(compositedir):
        os.makedirs(compositedir)
    if hdtv and not os.path.exists(hdtvdir):
        os.makedirs(hdtvdir)

    logging.debug("Reading tiles: %s %s" % (date, time))
    base = Image.new('RGBA', (htiles * tilesize, vtiles * tilesize))
    for i in range(0, vtiles):
        for j in range(0, htiles):
            try:
                tile = Image.open(
                    "%s/%03d_%03d.png" %
                    (destdir, i + voffset, j + hoffset)).convert('RGBA')
            except:
                logging.warning("Couldn't open %s/%03d_%03d.png" %
                                (destdir, i + voffset, j + hoffset))
                return
            base.paste(tile, (j * tilesize, i * tilesize))

    # make the map overlay if all map tiles exist
    logging.debug("Reading map: %s %s" % (date, time))
    try:
        fetchmap()
        overlay = Image.new('RGBA', (htiles * tilesize, vtiles * tilesize))
        for i in range(0, vtiles):
            for j in range(0, htiles):
                tile = Image.open(
                    "%s/%03d_%03d.png" %
                    (mapdir, i + voffset, j + hoffset)).convert('RGBA')
                overlay.paste(tile, (j * tilesize, i * tilesize))
        base = Image.alpha_composite(base, overlay)
    except:
        logging.warning("fetchmap failed")
        # pass # catch if fetchmap() fails

    if composite and not os.path.isfile(compositefn):
        logging.info("Composite created: %s" % (compositefn))
        base.save(compositefn)

    if hdtv:
        # Crop to (w x h) @ upper corner (x, y)
        # Base image is 2712x2034
        # Crop to 16x9 aspect ratio - step is 48x27,(96x54), (192x108), (240x135)
        # Sizes might be 2400x1350, 2640x1485, 2688x1512
        if goes == "16":  # Eastern CONUS, not for hurricanes
            x = 150
            y = 200
            w = 2400
            h = 1350
        if goes == "17":  # Eastern Pacific to watch snow & Hawaii sailing wx
            x = 24
            y = 180
            w = 2688
            h = 1512
        crop = base.crop((x, y, x + w, y + h))
        # crop.load()
        hdcanvas = crop.resize((1920, 1080), Image.LANCZOS)

        year = ts[0:4]
        month = ts[4:6]
        day = ts[6:8]
        hour = ts[8:10]
        minute = ts[10:12]

        cfont = ImageFont.truetype("lucon.ttf",
                                   24)  # lucida console - cour.ttf is ugly
        # getsize() returns for actual string, so figure out the greatest possible font height
        x, fheight = cfont.getsize(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[{]}\|;:',<.>/?"
        )
        tsstring = " GOES-%s %s-%s-%s %s:%sZ " % (goes, year, month, day, hour,
                                                  minute)
        x = 4
        y = 8
        ypad = 2
        w, h = cfont.getsize(tsstring)
        canvas = Image.new('RGBA', hdcanvas.size, (255, 255, 255, 0))
        draw = ImageDraw.Draw(canvas)
        draw.rectangle(
            (x, y, x + w, y + fheight + ypad + ypad),
            fill=(0, 0, 0, 0x80))  # Add some Y padding - X is padded w/ spaces
        draw.text((x, y + ypad),
                  tsstring,
                  fill=(0xff, 0xff, 0xff, 0xff),
                  font=cfont)
        # print ("x%d y%d w%d h%d ypad%d fheight%d" % (x, y, w, h, ypad, fheight))
        if goes == "17" and (int(year) < 2019) or ((int(year) == 2019) and
                                                   ((int(month) < 2) or
                                                    ((int(month) == 2) and
                                                     (int(day) < 12)))):
            wstring = " GOES-17 Preliminary, Non-Operational Data "
            w, h = cfont.getsize(wstring)
            x = hdcanvas.width - (w + x)
            draw.rectangle(
                (x, y, x + w, y + fheight + ypad + ypad),
                fill=(0, 0, 0,
                      0x80))  # Add some Y padding - X is padded w/ spaces
            draw.text((x, y + ypad),
                      wstring,
                      fill=(0xff, 0xff, 0xff, 0xff),
                      font=cfont)
            # print ("x%d y%d w%d h%d ypad%d fheight%d" % (x, y, w, h, ypad, fheight))

        logoheight = 96.0
        logospacing = 4
        logomargin = 8
        rammb1 = Image.open("rammb_logo.png")
        rammblogo = rammb1.resize(
            (int(rammb1.width *
                 (logoheight / rammb1.height)), int(logoheight)),
            Image.ANTIALIAS)
        x = hdcanvas.width - (rammblogo.width + logomargin)
        y = hdcanvas.height - (rammblogo.height + logomargin)
        # print("ciralogo %dx%d @ %d, %d" % (rammblogo.width, rammblogo.height, x, y))
        hdcanvas.paste(rammblogo, (x, y), rammblogo)

        cira1 = Image.open("cira18Logo.png")
        ciralogo = cira1.resize(
            (int(cira1.width * (logoheight / cira1.height)), int(logoheight)),
            Image.ANTIALIAS)
        x = x - (ciralogo.width + logospacing)
        y = hdcanvas.height - (ciralogo.height + logomargin)
        # print("ciralogo %dx%d @ %d, %d" % (ciralogo.width, ciralogo.height, x, y))
        hdcanvas.paste(ciralogo, (x, y), ciralogo)

        if goes == "16":
            l1 = Image.open("goesRDecalSmall.png")
        if goes == "17":
            l1 = Image.open("GOES-S-Mission-Logo-1024x655.png")
        goeslogo = l1.resize(
            (int(l1.width * (logoheight / l1.height)), int(logoheight)),
            Image.ANTIALIAS)
        x = x - (goeslogo.width + logospacing)
        y = hdcanvas.height - (goeslogo.height + logomargin)
        # print("goeslogo %dx%d @ %d, %d" % (goeslogo.width, goeslogo.height, x, y))
        hdcanvas.paste(goeslogo, (x, y), goeslogo)

        # afont = ImageFont.truetype("times.ttf", 24)
        text = " Image Credits "
        w, h = cfont.getsize(text)
        x = hdcanvas.width - (w + logomargin)
        y = hdcanvas.height - (logoheight + h + logomargin + logospacing +
                               ypad + ypad)
        # print("image credit %dx%d @ %d, %d" % (w, h, x, y))
        draw.rectangle((x, y, x + w, y + h), fill=(0, 0, 0, 0x80))
        draw.text((x, y + ypad), text, fill=(255, 255, 255, 255), font=cfont)
        hdcanvas = Image.alpha_composite(hdcanvas, canvas)
        del draw

        hdcanvas.save(hdfn)
        logging.info("HD created: %s" % (hdfn))

    logging.info("rm %s" % (destdir))
    shutil.rmtree(destdir)
Example #53
0
         kp, des = sift.detectAndCompute(gray,None)
         temptest, classified_pointstest, meanstest=cv2.kmeans(data=des,K=k_num,bestLabels=None,criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1000, 0.001),attempts=10,flags=cv2.KMEANS_RANDOM_CENTERS)
         meanstest=meanstest.reshape(-1)
         test_set.append(meanstest)
         test_labels.append(1)
         testdata=np.float32(test_set)
         responses=np.float32(test_labels)
         font=cv2.FONT_HERSHEY_SIMPLEX
         im = Image.open("E:\\python\\imagecat\\"+str(i)+".jpg").convert('RGBA')
         im=im.resize((250,250))
         txt=Image.new('RGBA', im.size, (0,0,0,0))
         fnt=ImageFont.truetype("c:/Windows/fonts/Tahoma.ttf", 20)
         d=ImageDraw.Draw(txt)
         d.text((txt.size[0]-240,txt.size[1]-60), "true label:1",font=fnt, fill=(0,255,0,255))
         #d.text((txt.size[0]-120,txt.size[1]-60), "test label:1",font=fnt, fill=(255,0,0,255))
         out=Image.alpha_composite(im, txt)
         #out.show()
         temppath="E:\\python\\testsetdk\\"+"Knum_"+str(k_num)+"i_"+str(testdata.shape[0])+".jpg"
         out.save(temppath)
         Paths.append(temppath)
     except BaseException as error:
         print("error")
         continue
 for i in xrange(10):
     try:
         img=cv2.imread("E:\\python\\imagemaltese\\"+str(i)+".jpg")
         res=cv2.resize(img,(250,250))
         gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
         sift = cv2.SIFT()
         kp, des = sift.detectAndCompute(gray,None)
         temptest, classified_pointstest, meanstest=cv2.kmeans(data=des,K=k_num,bestLabels=None,criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1000, 0.001),attempts=10,flags=cv2.KMEANS_RANDOM_CENTERS)
    portraits = get_portraits_img(card_file)
    if portraits is None:
        # This can happen since JP gets ahead of NA and it's not easy to
        # confirm that a card is in JP but not NA
        print('skipping {} because CARDS file does not exist: {}'.format(
            card_id, card_file))
        continue

    card_img = get_card_img(portraits, row, col)
    if is_entirely_transparent(card_img):
        print('skipping {} because it is missing'.format(card_id))
        continue

    # Create a grey image to overlay the portrait on, filling in the background
    grey_img = Image.new("RGBA", card_img.size, color=(68, 68, 68, 255))
    card_img = Image.alpha_composite(grey_img, card_img)

    attr_img = attr_imgs[card_attr]

    # Adjust the card image to fit the portrait
    new_card_img = Image.new("RGBA", attr_img.size)
    new_card_img.paste(card_img, (2, 2))

    # Merge the attribute border on to the portrait
    merged_img = Image.alpha_composite(new_card_img, attr_img)

    if card_sattr:
        sattr_img = sattr_imgs[card_sattr]
        # Adjust the subattribute image to the attribute image size
        new_sattr_img = Image.new("RGBA", attr_img.size)
        # There's a slight offset needed for the subattribute border
Example #55
0
class PixCache(object):
    def __init__(self):
        self._data = {}

    def get_pix(self, filename, size=None):
        if filename is None:
            return None
        mimetype = mimetypes.guess_type(filename)[0]
        if mimetype is None or not mimetype.startswith("image/"):
            return None

        if filename not in self._data:
            self._data[filename] = {}
        if size in self._data[filename]:
            pix = self._data[filename][size]
        else:
            try:
                h = hashlib.sha1(('%f%s' % (os.path.getmtime(filename),
                                            filename)).encode()).hexdigest()
                tmp_cache_path = GLib.get_user_cache_dir() + '/cs_backgrounds/'
                if not os.path.exists(tmp_cache_path):
                    os.mkdir(tmp_cache_path)
                cache_filename = tmp_cache_path + h + "v2"

                if os.path.exists(cache_filename):
                    # load from disk cache
                    try:
                        with open(cache_filename, "r") as cache_file:
                            pix = pickle.load(cache_file)
                        tmp_img = Image.open(BytesIO(pix[0]))
                        pix[0] = self._image_to_pixbuf(tmp_img)
                    except Exception, detail:
                        print "Failed to load cache file: %s: %s" % (
                            cache_filename, detail)
                        pix = None

                else:
                    if mimetype == "image/svg+xml":
                        # rasterize svg with Gdk-Pixbuf and convert to PIL Image
                        tmp_pix = GdkPixbuf.Pixbuf.new_from_file(filename)
                        mode = "RGBA" if tmp_pix.props.has_alpha else "RGB"
                        img = Image.frombytes(
                            mode, (tmp_pix.props.width, tmp_pix.props.height),
                            tmp_pix.read_pixel_bytes().get_data(), "raw", mode,
                            tmp_pix.props.rowstride)
                    else:
                        img = Image.open(filename)
                        img = apply_orientation(img)

                    # generate thumbnail
                    (width, height) = img.size
                    if img.mode != "RGB":
                        if img.mode == "RGBA":
                            bg_img = Image.new("RGBA", img.size,
                                               (255, 255, 255, 255))
                            img = Image.alpha_composite(bg_img, img)
                        img = img.convert("RGB")
                    if size:
                        img.thumbnail((size, size), Image.ANTIALIAS)
                    img = imtools.round_image(img, {}, False, None, 3, 255)
                    img = imtools.drop_shadow(img,
                                              4,
                                              4,
                                              background_color=(255, 255, 255,
                                                                0),
                                              shadow_color=0x444444,
                                              border=8,
                                              shadow_blur=3,
                                              force_background_color=False,
                                              cache=None)

                    # save to disk cache
                    try:
                        png_bytes = BytesIO()
                        img.save(png_bytes, "png")
                        with open(cache_filename, "w") as cache_file:
                            pickle.dump([png_bytes.getvalue(), width, height],
                                        cache_file, 2)
                    except Exception, detail:
                        print "Failed to save cache file: %s: %s" % (
                            cache_filename, detail)
Example #56
0
    def draw_page(self):
        # get an image
        dir_path = os.path.dirname(os.path.abspath(__file__))
        img_path = dir_path + '/assets/stats_h_page.png'
        if self.dt_range == 'hour':
            img_path = dir_path + '/assets/stats_h_page.png'
        elif self.dt_range == 'day':
            img_path = dir_path + '/assets/stats_d_page.png'
        elif self.dt_range == 'week':
            img_path = dir_path + '/assets/stats_w_page.png'
        elif self.dt_range == 'month':
            img_path = dir_path + '/assets/stats_m_page.png'
        elif self.dt_range == 'year':
            img_path = dir_path + '/assets/stats_y_page.png'
        base = Image.open(img_path).convert('RGBA')
        fff = Image.new(base.mode, base.size, (255,) * 4)
        img = Image.composite(base, fff, base)

        # make a blank image for the text, initialized as transparent
        txt = Image.new('RGBA', base.size, (255, 255, 255, 0))

        # get a font
        font_path = dir_path + '/assets/HaxM-10.pil'
        font10 = ImageFont.load(font_path)
        font_path = dir_path + '/assets/HaxM-13.pil'
        font20 = ImageFont.load(font_path)
        # get a drawing context
        d = ImageDraw.Draw(txt)

        # draw text, full opacity
        fname = '/var/www/connectbox/connectbox_default/stats.top10.json'
        if os.path.isfile(fname):
            # file exists continue
            with open(fname) as json_file:
                data = json.load(json_file)
                y = 0
                count = 0

                if self.page_num == 1:
                    d.text((107, 22), 'p1', font=font20, fill="black")
                else:
                    d.text((107, 22), 'p2', font=font20, fill="black")

                # check to see if we have data or not
                for p in data[self.dt_range]:
                    if 'resource' in p.keys():
                        # cover up the unhappy face
                        d.rectangle((25, 1, 75, 128), fill="white")

                for p in data[self.dt_range]:
                    media = p['resource'].rsplit('/', 1)[1]
                    if self.page_num == 1:
                        # trim out directories
                        d.text((2, y), '(%s) %s' %
                               (str(p['count']), media),
                               font=font10, fill="black")
                        y += 12
                        count += 1
                        if count == 5:
                            break
                    else:
                        # trim out directories
                        count += 1
                        if count > 5:
                            d.text((2, y), '(%s) %s' %
                                   (str(p['count']), media),
                                   font=font10, fill="black")
                            y += 12

        out = Image.alpha_composite(img, txt)
        self.device.display(out.convert(self.device.mode))
        self.device.show()
Example #57
0
        lst_atypical = [a[1:] for a in lst_atypical]
        bg_atyp = random.choice(lst_atypical)

        usepath = os.path.join(
            '/media/noor/DataNS/Imagesets/SUN/SUN2012/SUN2012', bg_atyp)
        for bg_im in os.listdir(
                os.path.join(
                    '/media/noor/DataNS/Imagesets/SUN/SUN2012/SUN2012',
                    bg_atyp)):
            background = Image.open(
                os.path.join(
                    '/media/noor/DataNS/Imagesets/SUN/SUN2012/SUN2012',
                    bg_atyp, bg_im))
            background2 = background.convert("RGBA")

            result = Image.alpha_composite(background2, ob)
            #print(image.split("/")[-1])

            if not os.path.exists(
                    os.path.join(
                        '/media/noor/DataNS/Imagesets/DNimal_I_background/humanstim/',
                        image.split("/")[-2],
                        image.split("/")[-1], 'a_background', 'loc3')):
                os.makedirs(
                    os.path.join(
                        '/media/noor/DataNS/Imagesets/DNimal_I_background/humanstim/',
                        image.split("/")[-2],
                        image.split("/")[-1], 'a_background', 'loc3'))

            newfilename = os.path.join(
                '/media/noor/DataNS/Imagesets/DNimal_I_background/humanstim/',
Example #58
0
def main(args):
    all_model_class = []
    all_model_ids = []

    with open(args.task_file, 'r') as f:
        lines = f.readlines()
        for line in lines:
            if line == '':
                continue

            tmp = line.rstrip('\n').split(' ')
            all_model_class.append(tmp[0])
            all_model_ids.append(tmp[1])

    for i, curr_model_id in enumerate(all_model_ids):
        start_time = time.time()
        rendering_curr_model_root = os.path.join(DIR_RENDERING_PATH,
                                                 all_model_class[i],
                                                 all_model_ids[i])
        rendering_curr_model_save_png_root = os.path.join(
            rendering_curr_model_root, 'rendering_png')
        if not os.path.exists(rendering_curr_model_save_png_root):
            os.mkdir(rendering_curr_model_save_png_root)

        if os.path.exists(
                os.path.join(rendering_curr_model_save_png_root,
                             '%.2d_rgb.png' % (N_VIEWS - 1))):
            continue

        rf = open(
            os.path.join(rendering_curr_model_root, 'rendering_metadata.txt'),
            'r')
        f = open(
            os.path.join(rendering_curr_model_save_png_root,
                         'depth_range.txt'), 'w')
        for view_id in range(N_VIEWS):
            image_path = os.path.join(rendering_curr_model_root,
                                      'rendering_exr', '%.2d.exr' % view_id)

            try:
                x, y, img, depth, depth_min, depth_max = convert_OpenEXR_to_sRGB(
                    image_path)
            except:
                continue
            finally:
                pass

            img = (img * 255.0).astype(numpy.uint8)
            img = Image.fromarray(img)
            img.save(
                os.path.join(rendering_curr_model_save_png_root,
                             '%.2d_rgba.png' % view_id))

            depth = (depth * 255.).astype(numpy.uint8)
            depth = Image.fromarray(depth)
            depth = depth.convert('L')
            # save depth map & range
            depth.save(
                os.path.join(rendering_curr_model_save_png_root,
                             '%.2d_depth.png' % view_id))

            depth_unit = RENDERING_MAX_CAMERA_DIST * float(
                rf.readline().split(' ')[3])
            print(depth_min, depth_max, depth_unit, file=f)

            # convert to jpg, save jpg
            background = Image.new('RGBA', (x, y), (255, 255, 255, 255))
            img_rgb = Image.alpha_composite(background, img)
            img_rgb.convert('RGB').save(
                os.path.join(rendering_curr_model_save_png_root,
                             '%.2d_rgb.png' % view_id))
            #print('depth min:', depth_min, ',max:', depth_max)

        f.close()
        rf.close()
        end_time = time.time()
        print('transfer model in', end_time - start_time, ' secs')
d.text((1100, 460), PAQ, font=fnt50, fill=(0, 0, 0, 180))

linea1 = "________________________________"
linea11 = "_____________________________"
linea2 = "_________________________________________________________"

###LINEAS
d.text((300, 80), linea2, font=fnt50, fill=(0, 0, 0, 220))
d.text((1100, 155), linea1, font=fnt50, fill=(0, 0, 0, 220))
d.text((1100, 225), linea1, font=fnt50, fill=(0, 0, 0, 220))
d.text((1100, 400), linea1, font=fnt50, fill=(0, 0, 0, 220))
d.text((1100, 400), linea1, font=fnt50, fill=(0, 0, 0, 220))
d.text((150, 560), linea11, font=fnt50, fill=(0, 0, 0, 220))
d.text((270, 560), linea11, font=fnt50, fill=(0, 0, 0, 220))

out = Image.alpha_composite(base, txt)

out.save('nommm.png')

img = Image.open('nommm.png')

# open an image file (.bmp,.png,.png,.gif) you have in the working folder

nuevoAncho = 2980

nuevoAlto = 4200

nImg = img.resize((nuevoAncho, nuevoAlto))

# Guarda la imagen
nImg.save('nommmsss.png')
def mouth_display_png(image_absolute_path, threshold=70,
                      invert=False, x=0, y=0):
    """Converts a png image into the appropriate encoding for the
        Arduino Mark I enclosure.

        NOTE: extract this out of api.py when re structuing the
              enclosure folder

        Args:
            image_absolute_path (string): The absolute path of the image
            threshold (int): The value ranges from 0 to 255. The pixel will
                             draw on the faceplate it the value is below a
                             threshold
            invert (bool): inverts the image being drawn.
            x (int): x offset for image
            y (int): y offset for image
        """
    # to understand how this funtion works you need to understand how the
    # Mark I arduino proprietary encoding works to display to the faceplate
    img = Image.open(image_absolute_path).convert("RGBA")
    img2 = Image.new('RGBA', img.size, (255, 255, 255))
    width = img.size[0]
    height = img.size[1]

    # strips out alpha value and blends it with the RGB values
    img = Image.alpha_composite(img2, img)
    img = img.convert("L")

    # crop image to only allow a max width of 16
    if width > 32:
        img = img.crop((0, 0, 32, height))
        width = img.size[0]
        height = img.size[1]

    # crop the image to limit the max height of 8
    if height > 8:
        img = img.crop((0, 0, width, 8))
        width = img.size[0]
        height = img.size[1]

    encode = ""

    # Each char value represents a width number starting with B=1
    # then increment 1 for the next. ie C=2
    width_codes = ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                   'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                   'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a']

    height_codes = ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

    encode += width_codes[width - 1]
    encode += height_codes[height - 1]

    # Turn the image pixels into binary values 1's and 0's
    # the Mark I face plate encoding uses binary values to
    # binary_values returns a list of 1's and 0s'. ie ['1', '1', '0', ...]
    binary_values = []
    for i in range(width):
        for j in range(height):
            if img.getpixel((i, j)) < threshold:
                if invert is False:
                    binary_values.append('1')
                else:
                    binary_values.append('0')
            else:
                if invert is False:
                    binary_values.append('0')
                else:
                    binary_values.append('1')

    # these values are used to determine how binary values
    # needs to be grouped together
    number_of_top_pixel = 0
    number_of_bottom_pixel = 0

    if height > 4:
        number_of_top_pixel = 4
        number_of_bottom_pixel = height - 4
    else:
        number_of_top_pixel = height

    # this loop will group together the individual binary values
    # ie. binary_list = ['1111', '001', '0101', '100']
    binary_list = []
    binary_code = ''
    increment = 0
    alternate = False
    for val in binary_values:
        binary_code += val
        increment += 1
        if increment == number_of_top_pixel and alternate is False:
            # binary code is reversed for encoding
            binary_list.append(binary_code[::-1])
            increment = 0
            binary_code = ''
            alternate = True
        elif increment == number_of_bottom_pixel and alternate is True:
            binary_list.append(binary_code[::-1])
            increment = 0
            binary_code = ''
            alternate = False

    # Code to let the Makrk I arduino know where to place the
    # pixels on the faceplate
    pixel_codes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                   'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']

    for binary_values in binary_list:
        number = int(binary_values, 2)
        pixel_code = pixel_codes[number]
        encode += pixel_code

    return encode