我在输入type =“file”filread =“uploadme.src”上使用此指令,现在最具挑战性的部分是首先将.ai / .pdf文件转换为.jpg / .png / .gif并调整它们并保存API中的base64文本。我需要解决方案来转换它们首先使用base64 Uri函数调整大小,如下面的代码所示。
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
};
}