Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Load the image file with std.file.read().

  2. 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;
    }
  3. Load the CSS file with std.file.readText.

  4. Use std.array.replace to replace the URL with the data URI.

  5. 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"); ...