Using Base64 to create a data URI
Given a CSS file, we want to replace all instances of a particular image URL with a data URI to reduce the number of requests. Let's write a small D program to do this replacement.
How to do it…
Let's create a data URI by executing the following steps:
Load the image file with
std.file.read()
.Create the data URI with
std.base64
as shown in the following code:pure char[] makeDataUri(string contentType, in void[] data) { import std.base64; return "data:" ~ contentType ~ ";base64," ~ Base64.encode(cast(const(ubyte[]))) data; }
Load the CSS file with
std.file.readText
.Use
std.array.replace
to replace the URL with the data URI.Save the CSS file with
std.file.write
.
Putting it all together in main
, you will have the following code:
void main() { import std.file, std.array; auto imageData = std.file.read("image.png"); // step 1 string dataUri = makeDataUri("image/png", imageData); // step 2 auto cssFile = std.file.readText("style.css"); ...