Glitch Avatar Upater

May 18th 16

I was bored with my Twitter avatar and wanted to make it more interesting. To keep it fresh, I wanted it to be constantly changing so I decided to glitch my profile picture.

I used the glitch-canvas library to transform my image like this:

Glitched avatar

Using the canvas means that we can easily copy to base64 to upload to the Twitter API.

For the express server to accept the large request we need to increase the parser’s limit:

app.use(bodyParser.json(limit: "50mb”))

The post request receives the encoded image, removes the unnecessary prefix data and sends to Twitter:

app.post "/avatar", (req, res) ->

  b64Original = req.body.b64

  b64 = b64Original.replace(/^data:image\/png;base64,/, "")

  T.post "account/update_profile_image", image: b64, (err, data) ->

Client-side, we setup our canvas element and load the profile image. Once loaded we can transform using the glitch effect and then convert to base64 and post to the server:

$canvas = $("canvas")

canvas = $canvas[0]

ctx = canvas.getContext("2d")

img = new Image()

img.onload= ->

  canvas.width = 1600

  canvas.height = 1600

  ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, 1600, 1600)

  imgData = ctx.getImageData(0, 0, canvas.clientWidth, canvas.clientHeight)

  params =

    amount: random(1, 20)

    seed: random(1, 20)

    iterations: random(1, 20)

    quality: 100

  drawGlitchedImageData = (imgData) ->

    ctx.putImageData(imgData, 0, 0)

    b64 = canvas.toDataURL()

    upload(b64)

  glitch(imgData, params, drawGlitchedImageData)



img.src="images/profile.jpg"



upload = (data) ->

  params =

    b64: data

  $.ajax(

    type: "POST",

    url: "/avatar",

    contentType: "application/json"

    dataType: "json"

    data: JSON.stringify(params)

  ).done (data) ->

    bg()



random = (min, max) ->

  Math.floor(Math.random() * (max - min + 1)) + min

Glitch collection

Source is available here

Gulp and Metalsmith Blog

Next