Snippet · Mecha CMS

Code snippet collection for developers.

Inline Image to Base64 Converter

Author: Taufik Nurrohman · 373 Views

Tweet

Making simple online tool with Mecha.

Requires eval plugin.

Create a new page then add this content:

---
title: Image to Base64 Converter
description: Convert image file to base64 string.
type: HTML
...

<form action="" method="post" enctype="multipart/form-data">
  <p><input name="_image" type="file" class="input block"></p>
  <p><button type="submit" class="button">Convert</button></p>
</form>

[[e]]
if (!empty($_FILES['_image'])) {
    if ($_FILES['_image']['error'] > 0) {
        echo '<p style="color:red;">Error.</p>';
    } else if (strpos($_FILES['_image']['type'], 'image/') !== 0) {
        echo '<p style="color:red;">Images only!</p>';
    } else {
        $base64 = To::base64(file_get_contents($_FILES['_image']['tmp_name']));
        $base64 = From::html('data:' . $_FILES['_image']['type'] . ';base64,' . $base64);
        echo '<p><img alt="" onclick="window.open(this.src);" title="View URL" src="' . $base64 . '"></p>';
    }
}
[[/e]]

0 Comments

No comments yet.