zoukankan      html  css  js  c++  java
  • Python 图像下载解决图像损坏

    在下载图片的过程中,经常会发现图片损坏,下面提供了两种解决方法:

    方法一:

     if response.status_code == 200:
            print '=================================================='
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            total_path = dir_path + '/' + file_name
          # 核心代码,比较请求返回数据的大小和请求反应头里面的大小
            if len(response.content) == int(response.headers['Content-Length']):
    # print total_path with open(total_path, 'wb') as f: for chunk in response.iter_content(1024): f.write(chunk) f.close() else: raise FError('图片加载不完全') else: raise FError('网络没有正常返回')

    方法二:

     response = requests.get(url=source_url, headers=headers,verify=False,proxies=proxies,timeout=15)
            if response.status_code == 200:
                if not os.path.exists(dir_path):
                    os.makedirs(dir_path)
                total_path = dir_path + '/' + file_name
    
                image = Image.open(BytesIO(response.content))
                image.save(total_path)
    
                print "图片保存到本地"
                return "1"
            else:
                print "图片没有保存到本地"

    这两张方法都下载了一千多张图片作为测试,没有发现下载的图片加载到一半,或者其他错误。

    记录下来,仅供以后参考使用。

  • 相关阅读:
    shell 逻辑操作符
    shell 整数
    shell 字符串
    常用文件测试操作符
    系统级脚本 rpcbind
    shell 特殊字符
    redhat7.5 升级OpenSSH_7.8p1
    kubernetes 项目
    salt 安装kubernetes集群3节点
    web应用
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/8599992.html
Copyright © 2011-2022 走看看