JPEG Encoding in Native Unity JavaScript

A few months ago someone posted to the Unity forums about how to encode a JPEG file without writing to disk.  It piqued my curiosity, so I poked at it.  It turned out that the required .NET libraries aren’t available in Unity (likely for size reasons, but maybe it’s a Mono thing). Bummer.

Native Encoding

The solution to this problem is to implement a JPEG encoder in native C# or JavaScript in Unity.  The other day I saw someone link to a browser JavaScript implementation of JPEG encoding, which was based off the as3corelib implementation from Flash.  Eureka!  It looked like an easy port, and an interesting exercise, so I went ahead and brought it over Unity JavaScript.

Using the JPEG Encoder

Usage is quite simple:

// spin up the JPEG encoder
var encoder:JPGEncoder = new JPGEncoder(texture, 75.0);

// encoder is threaded; wait for it to finish

// do something with bytes (like WWW upload or save to disk)
var bytes:byte[] = encoder.GetBytes();

The encoder is threaded, so the calling script needs to yield until it’s complete. Warning: We have never actually used threads in Unity; this might totally blow up in your face! If that’s the case it’d be easy to pseudo-thread it with a few yield statements (or just run it straight in circumstances where a frame hitch isn’t a big deal–capture the screen and hold on to the image bits until the player is at a good static GUI screen or something).

Possible Uses

Why would you want such a thing? Perhaps you want to allow the player to take screenshots from a standalone build, saved to disk. Or perhaps you want to upload images to your server (Unity has an EncodeToPNG function, but they can be quite large for network transmission). Splume, one of our first Unity games, had a level editor that simply uploaded game screenshots as thumbnails:

Splume 1 Splume 2

We also uploaded screenshots when something big would happen, like a huge scoring combo.

Download the Encoder and Sample Project

Download a simple project that takes screenshots and outputs .JPG files. Just drop JPGEncoder.js into your own projects to use native JPEG encoding. Enjoy!

This entry was posted in Scripts. Bookmark the permalink.

One Response to JPEG Encoding in Native Unity JavaScript

  1. Mike says:

    Thanks, converting it to C# and checking whether this is helps my image uploading problems.
    Best regards!

Comments are closed.