Convert R image to Base 64
I don't know exactly what you want to accomplish, but here is an example:
# save example plot to file
png(tf1 <- tempfile(fileext = ".png")); plot(0); dev.off()
# Base64-encode file
library(RCurl)
txt <- base64Encode(readBin(tf1, "raw", file.info(tf1)[1, "size"]), "txt")
# Create inline image, save & open html file in browser
html <- sprintf('<html><body><img src="data:image/png;base64,%s"></body></html>', txt)
cat(html, file = tf2 <- tempfile(fileext = ".html"))
browseURL(tf2)
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 Base64 to PNG/JPEG file in R
this works for me:
library(base64enc)
enc <- base64encode("images.jpg")
conn <- file("w.bin","wb")
writeBin(enc, conn)
close(conn)
inconn <- file("w.bin","rb")
outconn <- file("img2.jpg","wb")
base64decode(what=inconn, output=outconn)
close(inconn)
close(outconn)
images.jpg courtesy of Wikipedia accessed from here
How to convert a base64 string to a png file with R?
I've found a solution.
My base64 string:
mybase64 <- "data:image/png;base64,iVBORw0KGgoAAAANSU......"
Then:
raw <- base64enc::base64decode(what = substr(mybase64, 23, nchar(mybase64)))
png::writePNG(png::readPNG(raw), "mypng.png")
How can I convert an image into a Base64 string?
You can use the Base64 Android class:
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
You'll have to convert your image into a byte array though. Here's an example:
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();
* Update *
If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).
Check this article out for a workaround:
How to base64 encode decode Android
How to convert image data response to Image base64?
axios.get('RequestURL', { responseType: 'arraybuffer' })
.then(response => {
let blob = new Blob(
[response.data],
{ type: response.headers['content-type'] }
)
let image = window.URL.createObjectURL(blob)
return image
})
axios.get('RequestURL', {responseType: 'blob'})
.then(response => {
let imageNode = document.getElementById('image');
let imgUrl = URL.createObjectURL(response.data)
imageNode.src = imgUrl
})
How to convert R plot or ggplot2 to base64 string?
Save the ggplot:
ggsave("myggplot.png", plot)
Then use the base64enc
package as follows:
base64enc::dataURI(file = "myggplot.png", mime = "image/png")
Related Topics
Passing Along Ellipsis Arguments to Two Different Functions
Show Content for Menuitem When Menusubitems Exist in Shiny Dashboard
How to Access Dimensions of Labels Plotted by 'Geom_Text' in 'Ggplot2'
How to Calculate Adjacency Matrices in R
Replacing Values in a Column with Another Column R
Export Fitted Regression Splines (Constructed by 'Bs' or 'Ns') as Piecewise Polynomials
R: Web Scraping Yahoo.Finance After 2019 Change
Shiny - Checkbox in Table in Shiny
Reverse and Change Limit of Axis
How to Create a World Map in R with Specific Countries Filled In
Data.Table Package in R 3.5 Does Not Install
How to Use Ggplot2's Geom_Dotplot() with Both Fill and Group
How to Download and Display an Image from an Url in R
Different Colors for Each Bar in Stacked Bar Graph - Base Graphics
Explicitly Set Panel Size (Not Just Plot Size) in Ggplot2