Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created July 14, 2021 13:24
Show Gist options
  • Select an option

  • Save unitycoder/dcee65c3f33ebebfbd21146e63f202a9 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/dcee65c3f33ebebfbd21146e63f202a9 to your computer and use it in GitHub Desktop.
Download PNG file blob from webgl (without server)
// https://forum.unity.com/threads/user-image-download-from-in-webgl-app.474715/#post-3698248
[DllImport("__Internal")]
private static extern void DownloadFile(byte[] array, int byteLength, string fileName);
 
var texture = ScreenCapture.CaptureScreenshotAsTexture();
byte[] textureBytes = texture.EncodeToPNG();
DownloadFile(textureBytes, textureBytes.Length, "screenshot.png");
Destroy(texture);
// https://forum.unity.com/threads/user-image-download-from-in-webgl-app.474715/#post-3698248
DownloadFile : function(array, size, fileNamePtr)
{
    var fileName = UTF8ToString(fileNamePtr);
 
    var bytes = new Uint8Array(size);
    for (var i = 0; i < size; i++)
    {
       bytes[i] = HEAPU8[array + i];
    }
 
    var blob = new Blob([bytes]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
 
    var event = document.createEvent("MouseEvents");
    event.initMouseEvent("click");
    link.dispatchEvent(event);
    window.URL.revokeObjectURL(link.href);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment