简体   繁体   English

使用 Python 3 从 URL 中提取图像

[英]Extract Image from a URL using Python 3

I'm working on a REST API using Flask in which I have to retrieve an Image from a URL which is provided by the user inside the Url Parameters.我正在使用 Flask 处理 REST API,其中我必须从用户在 Url 参数中提供的 URL 中检索图像。

Here's What I have tried:这是我尝试过的:

import urllib
from io import BytesIO
from PIL import Image
from flask import Flask

app = Flask(__name__)


@app.route('/<path:image_url>')
def build_mask_rmv_bg(image_url):
    f = urllib.request.urlopen(image_url)
    jpeg_str = f.read()
    original_im = Image.open(BytesIO(jpeg_str))
    return original_im


if __name__ == '__main__':
    app.run()

And, Here my request:而且,这是我的要求:

http://127.0.0.1:5000/http://raw.githubusercontent.com/tensorflow/models/master/research/deeplab/g3doc/img/image2.jpg

I have tried both HTTP & HTTTPs paths in URL Parameter.But it return the following error:我在 URL Parameter.But 中尝试了 HTTP 和 HTTTPS 路径,但返回以下错误:

urllib.error.URLError: <urlopen error [SSL:CERTIFICATE_VERIFY_FAILED] certificate
verify failed (_ssl.c:749)>
127.0.0.1 - - [01/Sep/2018 09:37:51] "GET /http://raw.githubusercontent.com/tensorflow/models/master/research/deeplab/g3doc/img/image2.jpg HTTP/1.1" 500 -

Update:更新:

I have updated it by using wget , now it doesn't return any error but the file is still not downloading the image.我已经使用wget更新了它,现在它没有返回任何错误,但文件仍然没有下载图像。

Here's the updated code:这是更新后的代码:

from flask import Flask
import wget
app = Flask(__name__)


@app.route('/<path:image_url>')
def build_mask_rmv_bg(image_url):
    url = str(image_url)
    # download the file contents in binary format
    print(url)
    wget.download(url, "img/image1.jpg")
    return 'something happened'


if __name__ == '__main__':
    app.run()

What's wrong here?这里有什么问题?

Help me, please!请帮帮我!

Thanks in advance!提前致谢!

You can use Python request module to get data from URL then save in file in binary format like this您可以使用 Python 请求模块从 URL 获取数据,然后像这样以二进制格式保存在文件中

f = open(filename, "wb")
r = requests.get(url)
f.write(r.content)

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

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