Skip to main content
 首页 » 编程设计

python之将文件夹中的多个jpg文件编码为python中的base 64

2024年11月24日13powertoolsteam

如何将一个文件夹中的多个 jpeg 文件编码为 base 64。目前我的代码只能对一个文件进行编码。但是我希望这样可以对文件夹路径中的所有 jpeg 文件进行编码。

with open("path\\A.jpg", "rb") as image_file: 
    encoded_string = base64.b64encode(image_file.read()) 

extract_ocr_words(编码字符串)

在上面的路径中会有多个jpeg文件比如

A.jpg 
B.jpg 
C.jpg 

最终输出应该结合文件夹中的所有图像并提取文本并在最终命令中显示为列表

extract_ocr_words(encoded_string) 
 
['ABC', 'LKM', 'GHI', 'TLI', 'CLI'] 

请您参考如下方法:

您必须遍历文件夹内的文件。您可以使用 os 库 ( link ):

import os 
 
words = [] 
directory = 'path/to/your/pictures' 
for filename in os.listdir(directory): 
    if filename.endswith(".jpg"):  
        with open(os.path.join(directory, filename), "rb") as image_file: 
            encoded_string = base64.b64encode(image_file.read()) 
            words.extend(extract_ocr_Words(encoded_string)) 
    else: 
        continue 
print('Words from all files') 
print(words) 

您还可以使用 os.path.join() ( link to function ) 函数连接路径的两个部分。它适用于 Windows 和 Unix 系统。它比转义 \ 更好。然后由您决定如何处理编码后的图像。

您仍然可以使用 glob 包来缩短您的代码。 功能可以实现如下:

import glob 
 
words = [] 
for f_name in glob.glob('*.jpg'): 
    with open(f_name,"rb") as image_file: 
         encoded_string = base64.b64encode(image_file.read()) 
         words = extract_ocr_Words(encoded_string) 
         words.extend(extract_ocr_Words(encoded_string)) 
    else: 
        continue 
print('Words from all files') 
print(words)