Как просмотреть изображения в формате .ai, .pdf перед загрузкой и конвертировать в base64 в angularjs? - PullRequest
0 голосов
/ 05 июня 2018

Я использую эту директиву при вводетекст base64 в API.Мне нужно решение, чтобы сначала преобразовать их, изменив их размер с помощью функции URI base64, как показано в коде ниже.

app.directive("fileread", [function() {
    return {
        scope: {
            fileread: "=",
            fileName: '='
        },
        link: function(scope, element, attributes) {
            element.bind("change", function(changeEvent) {
                var file, name, reader, size, type;
                var reader = new FileReader();
                reader.onload = function(loadEvent) {
                    scope.fileName = {};
                    scope.$apply(function() {
                        var img = new Image();
                        img.src = (loadEvent.target.result);
                        img.onload = function() {
                            var size = calculateAspectRatioFit(this.width, this.height, 100, 100);
                            scope.fileName.size = "_" + size.width + "X" + size.height;
                            //Get resized image
                            scope.fileread = imageToDataUri(this, size.width, size.height);

                        }
                        scope.fileName.src = (loadEvent.target.result);
                        if (angular.isString(name)) {
                            return scope.fileName.name = name;
                        }
                    });
                }

                file = changeEvent.target.files[0];
                name = file.name;
                type = file.type;
                size = file.size;
                reader.readAsDataURL(file);

            });
        }
    }
}]);
//Resize the image (in the example 640 x 480px)
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;

    // draw source image into the off-screen canvas:
    ctx.drawImage(img, 0, 0, width, height);

    // encode image to data-uri with base64 version of compressed image
    return canvas.toDataURL();
}

function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return {
        width: srcWidth * ratio,
        height: srcHeight * ratio
    };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...