feat: global img 压缩

This commit is contained in:
caoqianming 2023-08-22 10:33:19 +08:00
parent 0772be47de
commit 9ba12d06da
3 changed files with 28 additions and 11 deletions

View File

@ -27,6 +27,7 @@ from apps.utils.tools import timestamp_to_time
from apps.third.tapis import xxapis
import logging
from datetime import datetime
from apps.utils.img import compress_image
myLogger = logging.getLogger('log')
requests.packages.urllib3.disable_warnings()
@ -58,6 +59,8 @@ def save_dahua_pic(pic_url: str, save_path: str = '/media/'):
os.makedirs(full_path)
with open(full_path + file_name, 'wb') as f:
f.write(res.content)
full_path_file = full_path + file_name
compress_image(full_path_file)
return path + file_name

View File

@ -24,6 +24,7 @@ from datetime import timedelta
from apps.ai.main import algo_dict
from datetime import datetime
import uuid
from apps.utils.img import compress_image
@shared_task(base=CustomTask)
def store_img(code: str, duration: int):
@ -192,4 +193,11 @@ def monitor_and_analyse(vchannel_code: str, algo_codes: list):
# 释放资源
cap.release()
cv2.destroyAllWindows()
cv2.destroyAllWindows()
@shared_task(base=CustomTask)
def compressed_all_ecm_image():
events = Event.objects.exclude(global_img=None)
for event in events:
if event.global_img:
compress_image(settings.BASE_DIR + event.global_img)

View File

@ -1,7 +1,7 @@
import os
from PIL import Image
def compress_image(infile, outfile='', kb=80, step=10, quality=80):
def compress_image(infile, outfile='', kb=80, quality=80):
"""不改变图片尺寸压缩到指定大小
:param infile: 压缩源文件
:param outfile: 压缩文件保存地址
@ -14,12 +14,18 @@ def compress_image(infile, outfile='', kb=80, step=10, quality=80):
if o_size <= kb:
return infile
if outfile == '':
outfile = infile
while o_size > kb:
im = Image.open(infile)
im.save(outfile, quality=quality)
if quality - step < 0:
break
quality -= step
o_size = os.path.getsize(outfile)/1024
return outfile, o_size
path, end = infile.split('.')
outfile = path + '_compressed.' + end
im = Image.open(infile)
im.save(outfile, quality=quality)
while os.path.getsize(outfile) / 1024 > kb:
imx = Image.open(outfile)
# Resize the image using the same aspect ratio to reduce the file size
width, height = imx.size
new_width = int(width * 0.9) # You can adjust the scaling factor
new_height = int(height * 0.9)
imx = imx.resize((new_width, new_height), Image.ANTIALIAS)
imx.save(outfile, quality=quality)
# quality -= step
return outfile, os.path.getsize(outfile) / 1024