1

I'm trying to resize an image selected with the cordova.camera to save some data

function imageToDataUri(img, width, height) {
    // create an off-screen canvas
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    // set its dimension to target size
    canvas.width = width;
    canvas.height = height;
        var img1 = new Image;
        img.onload = function(){
          ctx.drawImage(img1, 0, 0, width, height);
        };
        img1.src = img;
    // draw source image into the off-screen canvas:            
        var newUrl = canvas.toDataURL('image/jpeg', 0.9);
        alert(img.length + ' optimizada' + newUrl.length);
    // encode image to data-uri with base64 version of compressed image
    return newUrl;
}
$('body').on('click','.takePicture',function(e){
     navigator.camera.getPicture(
        function (imageData) {
            var src =  imageToDataUri(imageData,1024,640);
            var uploadedImage = $('<img>').attr('src', src).attr('alt', 'imageeeeeee!');    
            $('.takePictureHolder div').html(uploadedImage);
            $('.takePictureHolder input').val(src);         
        },
        null,
        {
            correctOrientation: true,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.PHOTOLIBRARY
        }            
     );
});

The catching the photo part works the problem is that imageToDataUri generates a black image,

Any idea what I'm missing?

The alert for the picture I selected prompt 1137795 optimizada 14515

Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
  • You're not waiting for the image has loaded, nor drawn before getting the dataURL. Wrap it in the `onload` handler. – Kaiido Nov 01 '15 at 02:14
  • The answer on the other question has nothing to do with this question, you should resize the image using the own camera plugin options to resize the photo, with targetWidth and targetHeight params – jcesarmobile Nov 02 '15 at 19:50
  • @jcesarmobile the problem it that they both need to go together (with and height), and I don't want to change the aspect ratio of the image... can I still Do it with the camera options? (I just want to limit the width) – Toni Michel Caubet Nov 11 '15 at 14:27
  • the resize keeps the aspect ratio, so you can use a very big height and the desired width – jcesarmobile Nov 11 '15 at 15:25

0 Answers0