Пример #1
0
def makeCardImage(name, rules):
    img = Image.new('RGB', (500, 726), color='white')

    rulesf = textwrap.fill(rules, 40)  #wrap that text bb

    d = ImageDraw.Draw(img)
    d.text((20, 20), name, fill=(0, 0, 0), font=titleF)
    d.text((20, 500), rulesf, fill=(0, 0, 0), font=rulesF)

    file = filize(name, 'png')
    img.save(file)

    return file
Пример #2
0
 def runTest(self):
     symbology = self.conf.symbology
     img_prefix = join(IMG_ROOT, symbology)
     for args in self.conf.cases:
         img_filename, codestring = args[:2]
         options = args[2] if len(args)>2 else {}
         render_options = dict((args[3] if len(args)>3 else {}), scale=2.0)
         generated = barcode(symbology, codestring, options, **render_options).convert('L')
         loaded = Image.open(join(img_prefix, img_filename)).convert('L')
         diff = None
         try:
             # image size comparison
             self.assertEqual(generated.size, loaded.size)
             # pixel-wize comparison
             diff = ImageChops.difference(generated, loaded)
             diff_bbox = diff.getbbox()
             self.assertIsNone(diff_bbox)
         except AssertionError as exc:
             # generate and show diagnostics image
             if diff:
                 # if diff exists, generate 3-row diagnostics image
                 lw, lh = loaded.size
                 gw, gh = generated.size
                 diag = Image.new('L', (max(lw, gw), (lh+gh+max(lh, gh))))
                 diag.paste(loaded, (0, 0, lw, lh))
                 diag.paste(generated, (0, lh, gw, lh+gh))
                 diag.paste(diff, (0, lh+gh, max(lw, gw), (lh+gh+max(lh, gh))))
             else:
                 # else, just write generated image
                 diag = generated
             sio_img = StringIO()
             diag.convert('L').save(sio_img, 'PNG')
             # reopen sio_img
             sio_img = StringIO(sio_img.getvalue())
             sio_uu = StringIO()
             uuencode(sio_img, sio_uu, name='diag_%s' %img_filename)
             raise AssertionError(
                 'Image difference detected (%s)\n'
                 'uu of generated image:\n----\n%s----\n'
                 %(exc.args, sio_uu.getvalue()))
Пример #3
0
    def create(self, imlist, namelist, desclist=None):
        """ Main method to create the actual strip
        
        :param imlist: PIL images, ej: [[img1, img2],[img3, img4]]
        :type imlist: list of lists
        :param namelist: Names for the images. Must match imlist size
        :type namelist: list of lists
        :param desclist: Descriptions for the images. Must match imlist size
        :type desclist: list of lists
        :return:
        :rtype:
        """

        # SANITY CHECK
        err1 = "dimension of imlist must match dimension of namelist"
        err2 = "dimension of nested lists must be equal"

        if len(imlist) != len(namelist):
            raise ValueError(err1)
        elif [len(l) for l in imlist] != [len(l) for l in namelist]:
            raise ValueError(err2)

        if desclist is not None:
            if len(desclist) != len(imlist):
                raise ValueError(err1)
            elif [len(l) for l in imlist] != [len(l) for l in desclist]:
                raise ValueError(err2)

        def line_height(text, font):
            """ Calculate height for a multiline text
            
            :param text: multiline text
            :type text: str
            :param font: utilized font
            :type font: ImageFont
            :return: text height
            :rtype: float
            """
            lista = text.split("\n")
            alt = 0
            for linea in lista:
                alt += font.getsize(linea)[1]
            return alt + self.y_space

        # FUENTES
        font = ImageFont.truetype(self.font, self.body_size)
        fontit = ImageFont.truetype(self.font, self.title_size)
        font_desc = ImageFont.truetype(self.font, self.title_size - 4)

        # TITULO
        title = self.name
        title_height = line_height(title, fontit)
        
        # DIMENSIONES DESCRIPCION
        description = self.description.replace("_", "\n")
        desc_height = line_height(description, font_desc)
        desc_width = font_desc.getsize(description)[0]

        # ALTURA NOMBRES
        if desclist:
            all_names = [n.replace("_", "\n") for n in self.unpack(desclist)]
        else:
            all_names = [n.replace("_", "\n") for n in self.unpack(namelist)]

        all_height = [line_height(t, font) for t in all_names]
        name_height = max(*all_height) #+ 2
        # print alturatodos, alturanombres

        # CALCULO EL ANCHO DE LA PLANTILLA
        imgs_width = [[ii.size[0] + self.x_space for ii in i] for i in imlist]
        imgs_width_sum = [sum(i) for i in imgs_width]

        # CALCULO EL MAXIMO ANCHO DE LA LISTA DE ANCHOS
        max_width = max(imgs_width_sum)
        strip_width = int(max_width)

        # CALCULO EL ALTO MAX

        # POR AHORA LO CALCULA CON EL ALTO DE LA 1ER COLUMNA
        # PERO SE PODRIA CALCULAR CUAL ES LA IMG MAS ALTA Y CUAL
        # ES EL TITULO MAS ALTO, Y COMBINAR AMBOS...

        # Tener en cuenta que listaimgs es una lista de listas [[i1,i2], [i3,i4]]

        # print "calculando general_height de la plantilla..."

        imgs_height = [[ii.size[1] for ii in i] for i in imlist]
        max_imgs_height = [max(*i) + name_height + self.y_space for i in imgs_height]
        max_height = sum(max_imgs_height)

        strip_height = int(sum((title_height, desc_height, max_height,
                                    self.y_space * 3)))

        strip = ImPIL.new("RGB", (strip_width, strip_height),
                              self.background_color)

        draw = ImageDraw.Draw(strip)

        # DIBUJA LOS ELEMENTOS DENTRO DE LA PLANTILLA

        # COORD INICIALES
        x = 0
        y = 0

        # DIBUJA EL TITULO
        draw.text((x, y), title, font=fontit, fill=self.title_color)

        # DIBUJA LA DESCRIPCION
        y += title_height + self.y_space # aumento y
        # print "y de la descripcion:", y
        draw.text((x, y), description, font=font_desc, fill=self.title_color)

        # DIBUJA LAS FILAS

        # logging.debug(("altura de la descripcion (calculada):", desc_height))
        # logging.debug(("altura de la desc", font_desc.getsize(description)[1]))
        y += desc_height + self.y_space # aumento y

        # DIBUJA LAS FILAS Y COLUMNAS

        if desclist:
            namelist = desclist

        for i, n, alto in zip(imlist, namelist, max_imgs_height):
            # RESETEO LA POSICION HORIZONTAL
            xn = x # hago esto porque en cada iteracion aumento solo xn y desp vuelvo a x
            for image, name in zip(i, n):
                # LA COLUMNA ES: (imagen, name, anchocolumna)
                # print image, name

                ancho_i, alto_i = image.size

                # DIBUJO imagen
                strip.paste(image, (xn, y))

                # aumento y para pegar el texto
                _y = y + alto_i + self.y_space

                # DIBUJO name
                draw.text((xn, _y),
                          name.replace("_", "\n"),
                          font=font,
                          fill=self.body_color)

                # AUMENTO y
                xn += ancho_i + self.x_space

            # AUMENTO x
            y += alto

        strip.save(self.name + "." + self.ext)
        strip.show()

        return strip
Пример #4
0
def rgb_conv(i):
    color = 255 * array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5))
    return tuple(color.astype(int))


# function defining a mandelbrot
def mandelbrot(x, y):
    c0 = complex(x, y)
    c = 0
    for i in range(1, 1000):
        if abs(c) > 2:
            return rgb_conv(i)
        c = c * c + c0
    return (0, 0, 0)


# creating the new image in RGB mode
img = Image.new('RGB', (WIDTH, int(WIDTH / 2)))
pixels = img.load()

for x in range(img.size[0]):

    # displaying the progress as percentage
    print("%.2f %%" % (x / WIDTH * 100.0))
    for y in range(img.size[1]):
        pixels[x, y] = mandelbrot((x - (0.75 * WIDTH)) / (WIDTH / 4),
                                  (y - (WIDTH / 4)) / (WIDTH / 4))

    # to display the created fractal after
# completing the given number of iterations
img.show()
Пример #5
0
    x0 = x * mat[i][0] + y * mat[i][1] + mat[i][4] 
    y  = x * mat[i][2] + y * mat[i][3] + mat[i][5] 
    x = x0 
    #
    if x < xa:
        xa = x
    if x > xb:
        xb = x
    if y < ya:
        ya = y
    if y > yb:
        yb = y

# drawing
#imgy = round(imgy * (yb - ya) / (xb - xa)) # auto-re-adjust the aspect ratio 
image = Image.new("L", (imgx, imgy))

x=0.0
y=0.0 
for k in range(imgx * imgy):
    p=random.random()
    psum = 0.0
    for i in range(m):
        psum += mat[i][6]
        if p <= psum:
            break
    x0 = x * mat[i][0] + y * mat[i][1] + mat[i][4] 
    y  = x * mat[i][2] + y * mat[i][3] + mat[i][5] 
    x = x0 
    jx = int((x - xa) / (xb - xa) * (imgx - 1)) 
    jy = (imgy - 1) - int((y - ya) / (yb - ya) * (imgy - 1))