Skip to content

Commit

Permalink
support file that without extension
Browse files Browse the repository at this point in the history
  • Loading branch information
a523 committed Nov 13, 2021
1 parent 5409818 commit b9fb1fe
Showing 1 changed file with 38 additions and 15 deletions.
53 changes: 38 additions & 15 deletions preview_generator/preview/builder/image__wand.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

from wand.color import Color
from wand.image import Image
from wand.exceptions import WandException
import wand.version

from preview_generator.extension import mimetypes_storage
from preview_generator.exception import BuilderDependencyNotFound
from preview_generator.preview.generic_preview import ImagePreviewBuilder
from preview_generator.utils import ImgDims
Expand Down Expand Up @@ -124,23 +126,44 @@ def build_jpeg_preview(
size = self.default_size
preview_name = preview_name + extension
dest_path = os.path.join(cache_path, preview_name)
self.image_to_jpeg_wand(file_path, size, dest_path)
self.image_to_jpeg_wand(file_path, size, dest_path, mimetype=mimetype)

def image_to_jpeg_wand(self, file_path: str, preview_dims: ImgDims, dest_path: str,
mimetype: typing.Optional[str]) -> None:
try:
with self._convert_image(file_path, preview_dims) as img:
img.save(filename=dest_path)
except WandException as e:
assert mimetype
file_ext = mimetypes_storage.guess_extension(mimetype, strict=False) or ""
if file_ext:
file_path = file_ext.lstrip(".") + ":" + file_path
with self._convert_image(file_path, preview_dims) as img:
img.save(filename=dest_path)
else:
raise e

def _convert_image(self, file_path: str, preview_dims: ImgDims) -> Image:
"""
refer: https://legacy.imagemagick.org/Usage/thumbnails/
like cmd: convert -flatten -background white -thumbnail widthxheight \
-auto-orient -quality 85 -interlace plane input.jpeg output.jpeg
"""

def image_to_jpeg_wand(self, file_path: str, preview_dims: ImgDims, dest_path: str,) -> None:
with Image(filename=file_path) as img:
# https://legacy.imagemagick.org/Usage/thumbnails/
img.auto_orient()
img.background_color = Color("white")
img.merge_layers("flatten")
img = Image(filename=file_path)
img.auto_orient()
img.background_color = Color("white")

if self.progressive:
img.interlace_scheme = "plane"
img.merge_layers("flatten")

img.compression_quality = self.quality
if self.progressive:
img.interlace_scheme = "plane"

resize_dim = compute_resize_dims(
dims_in=ImgDims(width=img.width, height=img.height), dims_out=preview_dims
)
img.thumbnail(resize_dim.width, resize_dim.height)
img.compression_quality = self.quality

resize_dim = compute_resize_dims(
dims_in=ImgDims(width=img.width, height=img.height), dims_out=preview_dims
)
img.thumbnail(resize_dim.width, resize_dim.height)

img.save(filename=dest_path)
return img

0 comments on commit b9fb1fe

Please sign in to comment.