Botframework Data URI images

A quick botframework tip – you can include images in your message attachments by Data URI, not just by URL!

For example, constructing a message like this:

var reply = message.CreateReply("Here's a **datauri image attachment**");
reply.Attachments = new List<Attachment> {
    new Attachment()
    {
        ContentUrl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAAQABADAREAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAACAUH/8QAJhAAAQMDAwQCAwAAAAAAAAAAAQIDBQQGEQcIEgATISIUMRUjUf/EABYBAQEBAAAAAAAAAAAAAAAAAAMBBP/EAB8RAAICAQQDAAAAAAAAAAAAAAECAAMRBBITIiFB8P/aAAwDAQACEQMRAD8AubjdVbtj5cQFi3tX2lS/ka16Rko9pZqHHfklplgKAylJPNR/vEZPWyvTpUN7jMyK3M21fE03ZLuQ1Gmbyc0j1Dudq7o8RztXFzXEGtacZeQhxipKT7D9qcKUOQ+skfRWKrdqxj71HI4erHME97633Fc+pF10c64pIg7ll6CldoEcHEoTVL7fMZ9se2CPOekdkCiSjIYmLvYvMRdLQPXDG3FGSEzK1iKB4rYCnaan7oVwcCQCHVqGTkkeEefGOgbTtjccyW6sM4QAT//Z",
        ContentType = "image/jpg",
        Name = "datauri"
    }
};

Gives a response that looks like this:

botframework image data uri

The image is very blurry because the emulator forces all images to fit a predefined width; the image I’ve used is only 16×16, so has been massively stretched!

You can use a much larger image – the previous one is around 500 bytes and this next one is nearer 20kb:

botframework image data uri big

Pretty cool, huh? Make sure the Data URI you’re using is valid and correct, otherwise either the botframework will return an internal server error, or the emulator will break.

I’ve got this working with images over 140kb, so it’s certainly not limited by ye olde IE8’s 32kb limitation.

It is also supported across Skype desktop, Skype web, and Skype for Android:

datauri on skypes

Getting a Data URI

The easiest way to make sure you’re getting a valid Data URI is via the amazing Chrome devtools: visit a page with the image you want – in my example I’m using my twitter page – and open devtools (F12/ctrl+shift+I/cmd+shift+I/via the menu):

chrome dev tools - copy image as data uri

Open the Sources tab, then find the picture you want within the tree structure; once you’ve found it, right click and select “Copy image as Data URI”! Amazing. Easy. You can then paste this directly into the browser address bar to see the image rendered, then paste this in to your bot code, as above.

Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *