选择随机图像并进行水印PIL

时间:2020-09-27 16:05:28

标签: python python-imaging-library

我在文件夹中选择随机图像并且要使用PIL编辑时出错。

我的代码是

  this.httpClient
        .put(`articles/${article.id}`, article)
        
       .pipe(
            map(res => res.response),
            

                mergeMap(() =>       
                 this.articlesTagsAPI.someOtherMethod(updatedArticle.id, 
                           article.tags).pipe(
                                  map(() => {
                                     if(article.articleType === 'news'){
                                      return {
                                          ...updatedArticle,
                                          tags: article.tags
                                      };
                                     }else{ return of([])}
                                  })
                              )
                          )
                        
                )
            )
        );

并显示类似错误

回溯(最近通话最近): 在第26行的文件“ quotes.py”中 watermark_text(img,'1.jpg', 在watermark_text中,文件“ quotes.py”,第10行 照片= Image.open(input_image_path) 打开文件“ /data/data/com.termux/files/usr/lib/python3.8/site-packages/PIL/Image.py”,第2878行 fp = Builtins.open(filename,“ rb”)FileNotFoundError:[错误2]没有这样的文件或目录:'1qqq.jpg'

如何解决?

1 个答案:

答案 0 :(得分:0)

我对此很粗心,我应该这样写

import os
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

def watermark_text(input_image_path,
                   output_image_path,
                   text, pos):
    photo = Image.open(input_image_path)

    # make the image editable
    drawing = ImageDraw.Draw(photo)

    black = (255, 255, 255)
    font = ImageFont.truetype("font.ttf", 40)
    drawing.text(pos, text, fill=black, font=font)
    photo.show()
    photo.save(output_image_path)

if __name__ == '__main__':
    path="./bg/"
    files=os.listdir(path)
    d=random.choice(files)
    img = path + d
    watermark_text(img, '1.jpg',
                   text='Risna Fadillah',
                   pos=(0, 0))

对不起。