Android【照片备份】【折腾方案1】

  1. 理由
  • 群辉硬盘挂了,备份软件不能用了
  • usb 直接复制不稳定
  • xx助手不想装
  1. 方案
# 安卓安装Termux
# Termux搭建运行http server【遇到权限问题】
 - pkg update
 - pkg install tsu # root 权限
 - termux-setup-storage # 获取手机权限
 - ls ~/storage/shared # 查看权限
# 客户端爬取httpserver照片【指定路径递归问题】
# 下载后照片根据【exif】自动分类
 - 根据手机型号归类到人
 - 个人目录下根据时间按月建立文件夹
  1. 实现【很折腾,2天时间】
1. 服务器搭建随意,返回照片url即可,照片名称随意反正下载后要按照时间修改

2.客户端方案
 - 下载
   - scrapy 现成的能满足功能和性能要求,就是一段时间不用重新用需要点时间-pass
   - 自己实现,解决保存文件夹递归问题
def download_all_img(main_url="http://192.168.1.68:8000/Pictures",dest_fold_name="C:/aa-test/pic_download/"):
    dest_fold_name_list = [dest_fold_name]
    print(dest_fold_name_list)
    _download_all_img(main_url, dest_fold_name_list)


def _download_all_img(main_url, dest_fold_name_list):
    if isinstance(main_url,(str,)) and not main_url.endswith('/'):
        main_url = main_url+"/"
    r = requests.get(url=main_url, headers=headers)
    # r.encoding = 'gb2312'  # 根据情况选择编码
    html = r.text
    bs = BeautifulSoup(html, "html.parser")
    data = bs.select("body ul li a")  # css 用法
    for i in data:
        url_name = i.text
        if not url_name.startswith('.'):
            # 文件夹不需要递归增加层级
            dest_fold_name_list.append(os.path.join(dest_fold_name_list[-1], url_name))
            sub_url = main_url + url_name  # 需要随着递归增加层级
            if url_name.endswith('/'):
                _download_all_img(sub_url, dest_fold_name_list)
                dest_fold_name_list.pop() # 文件夹不需要递归增加层级
            else:
                dest_fold_name_list.pop() # 文件夹不需要递归增加层级
                # dest_fold_name_list[-1] 才是对应的文件夹
                download_one_img(sub_url,dest_fold_name_list[-1],url_name)


 - 照片归类
# 重复文件copy覆盖解决方法,递归,防止重命名后还是重复
def get_new_name2(file):
    if os.path.exists(file):
        new_file = file[:file.rfind('.')] + '_copy' + file[file.rfind('.'):]
        return get_new_name2(new_file)# 新命名文件是否存在
    return file# 返回新文件路径


def get_exif_and_arrange_img(imgfile, outdir):
    dirname, imgfilename = os.path.split(imgfile)
    # 整理后文件存放地址
    if (not os.path.isdir(outdir)):
        os.mkdir(outdir)
    #  存放exif 无法读取或者读取后为空的照片
    EXIF_ERROR_OR_NONE = os.path.join(outdir, 'OtherPerson', 'OtherDevice')
    if (not os.path.isdir(EXIF_ERROR_OR_NONE)):
        os.makedirs(EXIF_ERROR_OR_NONE)
    try:
        img = Image.open(imgfile, "r")
        print(imgfilename.center(80, '*'))
    except:
        videodir = outdir + '\\' + 'VIDEOS'
        if (not os.path.isdir(videodir)):
            os.mkdir(videodir)
        newvideofilename = \
            imgfilename[:imgfilename.rfind('.')] + '_' + str(random.randint(1, 999)) + imgfilename[imgfilename.rfind('.'):]
        final_file = videodir + '\\' + newvideofilename
        final_file = get_new_name2(final_file)
        shutil.copyfile(imgfile, final_file)
    else:
        try:
            exif_data = img._getexif()
        except:
            otherdir = outdir + '\\' + 'OTHERS'
            if not os.path.isdir(otherdir):
                os.mkdir(otherdir)
            newphotofilename = imgfilename[:imgfilename.rfind('.')] + '_' + str(random.randint(1, 999)) + imgfilename[imgfilename.rfind('.'):]
            final_file = otherdir + '\\' + newphotofilename
            final_file = get_new_name2(final_file)
            shutil.copyfile(imgfile, final_file)
        else:
            if exif_data:
                device = ''
                photodate = ''
                fulldate = ''
                for tag, value in exif_data.items():
                    # begin
                    decoded = TAGS.get(tag, tag)
                    # Make+Model是手机型号
                    if (decoded == 'Make'):
                        device += value + '_'
                    if (decoded == 'Model'):
                        device += value
                    # DateTime (306) = 2019:11:07 10:24:53
                    if (decoded == 'DateTime'):
                        photodate = value.replace(':', '')[0:6]  # 照片的月份
                        fulldate = value.replace(':', '')        # 照片详细时间
                    # end
                # begin
                device = device.replace("\0", '')
                if device == '':
                     device ='OtherDevice'
                #确定是谁的手机
                if device in PHONE_DEVICE_NAME:
                    device = PHONE_DEVICE_NAME[device]
                    devicedir = os.path.join(outdir, device)
                else:
                    devicedir = os.path.join(outdir, 'OtherPerson', device)
                if (not os.path.isdir(devicedir)):
                    os.makedirs(devicedir)
                device_datedir = devicedir + '\\' + photodate
                if (not os.path.isdir(device_datedir)):
                    os.mkdir(device_datedir)
                if photodate:
                    newphotofilename = fulldate + '_' + str(random.randint(1, 9999999)) + imgfilename[imgfilename.rfind('.'):]
                else:
                    #exif 有数据但是读取不到日期和设备信息,直接拷贝文件到 OtherDevice 下
                    newphotofilename = imgfilename

                final_file = device_datedir + '\\' + newphotofilename
                final_file = get_new_name2(final_file)
                shutil.copyfile(imgfile, final_file)
                img.close()
                # end
            else:
                # exif 没有有数据,直接拷贝文件到 OtherDevice 下
                print('exif data is None:' + imgfilename)
                final_file = EXIF_ERROR_OR_NONE + '\\' + imgfilename
                final_file = get_new_name2(final_file)
                shutil.copyfile(imgfile, final_file)


def arrange_img(soure_dir, det_dir):
    for parent, _dirnames, filenames in os.walk(soure_dir):
        for filename in filenames:
            imgfile = os.path.join(parent, filename)
            # imgfile图片全路径,det_dir新的文件夹
            get_exif_and_arrange_img(imgfile, det_dir)

原文地址:https://www.cnblogs.com/amize/p/15516955.html