2016-03-02 3 views
3

У меня есть функция в моем приложении Angular 1.5, которое изменяет размер изображения с кодировкой base64, если оно превышает максимальный размер. Эта функция отлично работает в Chrome, но в Firefox она возвращает пустую строку вместо любого base64-кодированного.Изменение размера изображения работает в Chrome, но не в Firefox

I've got it packaged up in an Angular app in Plunker here, но вот соответствующая функция:

// Image resizing 
    $scope.resizeImage = function(base64Data, maxWidth, maxHeight) { 
    img = document.createElement('img'); 

    img.src = base64Data; 
    height = img.height; 
    width = img.width; 

    if (width > maxWidth) { 
     ratio = maxWidth/width; // get ratio for scaling image 
     height = height * ratio; // Reset height to match scaled image 
     width = width * ratio; // Reset width to match scaled image 
    } 

    // Check if current height is larger than max 
    if (height > maxHeight) { 
     ratio = maxHeight/height; // get ratio for scaling image 
     width = width * ratio; // Reset width to match scaled image 
     height = height * ratio; // Reset height to match scaled image 
    } 

    var canvas = document.createElement('canvas'); 
    var ctx = canvas.getContext('2d'); 

    // We set the dimensions at the wanted size. 
    canvas.width = width; 
    canvas.height = height; 

    // We resize the image with the canvas method drawImage(); 
    ctx.drawImage(img, 0, 0, width, height); 

    var dataURI = canvas.toDataURL(); 
    return dataURI; 
    } 

ответ

1

Возможно, вам придется подождать, пока не будет загружен <img>:

img.onload = function() { 
    // now your image is ready for use 
}; 
Смежные вопросы