近期接手了一个前端项目,里面的图片资源文件很乱,看了下绝大多数都是2K以下的小图标,为了性能考虑图片准备做成雪碧图式。但是这个项目里面的图片比较混乱,存在着好几个版本,UI提供了最新的版本 但是最新版本里面的图片又不是都在使用,老版本里面的文件也不是都不再使用。所以存在着需要将这些不再使用的图片识别出来并且删除的问题。
经过一番搜索,没有找到合适的方式,自己学着写了段python代码。提供了两种方式
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import subprocess
import shlex
import shutil
import time
exclude_AssetImage = 'assets'
project_dir = "/Users/Documents/test/src"
back_not_used_dir = "/Users/Documents/test/src/assets/notUse"
auto_delete = 0
auto_move = 0
def do_find_command(search_dir,file_type):
dict = {}
if len(search_dir) == 0 or len(file_type) == 0:
return dict
search_dir = search_dir.replace('\n','')
command = "find '{}' -name '*.{other}' 2>/dev/null".format(search_dir,other = file_type)
s = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
results = s.communicate()[0].split()
for name in results:
if not name.endswith(file_type):
continue
dict[name] = name[name.find('assets'):]
return dict
def do_grep(path,key_word):
if not is_available_file_path(path):
print ('path:%s is not available' % path)
return
command = "grep -w -q '%s' '%s'" %(key_word,path)
if subprocess.call(command, shell=True) == 0:
return 1
else:
return 0
def goal_file(path):
files = []
for dirName, subdirList, fileList in os.walk(path):
for fname in fileList:
if is_available_file_path(fname):
path = '%s/%s' % (dirName,fname)
files.append(path)
return files
def is_available_file_path(path):
available = 0
if path.endswith('.less'):
available = 1
if path.endswith('.css'):
available = 1
if path.endswith('.js'):
available = 1
if path.endswith('.vue'):
available = 1
return available
def support_types():
types = []
types.append('png')
types.append('jpg')
types.append('jpeg')
types.append('gif')
return types
def delete_not_used_image(path):
os.remove(path)
print ('\r\n ========%s is deleted========' % path)
def move_not_used_image(path):
shutil.move(path,back_not_used_dir)
print ('\r\n ========%s is moved========' % path)
def start_find_task():
print("\nstart finding task...\nbelows are not used images:\n")
global project_dir
if len(sys.argv) > 1:
project_dir = sys.argv[1]
if project_dir == " ":
print("error! project_dir can not be nil")
start = time.time()
i = 0
results = {}
for type in support_types():
results = dict( results.items() + do_find_command(project_dir,type).items() )
goal_files = goal_file(project_dir)
for result in results:
used = 0
for file_path in goal_files:
if do_grep(file_path,results[result]):
used = 1
break
if used == 0:
print(result)
i = i + 1
if auto_delete:
if result.find('standard') < 0:
delete_not_used_image(result)
elif auto_move:
move_not_used_image(result)
c = time.time() - start
print('\nsearch finish,find %s results,total count %0.2f s'%(i,c))
start_find_task()
里面涉及到两个参数
auto_delete (找到未使用的图片文件直接删除)
auto_move (找到未使用的图片文件移动到指定目录)
本文介绍了在接手一个前端项目时,如何处理和优化混乱的图片资源,特别是针对2K以下的小图标。为提高性能,作者计划采用雪碧图,并需识别并删除未使用的图片。在找不到现成解决方案的情况下,作者自学Python编写了代码,提供两种功能:自动删除或移动未使用的图片文件。代码涉及关键参数auto_delete和auto_move。

481

被折叠的 条评论
为什么被折叠?



