9

I am making a website. I want to check from the server whether the link that the user submitted is actually an image that exists.

4

4 に答える 4

12

これは、迅速な方法の 1 つです。

それが実際に画像ファイルであることを実際に確認するのではなく、ファイルの拡張子に基づいて推測し、URL が存在することを確認するだけです。URL から返されたデータが実際に画像であることを確認する必要がある場合 (セキュリティ上の理由から)、このソリューションは機能しません。

import mimetypes, urllib2

def is_url_image(url):    
    mimetype,encoding = mimetypes.guess_type(url)
    return (mimetype and mimetype.startswith('image'))

def check_url(url):
    """Returns True if the url returns a response code between 200-300,
       otherwise return False.
    """
    try:
        headers = {
            "Range": "bytes=0-10",
            "User-Agent": "MyTestAgent",
            "Accept": "*/*"
        }

        req = urllib2.Request(url, headers=headers)
        response = urllib2.urlopen(req)
        return response.code in range(200, 209)
    except Exception:
        return False

def is_image_and_ready(url):
    return is_url_image(url) and check_url(url)
于 2012-05-11T00:40:29.593 に答える
1

imghdrを見てください

コード例を次に示します。

import imghdr
import httplib
import cStringIO

conn = httplib.HTTPConnection('www.ovguide.com', timeout=60)
path = '/img/global/ovg_logo.png'
conn.request('GET', path)
r1 = conn.getresponse()

image_file_obj = cStringIO.StringIO(r1.read())
what_type = imghdr.what(image_file_obj)

print what_type

これは「png」を返すはずです。画像でない場合は None を返します

それが役立つことを願っています!

-ブレイク

于 2012-05-11T00:51:09.277 に答える