Revision of Twine: storing images inside the HTML file from Mon, 01/14/2013 - 07:02

One aspect of Twine that I very much like is that the entire game is included in a single HTML file. It provides a great convenience and advantage for maintaining and archiving the game. Some Twine games include images in the text, and in most all cases there are in the form of hyperlinks to external image files, which, being separate from the game file, are vulnerable to being lost or broken.

There is a way to store image files (among other files) inside HTML using Base64 encoding, which converts binary files into streams of ASCII. Simply use an online Base64 encoder to convert your image into a Base64 data URI, and paste that wherever you would paste a URL to an image. This works not only for the HTML img tag, but also for Twine's img markup (although it probably won't be syntax-highlighted correctly in the passage editor).

Here is an example:
[img[data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAF4klEQVR4nO3dwY0cNxCGUcVhwBkoDQflMJyQnIlSkW+LVR+2QZPdVeT/HsCTAfcMu+o7DCTo2zcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAo8Nc/f/z66vz4+f3LU/35gQkCAMEEAIIJAAS7C8BoIKq/DzBAACCYAEAwAQA+rA6CQMBGBACCCQAEEwAINhsAPxLCxgQAggkABBMA4IMgQDABgGACAMEEAIIJAAQTAAgmABBMACDY7IKPnurvC3wiABBMACCYAAAfRgMwGpDq7wd8QQAgmABAMAFgK35kWksA2IoArCUAbEUA1hIAtiIAawkArfmDJ88SAFoTgGcJAK0JwLMEgNYE4FkCQCuzf/lEEL42usCj9y0ATBGAZwkArQnAswSA1gTgWQLAViz8nNGFnw2EALCUAMwRALYmAHMEgK0JwBwB4CjpC//3v3/+GjlvB0AQeJQACADBBEAACCYAAkCQ0390Gl3o6oWfDUL1fbMZARAAggmAABBMAASAYKMDWP15r1Yv+G4B6P5+aE4ABIBgAiAABBMAAWDC2wN4d+4+7+wApt1n9cILQHPVAyoAAiAAhaoHVAAEQAAKVQ+oAAiAACx09wIM5LPn9Pu9W+DZ/169P9tLH9Dqc/r9CkBz6QNafU6/XwFoLn1Aq8/p9ysADzOQe5/T7/fuL/OMHgG42H0gqwe0+px+vwLwsN0HsnpAq8/p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IBA4iABBMACCYAECwuwD4ERAOJgAQTAAgmABAkNEf+Sw8HEQAIJgAQDABgGCjP/IJABxEACCYAEAwAYBg/qAPBBMACCYAEEwAIJgf/SCYAEAwAYBgAgDBLDwEEwAIJgAQTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYH//AV586K7lksX7AAAAAElFTkSuQmCC]]

(If you paste the entire data URI between the braces into your browser URL bar, you can see the image.)

Some advantages:
- Stores all the game's resources in one file.
- Images are preloaded when the game starts.

Some disadvantages:
- Base64 encoding increases the size of the images by 33%.
- Can't easily use the same image file for multiple passages - each passage must have a full copy of the file. (You can work around this with some JavaScript preprocessing, if you really need to.)
- Doesn't work with IE versions < 9... go figure.