]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/util.py
13 def format_size(s
, max_unit
=None):
14 units
= ("B", "kB", "MB", "GB", "TB")
17 while s
>= 1024 and i
< len(units
) - 1:
21 if max_unit
and units
[i
] == max_unit
:
24 return "%.0f%s" % (s
, units
[i
])
26 def format_time(s
, shorter
=True):
27 #_ = handler.locale.translate
30 hrs
, s
= divmod(s
, 3600)
31 min, s
= divmod(s
, 60)
36 if shorter
and not hrs
:
37 return _("%(min)d min") % { "min" : min }
39 return _("%(hrs)d:%(min)02d hrs") % {"hrs" : hrs
, "min" : min}
41 def random_string(length
=8):
42 input_chars
= string
.ascii_letters
+ string
.digits
44 r
= (random
.choice(input_chars
) for i
in range(length
))
49 # Remove any non-ASCII characters
51 s
= unicodedata
.normalize("NFKD", s
)
55 # Remove excessive whitespace
56 s
= re
.sub(r
"[^\w]+", " ", s
)
58 return "-".join(s
.split())
60 def generate_thumbnail(data
, size
, square
=False, **args
):
61 assert data
, "No image data received"
63 image
= PIL
.Image
.open(io
.BytesIO(data
))
68 # Remove any alpha-channels
69 if image
.format
== "JPEG" and not image
.mode
== "RGB":
70 # Make a white background
71 background
= PIL
.Image
.new("RGBA", image
.size
, (255,255,255))
73 # Convert image to RGBA if not in RGBA, yet
74 if not image
.mode
== "RGBA":
75 image
= image
.convert("RGBA")
77 # Flatten both images together
78 flattened_image
= PIL
.Image
.alpha_composite(background
, image
)
80 # Remove the alpha channel
81 image
= flattened_image
.convert("RGB")
83 # Resize the image to the desired resolution
85 image
= PIL
.ImageOps
.fit(image
, (size
, size
), PIL
.Image
.LANCZOS
)
87 image
.thumbnail((size
, size
), PIL
.Image
.LANCZOS
)
89 if image
.format
== "JPEG":
90 # Apply a gaussian blur to make compression easier
91 image
= image
.filter(PIL
.ImageFilter
.GaussianBlur(radius
=0.05))
93 # Arguments to optimise the compression
95 "subsampling" : "4:2:0",
99 with io
.BytesIO() as f
:
100 # If writing out the image does not work with optimization,
101 # we try to write it out without any optimization.
103 image
.save(f
, format
, optimize
=True, **args
)
105 image
.save(f
, format
, **args
)