djangosnippets.org icon indicating copy to clipboard operation
djangosnippets.org copied to clipboard

WIP - feature #237 - twitter snippet

Open Gostich opened this issue 3 years ago • 3 comments

Gostich avatar Jun 05 '21 10:06 Gostich

@chriswedgwood I find out in the documentation of twitter that the image should have a ratio of 1:1 (reference https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/summary)

Images for this Card support an aspect ratio of 1:1 with minimum dimensions of 144x144 or maximum of 4096x4096 pixels.
Images must be less than 5MB in size. The image will be cropped to a square on all platforms.

I've been experimenting on change ´ImageFormatter´ of pygments and the first naive approach to change the size of snippet image generated with a ratio of 1:1. We need to figure out how to make image_pad so the padding is split between top and bottom (center the code in the image) and ensure minimum size of 144 and maximun size of 4096 is generated:

def twitter_img(request, snippet_id):
    snippet = get_object_or_404(Snippet, pk=snippet_id)
    response = HttpResponse(content_type='image/png')
    code_lines = snippet.code.splitlines()
    response.content = highlight(
        "\n".join(code_lines[:20]),
        snippet.language.get_lexer(),
        TwitterImageFormatter(linenos=True, image_pad=200)
    )
    return response


class TwitterImageFormatter(ImageFormatter):
    def get_style_defs(self, arg=''):
        super().get_style_defs(arg=arg)

    def _get_image_size(self, maxlinelength, maxlineno):
        width, height = super()._get_image_size(maxlinelength, maxlineno)
        if width != height:
            if width < height:
                width += height - width
            else:
                height += width - height
        return width, height

daniboygg avatar Jun 06 '21 15:06 daniboygg

@danigayosog thanks for this , yes this feels like the right way to go 👍

Let me implement this locally and test with https://ngrok.com/ and the https://cards-dev.twitter.com/validator

chriswedgwood avatar Jun 07 '21 08:06 chriswedgwood

Hey guys, I should have a bit time during the week to help but not today. I keep an eye here anyway.

Gostich avatar Jun 07 '21 09:06 Gostich