1

我的目标是有一个程序下载图像,对其进行故障处理,然后上传故障图像。到目前为止,我的代码如下所示:

import urllib 
import random
import pytumblr
from tumblr_keys import 
from BeautifulSoup import BeautifulStoneSoup

# Authenticate via OAuth
client = pytumblr.TumblrRestClient(
    consumer_key,
    consumer_secret,
    token_key,
    token_secret
)

def download_an_image(image_url):

    filename = image_url.split('/')[-1] 
    #filefinal = filename[:-4 ] + '.png'
    urllib.urlretrieve(image_url, filename)

    return filename

def get_random_start_and_end_points_in_file(file_data):
    start_point = random.randint(2600, len(file_data))
    end_point = start_point + random.randint(0, len(file_data) -     start_point)

    return start_point, end_point

def splice_a_chunk_in_a_file(file_data):
    start_point, end_point = get_random_start_and_end_points_in_file(file_data)
    section = file_data[start_point:end_point]
    repeated = ''

    for i in range(1, random.randint(1,2)):
        repeated += section

    new_start_point, new_end_point = get_random_start_and_end_points_in_file(file_data)
    file_data = file_data[:new_start_point] + repeated +    file_data[new_end_point:]
    return file_data

def glitch_an_image(local_image):
    file_handler = open(local_image, 'r')
    file_data = file_handler.read()
    file_handler.close()

    for i in range(1, random.randint(0,2)):
        file_data = splice_a_chunk_in_a_file(file_data)

    file_handler = open(local_image, 'w')
    file_handler.write(file_data)
    file_handler.close

    return local_image

if __name__ == '__main__':

    image_url = "https://41.media.tumblr.com/179e82abf626f870cb0b8fe93919eb67/tumblr_o4t9wtxwO31vq0p00o1_1280.png"
    local_image = download_an_image(image_url)
    image_glitch_file = glitch_an_image(local_image)

    client.create_photo('glitchingimages', state="published", tags=["glitch"], data= image_glitch_file)

为了确保下载的图片始终保存为 .png 文件,我尝试在“def download_an_image(image_url):”部分运行第二行。出于某种原因,Tumblr 仍然不允许我上传故障图像。我什至尝试上传它,它给了我一个错误。但我能够将它上传到 Flickr。只有当我再次将 .png 文件导出为 .png 时,我才能将其上传到 Tumblr。

您知道避免手动导出图像的方法吗?是否有更好的方法来确保下载的图像保存为 .png 文件?

谢谢!

4

0 回答 0