使用PIL从较小的图像选择中生成较大的图像会导致空白

时间:2019-02-01 05:03:05

标签: python python-3.x python-imaging-library

我正在制作一个实用程序,用于创建装满随机碎片的大型棋盘。使用PIL的粘贴功能创建大图像时,我总是会丢失一些图片。

如果板子是1x1,将没有图片;如果板子是2X2,则将带有两张上面的图片和一张左下图片,但没有右下图片。

看着我的代码,我意识到它正在尝试在前进到下一行之前将图像放置在每行背景的边界之外,但是如果我将其更改为仅上升到边界然后继续前进到下一行,图像的最右边一行将是黑色空格,这意味着我最终得到的图像要比当前编程时少一幅。

def create_set(name, quantity):
    print(datetime.datetime.now())
    pic_list = create_pieces(quantity)
    txt_name = name.split('.')[0]
    text_file = open(txt_name + '.txt', 'w+')
    text_file.write(str(datetime.datetime.now()) + ',   ')
    for i in range(len(pic_list)):
        if i > 0:
            text_file.write(',' + str(pic_list[i].split('.')[0]))
        else:
            text_file.write(str(pic_list[i].split('.')[0]))
    text_file.close()

    root = math.sqrt(quantity)

    background_dimension = int(root * 32)
    print(background_dimension)
    picture = Image.new('RGB',(background_dimension, background_dimension))
    offset = [0, 0]
    for i in range(0, len(pic_list), int(root)):
        # print(offset)
        images = [Image.open(j) for j in pic_list[i:i+int(root)]]

        for item in images:
            print(offset)
            # print(datetime.datetime.now())
            if offset[0] < background_dimension:
                picture.paste(item, (offset[0], offset[1]))
                offset[0] += 32
            else:
                offset[1] += 32
                offset[0] = 0
                picture.paste(item, (offset[0], offset[1]))

    picture.save(name)
    print(datetime.datetime.now())
    text_file = open(txt_name + '.txt', 'a')
    text_file.write(',   ' + str(datetime.datetime.now()))
    text_file.close

4x4 image with losing images past right bounds

2x2 image without losing images past right bounds

0 个答案:

没有答案