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.
Using the JPEG Encoder
Usage is quite simple:
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).
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:
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!