I am currently developing a mobile application that integrates with a Cordova plugin for sharing images on Instagram. The plugin requires the image input to be in either of two formats: a canvas ID or a base64 PNG dataUrl.
Since converting the image from JPG to PNG is not an ideal solution, especially for complex photo-like images where PNG files are significantly larger than JPGs, my approach is to attach the JPG to a canvas and then pass the canvas ID to the plugin function.
Here's a glimpse of my code:
HTML (utilizes AngularJS directives to switch between the original photo and the one transformed by the app's filter)
<div class="item item-image" ng-click="showOrig = !showOrig">
<img ng-src={{imgUrl}} ng-if="!showOrig" id="transformedImage">
<img ng-src={{imgUrlOrig}} ng-if="showOrig">
</div>
JavaScript / Angular controller
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
$scope.shareInstagram = function() {
Instagram
.share(getBase64Image(document.getElementById("transformedImage")), 'some caption', function(err) {
if (err) {
console.log('error: ', err);
} else {
console.log('Instagram share success.');
}
});
};
Unfortunately, this approach does not seem to work as expected. There are no visible errors in the console, and the function does not trigger upon tap/click.
If anyone has insights into why this might not be functioning properly, I would greatly appreciate some guidance.
Considering the lack of clarity in the documentation, it is possible that the canvas specifically requires a PNG image attached to it - meaning that passing a JPG may not suffice. In such a scenario, is there a method to convert the JPG to a PNG for compatibility?