我在离子应用程序中使用Camera插件获取了图像。我想限制用户选择用户所选图像的大小,比方说200kb。我添加了Camera as File插件。
我使用了以下代码:
/*Function to get image from gallery*/
$scope.getImageFromGallery = function(){
var options = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
targetWidth: 450,
targetHeight: 450,
encodingType: Camera.EncodingType.JPEG,
};
navigator.camera.getPicture(gallerySuccess, galleryError, options);
function gallerySuccess(imageURI){
getSize(imageURI);
}
function getSize(fileUri) {
window.resolveLocalFileSystemURL(fileUri, function(fileEntry){
fileEntry.getMetadata(function(metadata){
console.log("size is "+metadata.size);
}, resOnError);
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var imgData = evt.target.result;
var res = imgData.split(",");
$rootScope.imagebase64 = res[1];
var image = document.getElementById('preview-image1');
image.src = evt.target.result;
$('#preview-image').css('display','block');
$('#preview-image').css('background-image', "url("+res[1]+")").show();
};
reader.readAsDataURL(file);
}, resOnError);
},
resOnError);
}
function resOnError(error) {
console.log("error "+JSON.stringify(error));
}
function galleryError(error) {
}
}
但是在这里,当我选择2.5MB的图像时,它显示的是178908的大小 当我选择尺寸为8.9MB的图像时,显示的尺寸为88412。
据我所知,文件大小以字节为单位,但我得到的值不正确。
答案 0 :(得分:1)
试试这个解决方案这对你来说只需150kb就可以改成200kb
window.resolveLocalFileSystemURI(newPath, function (fileEntry) {
fileEntry.file(function (fileObj) {
if (fileObj.size <= 153600) {
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
//your stuff.....
};
reader.readAsDataURL(fileObj);
}
else {
// alert("Please upload image less then 150KB");
alertPopup = $ionicPopup.alert({
title: 'Upload image failed!',
template: 'Please upload image less then 150KB!'
});
}
console.log("Size = " + fileObj.size);
});
});