Daniele Olivieri

3D Digital Artist & Unity Developer

Unity, convert images in JPG

Hello guys!

today I want to share with you the code I use to compress in JPEG the screenshots taken during the game.

You probably already know how to take a screenshot, using “Application.CaptureScreenshot(..)” or Texture2D.ReadPixels(…)”,

in both cases the screenshot will be stored in PNG format, that it’s great but it could be a problem if you want to share it because of its large size.

I found the code online and thought that it might help some of you, so now here is the code of JPEGEncoder.js for Unity:

Download JPGEncoder.js

Download

Here is an example how to use the encoder (included):

function ScreenshotEncode()
{
    // wait for graphics to render
    yield WaitForEndOfFrame();

    // create a texture to pass to encoding
    var texture:Texture2D = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);

    // put buffer into texture
    texture.ReadPixels(Rect(0.0, 0.0, Screen.width, Screen.height), 0.0, 0.0);
    texture.Apply();

    // split the process up--ReadPixels() and the GetPixels() call inside of the encoder are both pretty heavy
    yield;

    // create our encoder for this texture
    var encoder:JPGEncoder = new JPGEncoder(texture, 75.0);

    // encoder is threaded; wait for it to finish
    while(!encoder.isDone)
        yield;

    // save our test image (could also upload to WWW)
    File.WriteAllBytes(Application.dataPath + "/../testscreen-" + count + ".jpg", encoder.GetBytes());
    count++;
}

Next Post

Previous Post

1 Comment

  1. id0 8 August 2015

    Great, and good quality, thank you!

Leave a Reply

© 2024 Daniele Olivieri

Theme by Anders Norén