使用python中的imagemagick下载、编写、转换和保存(损坏的图像)

2024-09-29 23:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我已经试着解决这个问题六个小时了,但是没有成功。在

我有一个函数,它根据时间戳(使用Requests library)从URL抓取一堆图像(GIF)文件。图像保存到我的桌面在一个特定的目录很好。 当我试图打开那个图像时,重命名并处理它,然后一切都会中断。在

以下是设置所有内容的初始方法:

def createImage():

    AB_CODES = ["WHK", "WHN", "WWW", "XBU", "XSM"]
    BASE_URL = "http://url_where_I_get_images_from"

    orig_dir = "originals/"
    new_dir = "processed/"

    # Add new image for each code
    for code in AB_CODES:
        radar_dir = BASE_URL + code
        url = requests.head(radar_dir)

        #parseUrl creates a valid timestamp corresponding to the latest image.
        timestamp = parseUrl(url)

        filename = timestamp + "_" + code + "_PRECIP_RAIN.gif"
        radar = BASE_URL + code + "/" + filename
        radar_img = requests.get(radar, timeout=30.000)

        # This is where the file from original source gets saved to my desktop, works.
        # Image gets saved in path/originals/img.gif
        if (radar_img.status_code == requests.codes.ok):
            image = radar_img.content
            filepath = os.path.join(orig_dir, filename)
            imgfile = open(filepath, "wb")
            imgfile.write(image)
            imgfile.close()

            # This is where I create a new image to be saved and worked on in
            # path/processed/new_img.gif
            image = radar_img.content
            filename = code + "_radar.gif"
            convpath = os.path.join(new_dir, filename)
            convimg = open(convpath, "wb")
            convimg.write(image)
            # This is the call to the function where I use imagemagick
            # which is not working
            image = processImage(convimg.name, "processed/XSM_radar_output.gif")
            convimg.close()

这里有两种方法组成我的处理函数。现在它正处于测试阶段,因为它不起作用。在

^{pr2}$

我试过没有外壳=真的。我收到的错误消息是映像已损坏:

Image: processed/XSM_radar.gif
convert processed/XSM_radar.gif -resize 50x50 processed/XSM_radar.gif
convert.im6: corrupt image `processed/XSM_radar.gif' @ error/gif.c/ReadGIFImage/1356.
convert.im6: no images defined `processed/XSM_radar_output.gif' @    error/convert.c/ConvertImageCommand/3044.
processed/XSM_radar.gif : FAIL!

我不明白为什么它告诉我它已经腐坏了。我在命令行中运行了这些完全相同的命令,它工作得很好。 (我已导入子流程)


Tags: thetoimageurlimgnewisdir
1条回答
网友
1楼 · 发布于 2024-09-29 23:24:23

有人帮我确定了错误。在

def processImage(input, output, verbose=True, shell=True):
    args = [
        "convert", input, 
        "-resize", "50x50", 
        output
    ]

if verbose:
    print("Image: %s" % input)
    print(" ".join(formatArg(a) for a in args))
    print
if os.path.exists(input):
    try:
        **result = subprocess.check_call(args)**
    **except subprocess.CalledProcessError:**
        **result = False**
    **if result:**
        print("%s : SUCCESS!" % output)
    else:
        print("%s : FAIL!" % output)

结果应该是

^{pr2}$

如果返回错误,result_code应该设置为1。 所以:

if result_code == 0:
    do stuff

感谢您的关注! 祝你今天愉快。在

相关问题 更多 >

    热门问题