Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image shrinks on converting to base64 in cordova ios iphone

I'm working on a cross platform cordova project which involves uploading images to a server and displaying them on the website. The code used for obtaining the resized image from the phone memory and get the base64 data is as follows:

var image = new Image();
image.src = URL;
image.onload = function () {

var canvas = document.createElement("canvas");
var img_width = this.width;
var img_height = this.height;
canvas.width =1000;
canvas.height = 1000;

var w=(1000/img_width);
var h=(1000/img_height);

var ctx = canvas.getContext("2d");
ctx.scale(w,h);
ctx.drawImage(this,0,0);                

var dataURL = canvas.toDataURL("image/png",1);

Here, the problem is that, the image width is set as the canvas width but the height isnt. Also, the code works perfectly on android devices and ipads, but the issue arises only on iphones.

Tested on Iphone 4s and 5c Can Anyone Please Help Me!!!!

The input image is:

Image from the phone

The image output on the canvas( as png file ) is:

enter image description here

like image 240
Mark Philip D'santos Avatar asked Nov 10 '22 16:11

Mark Philip D'santos


1 Answers

I was able to create a workaround for the issue in my case by modifying the answer provided in the following link to my needs as follows:

When scaling and drawing an image to canvas in iOS Safari, width is correct but height is squished

I tweaked the code a little, so it looks like this now:

    var image = new Image();
    image.src = URL;
    image.onload = function () {
        var canvas = document.createElement("canvas");
        var img_width = image.width;
        var img_height = image.height;


        canvas.width = 600;
        canvas.height = 600;
        var ctx = canvas.getContext("2d");


        var imgRatio;
        if (image.width > image.height) {
            imgRatio = image.width / image.height;
        } else {
            imgRatio = image.height / image.width;
        }


        var canRatio = canvas.width / canvas.height;

        var scaledWidth = image.width * (canvas.height / image.height);
        var scaledHeight;
        if (platformVersion.substring(0, 1) < 8) {
            scaledHeight = (image.height * (canvas.width / image.height)) * 2.1;
        } else {
            scaledHeight = (image.height * (canvas.width / image.height));
        }


        if (imgRatio > canRatio) {
            ctx.drawImage(image, 0, 0, canvas.width, scaledHeight);
        } else {
            ctx.drawImage(image, 0, 0, scaledWidth, canvas.height);
        }

        var dataURL = canvas.toDataURL("image/png", 1);
    }

Here depending on whether the os of the phone is from the cordova device plugin i multiply a value to the scaled height to compensate for the squishing effect.

like image 89
Mark Philip D'santos Avatar answered Nov 14 '22 23:11

Mark Philip D'santos