How to show a base64 string on a component

Hi all, may app requests to server for getting some information, one of them is an image as a base64 string. Actually, How to show it on a component without saving the base64 string as image.

https://docs.juce.com/master/classMemoryBlock.html#ae9b274b678bd4bdbfb64fec6c1c35e58
or
https://docs.juce.com/master/structBase64.html#a1d31c080284840a2c23ee41175e882ea
and
https://docs.juce.com/master/classImageFileFormat.html#a5a0d38a154faccbc0bbe245dadede62c
should do it for ya…

base64 string -> MemoryBlock::fromBase64Encoding() or Base64::convertFromBase64()
then feed that into ImageFileFormat::loadFrom(). if all goes well, you’ll get a juce::Image that you can draw in your component’s paint() call

void paint(Graphics& g) override
{
    g.drawImage( image );
}

Hi @matkatmusic
Why I created a base64 string then decoded it using Base64::convertFromBase64(), the function returned false. Here is my code:

String gImageBase64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAUlJREFUeNpiYBhM4O8OYQEQJkUPI5EGGwCpfiB2gApdAOJEZo+3FwjpZSLSIeuRDAcBA6gYA8UWAF3fAKQUsEgpQOXIDyJoeN8HYlzh/gGIFYFB9YFcH/TjMZwBKtdPlg+ArgeF+X64AAs/AyOfDpj5/91RdOWOQF8cINUH9SguARrOaLoRjAmpJWgB0PUJaKmGEHCA6iFsATRi68nIh/XYMiE2HxTgSJaEgAJUL24LgC4AKcqnoDTJh5qB0weEkiUhgJFsmdCSZQAVysQAqFmo+QAoeB5axlADXADmC0O4D6BJDL/hvDoMTMA8wIQ9H6ADA1iyZUIKe/yFFis/A4OQNQQTB8BmskDDi2DE/v/+mIHhbhdJEQ4ymxGarO7TqBJUZAJGxgMg4wANDD8AMhsWB4FUtuQA1EzU4hpalhhQIYl+oFtLBCDAAICzXaQ1P2u5AAAAAElFTkSuQmCC";
MemoryOutputStream mo;
auto result = Base64::convertFromBase64(mo, gImageBase64);

The result is always false.
What wrong here? :frowning:
I tested the base64 string using this website https://codebeautify.org/base64-to-image-converter

use ``` to format your code.

Also, look at the implementation of convertFromBase64 to see if you’re supposed to include the data:image/png;base64, part of your base64 string.

1 Like

Thank you @matkatmusic I can decode base64 now, just removed data:image/png;base64, from the string :slight_smile: