I have a Base64 (encoded from image), and I want to convert it again into an image in Ionic. Is it possible? and is there any example for do this?
Thanks before
I have a Base64 (encoded from image), and I want to convert it again into an image in Ionic. Is it possible? and is there any example for do this?
Thanks before
I guess you mean like using the image as - just replace base64Value with the base 64 data.
Yes, do you have an example of that?
You can create a blob from image an then show it in [src] bind, I created a service that work on blob
@Injectable()
export class ImageHandlerProvider {
constructor () {
}
getBlob (b64Data) {
contentType = '';
sliceSize = 512;
b64Data = b64Data.replace(/data\:image\/(jpeg|jpg|png)\;base64\,/gi, '');
let byteCharacters = atob(b64Data);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
let blob = new Blob(byteArrays, {type: contentType});
return blob;
}
}
and in you component you can use it like:
let urlCreator = window.URL || window.webkitURL;
let dataBlob = this.imageHandlerProvider.getBlob(data);
let imageUrl = urlCreator.createObjectURL(dataBlob);
this.imageUrl = imageUrl;
<img [src]="imageUrl" alt="Image" />
You can check this codepen for more details.
I tried the variable
var data = 'data:image/png;base64,iVBORw0KG...'
But it says
Typescript Error: Unexpected token. A constructor, method, accessor, or property was expected.
And
var urlCreator = window.URL || window.webkitURL;
Property ‘webkitURL’ does not exist on type ‘Window’.
Do you have any solution?
I changed the variable become
private data = '/9j/4AAQSkZJRgABAQIAHAAcAAD/7RmQUGhvdG9zaG9w... //base64
and I give a comment to the window.webkitURL
There is no error in my code, but the result is only “Image” caption, below the result
In my case, I created a specific typescript file for base64:
export const SELFIE_PREVIEW_IMAGES = {
image1: 'base64FromImage'
}
And then imported it on my component page
import { SELFIE_PREVIEW_IMAGES } from './selfie-preview.images';
images;
constructor () {
this.images = SELFIE_PREVIEW_IMAGES;
}
And in html
<img [src]="images['image1']" alt="Image 1">
In your case, when you use getBlob()
function?
May I know the full context?
I use that for another reason, my server wants to receive a base64 but in device I get an image from file uri, so I need to convert this file url to base64 and blob to show it in page.