Skip to content

Commit

Permalink
Render SVG avatars directly at the final resolution.
Browse files Browse the repository at this point in the history
  • Loading branch information
linkmauve committed Jan 25, 2019
1 parent 71ef2a3 commit ebc886d
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions poezio/windows/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,27 @@ class Image:
from typing import Tuple, Optional, Callable


MAX_SIZE = 16


def render_svg(svg: bytes) -> Optional[Image.Image]:
if not HAS_RSVG:
return None
try:
handle = Rsvg.Handle.new_from_data(svg)
dimensions = handle.get_dimensions()
surface = cairo.ImageSurface(cairo.Format.ARGB32, dimensions.width, dimensions.height)
biggest_dimension = max(dimensions.width, dimensions.height)
scale = MAX_SIZE / biggest_dimension
translate_x = (biggest_dimension - dimensions.width) / 2
translate_y = (biggest_dimension - dimensions.height) / 2

surface = cairo.ImageSurface(cairo.Format.ARGB32, MAX_SIZE, MAX_SIZE)
context = cairo.Context(surface)
context.scale(scale, scale)
context.translate(translate_x, translate_y)
handle.render_cairo(context)
data = surface.get_data()
image = Image.frombytes('RGBA', (dimensions.width, dimensions.height), data.tobytes())
image = Image.frombytes('RGBA', (MAX_SIZE, MAX_SIZE), data.tobytes())
# This is required because Cairo uses a BGRA (in host endianess)
# format, and PIL an ABGR (in byte order) format. Yes, this is
# confusing.
Expand Down

0 comments on commit ebc886d

Please sign in to comment.