How to Convert an Image to Base64 Encoding

How can I convert an image into Base64 string using JavaScript?

You can use the HTML5 <canvas> for it:

Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).

Convert image.jpg to Base64

This worked for me: https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp

I can't believe C++ doesn't have base64 functionality in the standard library!

#include <fstream>
#include <string>
#include "base64.h"

using namespace std;

int main()
{
string line;

ifstream input("test.jpg", ios::in | ios::binary);

ofstream output("text.txt");

if (input.is_open()) {

while (getline(input, line)) {

string encoded = base64_encode(reinterpret_cast<const unsigned char*>(line.c_str()), line.length());

output << encoded;
}

input.close();
}
}

How to encode a image in Python to Base64?

You can encode the RGB directly to jpg in memory and create a base64 encoding of this.

jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

Full example:

import cv2
import base64
img = cv2.imread('test_image.jpg')
jpg_img = cv2.imencode('.jpg', img)
b64_string = base64.b64encode(jpg_img[1]).decode('utf-8')

The base 64 string should be decodable with https://codebeautify.org/base64-to-image-converter

Convert Image to Base64 string

StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file1 = await storageFolder.GetFileAsync("Image.png");

string _b64 = Convert.ToBase64String(File.ReadAllBytes(file1.Path));

This worked for me.

How an image get converted by base64 algorithm?

Base64 isn't an image encoder, it's a byte encoder, important distinction. Whatever you pass it, whether it be a picture, an mp3, or the string "ilikepie" - it takes those bytes and generates a text representation of them. It has no understanding of anything in your pixels/dpi/ppi/1bit/8bit/24bit/Mime list, that would be the business of the software that reads those original bytes.

Per request I want an answer that describes the flow from when we save the image in our computer until it's become 64base string.

To get to a base64 representation:

  • Open paint and draw a smiley face.
  • Save that smiley face as smile.png
  • Paint uses its png encoder to convert the bitmap of pixels into a stream of bytes that it compresses and appends headers to so that when it sees those bytes again it knows how to display them.
  • Image is written to disk as series of bytes.
  • You run a base64 encoder on smile.png.
  • base64 reads the bytes from disk at the location smile.png refers to and converts their representation and displays the result.

To display that base64 representation in a browser:

  • browser is handed a resource encoded with base64, which looks something data:image/png;base64,blahblah...
  • Browser takes the image/png part and knows that the data following it will be the bytes of a png image.
  • It then sees base64, and knows that the next blob will need to be base64 decoded, before it can then be decoded by its png decoder.
  • It converts the base64 string to bytes.
  • It passes those bytes to its png decoder.
  • It gets a bitmap graphic that it can then display.

Way to convert image straight from URL to base64 without saving as a file in Python

Using the requests library:

import base64
import requests


def get_as_base64(url):

return base64.b64encode(requests.get(url).content)

How to convert simple R plot image to base64 encoding without reading/writing image file to disk first?

Your a object, as you identified, is not an actual plot, but the "raw data from the plot". Strictly speaking, it's a representation of what you want plotted, the mapping between variables and elements, and all the aesthetics (theme, colours, etc.). Try the following:

str(a, max.level=1)

(and increment max.level bit by bit).

When you view a in the console, R is actually calling print(a) - that's why you will not get the plot outputted if you just run a script from a command line where you try to output a plot by calling a by itself.

When calling print(a) (or indirectly from an interactive session), ggplot2 builds the plot by mapping the variables to the x- and y-axis, colours, maps out facets, etc. etc. The result of that is then drawn on a graphical device, either a plot window or a file. You can actually catch the graphical representation of this drawing with ggplotGrob and then further manipulate the actual drawing, before it is sent to the screen or file.

How does this help?

You need to use print(a) instead of directly encode a (as you have noticed).

I.e. to produce a base64-encoded plot, you can do:

library(base64enc)
## convert image to base64 encoded string

fn <- tempfile(fileext='.png')
png(fn)
print(a)
dev.off()

base64enc::base64encode(fn)

But: This does require you can write to temporary files. And to be honest, I have a hard time believing you are prevented from this.

And unfortunately, I am not aware of any graphical devices (png, bmp, etc.) were you can write directly to a memorystream or variable instead of a physical file.

Convert image from url to Base64

HTML

<img id="imageid" src="https://www.google.de/images/srpr/logo11w.png">

JavaScript

function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

var base64 = getBase64Image(document.getElementById("imageid"));

This method requires the canvas element, which is perfectly supported.

  • The MDN reference of HTMLCanvasElement.toDataURL().
  • And the official W3C documentation.

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");


Related Topics



Leave a reply



Submit