Avishai Peretz
Avishai Peretz

Reputation: 112

Cordova how to rotate a picture from camera

i take a picture with cordova camera plugin camera.getPicture() api

and get a base64 image how i rotate 90 right this base64 image and get new base64 string to save my code:

Camera.getPicture(options).then(function(imageURI) {
        var img = new Image();
        img.src = "data:image/png;base64," + imageURI;

        var rotate = false;

        if (img.width > img.height) {
            rotate = true;
        }

         uploadImage(imageURI, activeIndex, rotate);

    }, function(err) {
        console.log(err);
        $ionicLoading.hide();
    });

function to rotate the picture

 var rotateImage = function (base64ImageSrc) {
    var canvas = document.createElement('canvas');
    var img = new Image();
    img.src = base64ImageSrc;
    var context = canvas.getContext('2d');

    // translate context to center of canvas
    context.translate(canvas.width / 2, canvas.height / 2);

    // rotate 45 degrees clockwise
    context.rotate(Math.PI / 4);

    console.log(canvas.toDataURL());
    var ImageUrl = canvas.toDataURL();
    ImageUrl = ImageUrl.split("data:image/png;base64,");
    ImageUrl = ImageUrl[1];
    console.log(ImageUrl);
    return ImageUrl;
};

Upvotes: 3

Views: 3031

Answers (1)

Muhsin Keloth
Muhsin Keloth

Reputation: 7964

The image rotation can be achive by using a canvas,

function rotateBase64Image() {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext("2d");

        var image = new Image();
        image.src = base64data;
        image.onload = function() {
            ctx.translate(image.width, image.height);
            ctx.rotate(180 * Math.PI / 180);
            ctx.drawImage(image, 0, 0); 
            window.eval(""+callback+"('"+canvas.toDataURL()+"')");
        };

 }

base64data:A String containing the base64-encoded photo image[Orginal Image]

canvas.toDataURL(): Rotated image

Refer

Upvotes: 2

Related Questions