Reputation: 4962
I am able to get the image URI using Ionic Image Picker plugin:
this.imagePicker.getPictures(options).then((results) => {
for (var i = 0; i < results.length; i++) {
//below logs: 'Image URI: file:///Users/josh.0/Library/Developer/CoreSimulator/Devices/CC0FFBD2-EADF-4489-8F22-7948E0EFD261/data/Containers/Data/Application/2BC3C571-61B7-4EFF-A4D1-4D1F99F04EBC/tmp/cdv_photo_013.jpg'
console.log('Image URI: ' + results[i]);
}
}, (err) => { });
I need to get this image as a File, so I can upload it. I've tried doing the following, but it doesn't work:
this.imagePicker.getPictures(options).then((results) => {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
let base64Image = "data:image/jpeg;base64," + results[i];
fetch(base64Image)
.then(res => res.blob())
.then(blob => {
//Doesnt fire
console.log("Got blob")
const file = new File([blob], "image.png")
})
}
}, (err) => { });
How do I convert an image URI to file?
Upvotes: 2
Views: 7188
Reputation: 4962
Ionic really needs to improve their documentation. The documentation on the plugin in the docs is absolutely pathetic. Took me hours to figure this out on my own. Anyway, here it is:
getImage() {
const options = {
maximumImagesCount: 1,
width: 800,
height: 800,
quality: 100,
outputType: 1 //Set output type to 1 to get base64img
};
this.imagePicker.getPictures(options).then((results) => {
var files: File[] = [];
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
let blob = this.getBlob(results[i], ".jpg")
const file = new File([blob], "image.jpg")
//Do something with file like upload
}
}, (err) => { });
}
private getBlob(b64Data:string, contentType:string, sliceSize:number= 512) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
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;
}
Upvotes: 3
Reputation:
You need to get the file from the directory with AJAX. I use AngularJS and below is what I used to get the Blob. You can pretty much convert this to whatever JS framework/library you're using.
AngularJS method:
$http.get(file_uri, {'responseType':'blob'}).then(successMethod, failMethod);
Upvotes: 1