简体   繁体   English

从目录中提取随机图像,编码为base64,然后打印

[英]Pull random image from directory, encode to base64 and then print

I'm having difficult time trying to work these two together. 我很难把这两个一起工作。 It's frustrating me a little, so I hope to find ideas/solutions. 这让我有些沮丧,所以我希望找到想法/解决方案。

The complete works (what I'm planning on) should grab a random image from an online directory, encode it to base64 then print the base64. 完整的作品(我正在计划的作品)应该从在线目录中获取随机图像,将其编码为base64,然后打印base64。 I've had total curl madness going all day and now I'm turning to python. 我整天都在疯狂地疯狂,现在我转向python。 Onwards! 向前!

These are kinda just notes at the minute but should explain the process. 这些只是目前的注释,但应解释该过程。

import random, os
import base64

def search(): #get file
    path = r"/Users/Impshum/Pictures" #should be able to http
    random_filename = random.choice([
        x for x in os.listdir(path)
        if os.path.isfile(os.path.join(path, x))
    ])
    print(random_filename) #not printing full location


def encode(): #encode to base64
    image = open('heaven.jpg', 'rb')
    image_read = image.read()
    image_64_encode = base64.encodestring(image_read)
    print image_64_encode

search() #notes
encode() #notes

Many thanks in advance. 提前谢谢了。

You have most of the code you need 您拥有所需的大部分代码

import random, os
import base64

def search(path): #get file
    random_filename = random.choice([
        x for x in os.listdir(path)
        if os.path.isfile(os.path.join(path, x))
    ])
    return os.path.join(path, random_filename)


def encode(path):
    image = open(path, 'rb')
    image_read = image.read()
    image.close()
    image_64_encode = base64.encodestring(image_read)
    return image_64_encode

print(encode(search(r"/Users/Impshum/Pictures")))

There are things you can do to make this "nicer", but this should get you started. 您可以做一些事情来使这个“更精细”,但这应该可以帮助您入门。

For instance, you might want to use glob instead of os.listdir / os.path.join, etc. And using a context manager 例如,您可能要使用glob而不是os.listdir / os.path.join等。并使用上下文管理器

import glob
import base64
import random

def search(path): #get file
    random_filename = random.choice(glob.glob(path))
    return random_filename


def encode(path):
    with open(path, 'rb') as image:
        image_read = image.read()
        image_64_encode = base64.encodestring(image_read)
        return image_64_encode

print(encode(search(r"/Users/Impshum/Pictures/*")))

Error handling is left as an exercise to the OP 错误处理留给OP练习

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM