Esempio n. 1
0
def resize_icon(source, dest_folder, target_sizes, **kw):
    """Resizes addon icons."""
    log.info('[1@None] Resizing icon: %s' % dest_folder)
    try:
        # Resize in every size we want.
        dest_file = None
        for size in target_sizes:
            dest_file = '%s-%s.png' % (dest_folder, size)
            resize_image(source, dest_file, (size, size))

        # Store the original hash, we'll return it to update the corresponding
        # add-on. We only care about the first 8 chars of the md5, it's
        # unlikely a new icon on the same add-on would get the same first 8
        # chars, especially with icon changes being so rare in the first place.
        with open(source, 'rb') as fd:
            icon_hash = hashlib.md5(fd.read()).hexdigest()[:8]

        # Keep a copy of the original image.
        dest_file = '%s-original.png' % dest_folder
        os.rename(source, dest_file)

        return {
            'icon_hash': icon_hash
        }
    except Exception as e:
        log.error("Error saving addon icon (%s): %s" % (dest_file, e))
Esempio n. 2
0
def _recreate_images_for_preview(preview):
    log.info('Resizing preview: %s' % preview.id)
    try:
        preview.sizes = {
            'thumbnail_format': amo.ADDON_PREVIEW_SIZES['thumbnail_format']
        }
        if storage.exists(preview.original_path):
            # We have an original size image, so we can resize that.
            src = preview.original_path
            preview.sizes['image'], preview.sizes['original'] = resize_image(
                src,
                preview.image_path,
                amo.ADDON_PREVIEW_SIZES['full'],
            )
            preview.sizes['thumbnail'], _ = resize_image(
                src,
                preview.thumbnail_path,
                amo.ADDON_PREVIEW_SIZES['thumbnail'],
                format=amo.ADDON_PREVIEW_SIZES['thumbnail_format'],
            )
        else:
            # Otherwise we can't create a new sized full image, but can
            # use it for a new thumbnail
            src = preview.image_path
            preview.sizes['thumbnail'], preview.sizes['image'] = resize_image(
                src,
                preview.thumbnail_path,
                amo.ADDON_PREVIEW_SIZES['thumbnail'],
                format=amo.ADDON_PREVIEW_SIZES['thumbnail_format'],
            )
        preview.save()
        return True
    except Exception as e:
        log.exception('Error saving preview: %s' % e)
Esempio n. 3
0
def resize_preview(src, preview_pk, **kw):
    """Resizes preview images and stores the sizes on the preview."""
    preview = Preview.objects.get(pk=preview_pk)
    thumb_dst, full_dst, orig_dst = (
        preview.thumbnail_path,
        preview.image_path,
        preview.original_path,
    )
    sizes = {}
    log.info('[1@None] Resizing preview and storing size: %s' % thumb_dst)
    try:
        (sizes['thumbnail'], sizes['original']) = resize_image(
            src, thumb_dst, amo.ADDON_PREVIEW_SIZES['thumb']
        )
        (sizes['image'], _) = resize_image(
            src, full_dst, amo.ADDON_PREVIEW_SIZES['full']
        )
        if not os.path.exists(os.path.dirname(orig_dst)):
            os.makedirs(os.path.dirname(orig_dst))
        os.rename(src, orig_dst)
        preview.sizes = sizes
        preview.save()
        return True
    except Exception as e:
        log.error('Error saving preview: %s' % e)
Esempio n. 4
0
def resize_icon(source, dest_folder, target_sizes, **kw):
    """Resizes addon icons."""
    log.info('[1@None] Resizing icon: %s' % dest_folder)
    try:
        # Resize in every size we want.
        dest_file = None
        for size in target_sizes:
            dest_file = '%s-%s.png' % (dest_folder, size)
            resize_image(source, dest_file, (size, size))

        # Store the original hash, we'll return it to update the corresponding
        # add-on. We only care about the first 8 chars of the md5, it's
        # unlikely a new icon on the same add-on would get the same first 8
        # chars, especially with icon changes being so rare in the first place.
        with open(source, 'rb') as fd:
            icon_hash = hashlib.md5(fd.read()).hexdigest()[:8]

        # Keep a copy of the original image.
        dest_file = '%s-original.png' % dest_folder
        os.rename(source, dest_file)

        return {
            'icon_hash': icon_hash
        }
    except Exception as e:
        log.error("Error saving addon icon (%s): %s" % (dest_file, e))
Esempio n. 5
0
def resize_icon(src, dst, locally=False, **kw):
    """Resizes collection icons to 32x32"""
    log.info('[1@None] Resizing icon: %s' % dst)

    try:
        resize_image(src, dst, (32, 32), locally=locally)
        return True
    except Exception, e:
        log.error("Error saving collection icon: %s" % e)
Esempio n. 6
0
def resize_photo(src, dst, locally=False, **kw):
    """Resizes userpics to 200x200"""
    task_log.info('[1@None] Resizing photo: %s' % dst)

    try:
        resize_image(src, dst, (200, 200))
        return True
    except Exception as e:
        task_log.error('Error saving userpic: %s' % e)
Esempio n. 7
0
def resize_photo(src, dst, locally=False, **kw):
    """Resizes userpics to 200x200"""
    task_log.debug('[1@None] Resizing photo: %s' % dst)

    try:
        resize_image(src, dst, (200, 200))
        return True
    except Exception, e:
        task_log.error("Error saving userpic: %s" % e)
Esempio n. 8
0
def resize_icon(src, dst, locally=False, **kw):
    """Resizes collection icons to 32x32"""
    log.info('[1@None] Resizing icon: %s' % dst)

    try:
        resize_image(src, dst, (32, 32), locally=locally)
        return True
    except Exception, e:
        log.error("Error saving collection icon: %s" % e)
Esempio n. 9
0
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)

        size_thumb = (150, 120)
        size_full = (960, 640)

        with tempfile.NamedTemporaryFile(dir=settings.TMP_PATH) as tmp:
            resize_image(obj.custom_image.path, tmp.name, size_thumb, 'jpg')
            copy_stored_file(tmp.name, obj.thumbnail_path)

        with tempfile.NamedTemporaryFile(dir=settings.TMP_PATH) as tmp:
            resize_image(obj.custom_image.path, tmp.name, size_full, 'jpg')
            copy_stored_file(tmp.name, obj.custom_image.path)
Esempio n. 10
0
def resize_preview(src, instance, **kw):
    """Resizes preview images and stores the sizes on the preview."""
    thumb_dst, full_dst = instance.thumbnail_path, instance.image_path
    sizes = {}
    log.info("[1@None] Resizing preview and storing size: %s" % thumb_dst)
    try:
        sizes["thumbnail"] = resize_image(src, thumb_dst, amo.ADDON_PREVIEW_SIZES[0], remove_src=False)
        sizes["image"] = resize_image(src, full_dst, amo.ADDON_PREVIEW_SIZES[1], remove_src=False)
        instance.sizes = sizes
        instance.save()
        return True
    except Exception, e:
        log.error("Error saving preview: %s" % e)
Esempio n. 11
0
def test_resize_transparency():
    src = os.path.join(settings.ROOT, 'src', 'olympia', 'amo', 'tests',
                       'images', 'transparent.png')
    dest = tempfile.mkstemp(dir=settings.TMP_PATH)[1]
    expected = src.replace('.png', '-expected.png')
    try:
        resize_image(src, dest, (32, 32))
        with open(dest) as dfh:
            with open(expected) as efh:
                assert dfh.read() == efh.read()
    finally:
        if os.path.exists(dest):
            os.remove(dest)
Esempio n. 12
0
def test_resize_transparency():
    src = os.path.join(
        settings.ROOT, 'src', 'olympia', 'amo', 'tests',
        'images', 'transparent.png')
    dest = tempfile.mkstemp(dir=settings.TMP_PATH)[1]
    expected = src.replace('.png', '-expected.png')
    try:
        resize_image(src, dest, (32, 32), remove_src=False, locally=True)
        with open(dest) as dfh:
            with open(expected) as efh:
                assert dfh.read() == efh.read()
    finally:
        if os.path.exists(dest):
            os.remove(dest)
Esempio n. 13
0
def resize_icon(src, dst, size, locally=False, **kw):
    """Resizes addon icons."""
    log.info("[1@None] Resizing icon: %s" % dst)
    try:
        if isinstance(size, list):
            for s in size:
                resize_image(src, "%s-%s.png" % (dst, s), (s, s), remove_src=False, locally=locally)
            if locally:
                os.remove(src)
            else:
                storage.delete(src)
        else:
            resize_image(src, dst, (size, size), remove_src=True, locally=locally)
        return True
    except Exception, e:
        log.error("Error saving addon icon: %s" % e)
Esempio n. 14
0
def test_resize_image_from_svg():
    src_folder = os.path.join(settings.ROOT, 'src', 'olympia', 'versions',
                              'tests', 'static_themes')
    src = os.path.join(src_folder, 'weta_theme_full.svg')
    expected = os.path.join(src_folder, 'weta_theme_full.jpg')
    tmp_file_name = get_temp_filename()
    try:
        resize_image(src, tmp_file_name, (680, 92), format='jpg')
        with open(tmp_file_name, 'rb') as dfh:
            with open(expected, 'rb') as efh:
                dd = dfh.read()
                ee = efh.read()
                assert len(dd) == len(ee) and dd == ee
    finally:
        if os.path.exists(tmp_file_name):
            os.remove(tmp_file_name)
Esempio n. 15
0
def test_resize_transparency_for_P_mode_bug_1181221():
    # We had a monkeypatch that was added in
    # https://github.com/jbalogh/zamboni/commit/10340af6d1a64a16f4b9cade9faa69976b5b6da5  # noqa
    # which caused the issue in bug 1181221. Since then we upgraded Pillow, and
    # we don't need it anymore. We thus don't have this issue anymore.
    src = os.path.join(settings.ROOT, 'src', 'olympia', 'amo', 'tests',
                       'images', 'icon64.png')
    dest = tempfile.mkstemp(dir=settings.TMP_PATH)[1]
    expected = src.replace('.png', '-expected.png')
    try:
        resize_image(src, dest, (32, 32))
        with open(dest) as dfh:
            with open(expected) as efh:
                assert dfh.read() == efh.read()
    finally:
        if os.path.exists(dest):
            os.remove(dest)
Esempio n. 16
0
def resize_preview(src, instance, **kw):
    """Resizes preview images and stores the sizes on the preview."""
    thumb_dst, full_dst = instance.thumbnail_path, instance.image_path
    sizes = {}
    log.info('[1@None] Resizing preview and storing size: %s' % thumb_dst)
    try:
        sizes['thumbnail'] = resize_image(src, thumb_dst,
                                          amo.ADDON_PREVIEW_SIZES[0],
                                          remove_src=False)
        sizes['image'] = resize_image(src, full_dst,
                                      amo.ADDON_PREVIEW_SIZES[1],
                                      remove_src=False)
        instance.sizes = sizes
        instance.save()
        return True
    except Exception, e:
        log.error("Error saving preview: %s" % e)
Esempio n. 17
0
def resize_icon(src, dst, size, locally=False, **kw):
    """Resizes addon icons."""
    log.info('[1@None] Resizing icon: %s' % dst)
    try:
        if isinstance(size, list):
            for s in size:
                resize_image(src, '%s-%s.png' % (dst, s), (s, s),
                             remove_src=False, locally=locally)
            if locally:
                os.remove(src)
            else:
                storage.delete(src)
        else:
            resize_image(src, dst, (size, size), remove_src=True,
                         locally=locally)
        return True
    except Exception, e:
        log.error("Error saving addon icon: %s" % e)
Esempio n. 18
0
def test_resize_transparency_for_P_mode_bug_1181221():
    # We had a monkeypatch that was added in
    # https://github.com/jbalogh/zamboni/commit/10340af6d1a64a16f4b9cade9faa69976b5b6da5  # noqa
    # which caused the issue in bug 1181221. Since then we upgraded Pillow, and
    # we don't need it anymore. We thus don't have this issue anymore.
    src = os.path.join(
        settings.ROOT, 'src', 'olympia', 'amo', 'tests',
        'images', 'icon64.png')
    dest = tempfile.mkstemp(dir=settings.TMP_PATH)[1]
    expected = src.replace('.png', '-expected.png')
    try:
        resize_image(src, dest, (32, 32), remove_src=False, locally=True)
        with open(dest) as dfh:
            with open(expected) as efh:
                assert dfh.read() == efh.read()
    finally:
        if os.path.exists(dest):
            os.remove(dest)
Esempio n. 19
0
def resize_preview(src, preview_pk, **kw):
    """Resizes preview images and stores the sizes on the preview."""
    preview = Preview.objects.get(pk=preview_pk)
    thumb_dst, full_dst, orig_dst = (
        preview.thumbnail_path, preview.image_path, preview.original_path)
    sizes = {}
    log.info('[1@None] Resizing preview and storing size: %s' % thumb_dst)
    try:
        (sizes['thumbnail'], sizes['original']) = resize_image(
            src, thumb_dst, amo.ADDON_PREVIEW_SIZES['thumb'])
        (sizes['image'], _) = resize_image(
            src, full_dst, amo.ADDON_PREVIEW_SIZES['full'])
        if not os.path.exists(os.path.dirname(orig_dst)):
            os.makedirs(os.path.dirname(orig_dst))
        os.rename(src, orig_dst)
        preview.sizes = sizes
        preview.save()
        return True
    except Exception as e:
        log.error("Error saving preview: %s" % e)
Esempio n. 20
0
def _recreate_images_for_preview(preview):
    log.info('Resizing preview: %s' % preview.id)
    try:
        preview.sizes = {}
        if storage.exists(preview.original_path):
            # We have an original size image, so we can resize that.
            src = preview.original_path
            preview.sizes['image'], preview.sizes['original'] = resize_image(
                src, preview.image_path, amo.ADDON_PREVIEW_SIZES['full'])
            preview.sizes['thumbnail'], _ = resize_image(
                src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb'])
        else:
            # Otherwise we can't create a new sized full image, but can
            # use it for a new thumbnail
            src = preview.image_path
            preview.sizes['thumbnail'], preview.sizes['image'] = resize_image(
                src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb'])
        preview.save()
        return True
    except Exception as e:
        log.exception("Error saving preview: %s" % e)
Esempio n. 21
0
def _recreate_images_for_preview(preview):
    log.info('Resizing preview: %s' % preview.id)
    try:
        if not preview.sizes:
            preview.sizes = {}
        if storage.exists(preview.original_path):
            # We have an original size image, so we can resize that.
            src = preview.original_path
            preview.sizes['image'], _ = resize_image(
                src, preview.image_path, amo.ADDON_PREVIEW_SIZES['full'])
        else:
            # Otherwise we can't create a new sized full image, but can
            # use it for a new thumbnail
            src = preview.image_path
        # But we should resize the thumbnail regardless.
        preview.sizes['thumbnail'], _ = resize_image(
            src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb'])
        preview.save()
        return True
    except Exception as e:
        log.exception("Error saving preview: %s" % e)
Esempio n. 22
0
def resize_preview(src, instance, **kw):
    """Resizes preview images and stores the sizes on the preview."""
    thumb_dst, full_dst, orig_dst = (instance.thumbnail_path,
                                     instance.image_path,
                                     instance.original_path)
    sizes = {}
    log.info('[1@None] Resizing preview and storing size: %s' % thumb_dst)
    try:
        (sizes['thumbnail'],
         sizes['original']) = resize_image(src, thumb_dst,
                                           amo.ADDON_PREVIEW_SIZES[0])
        (sizes['image'], _) = resize_image(src, full_dst,
                                           amo.ADDON_PREVIEW_SIZES[1])
        if not os.path.exists(os.path.dirname(orig_dst)):
            os.makedirs(os.path.dirname(orig_dst))
        os.rename(src, orig_dst)
        instance.sizes = sizes
        instance.save()
        return True
    except Exception, e:
        log.error("Error saving preview: %s" % e)
Esempio n. 23
0
def generate_static_theme_preview(theme_manifest, header_root, preview):
    tmpl = loader.get_template(
        'devhub/addons/includes/static_theme_preview_svg.xml')
    context = {'amo': amo}
    context.update({
        process_color_value(prop, color)
        for prop, color in theme_manifest.get('colors', {}).items()
    })
    images_dict = theme_manifest.get('images', {})
    header_url = images_dict.get('headerURL',
                                 images_dict.get('theme_frame', ''))

    header_src, header_width, header_height = encode_header_image(
        os.path.join(header_root, header_url))
    meet_or_slice = ('meet' if header_width < amo.THEME_PREVIEW_SIZE.width else
                     'slice')
    preserve_aspect_ratio = '%s %s' % ('xMaxYMin', meet_or_slice)
    context.update(header_src=header_src,
                   header_src_height=header_height,
                   preserve_aspect_ratio=preserve_aspect_ratio)

    # Limit the srcs rendered to 15 to ameliorate DOSing somewhat.
    # https://bugzilla.mozilla.org/show_bug.cgi?id=1435191 for background.
    additional_srcs = images_dict.get('additional_backgrounds', [])[:15]
    additional_alignments = (theme_manifest.get('properties', {}).get(
        'additional_backgrounds_alignment', []))
    additional_tiling = (theme_manifest.get('properties', {}).get(
        'additional_backgrounds_tiling', []))
    additional_backgrounds = [
        AdditionalBackground(path, alignment, tiling, header_root)
        for (path, alignment, tiling) in izip_longest(
            additional_srcs, additional_alignments, additional_tiling)
        if path is not None
    ]
    context.update(additional_backgrounds=additional_backgrounds)

    svg = tmpl.render(context).encode('utf-8')
    image_size = write_svg_to_png(svg, preview.image_path)
    if image_size:
        pngcrush_image(preview.image_path)
        sizes = {
            # We mimic what resize_preview() does, but in our case, 'image'
            # dimensions are not amo.ADDON_PREVIEW_SIZES[1] but something
            # specific to static themes automatic preview.
            'image':
            image_size,
            'thumbnail':
            resize_image(preview.image_path, preview.thumbnail_path,
                         amo.ADDON_PREVIEW_SIZES[0])[0]
        }
        preview.update(sizes=sizes)