设置 base64 图像的大小 javascript - angularjs
set size of a base64 image javascript - angularjs
我看了很多答案,但我没有找到好的解决方案:
我的 $scope.file = /9j/4VeIRXhpZgAASUkqAAgAAAAL [..] 里有一张照片
它的大小是 5217984 = 5 MB
但是这张图片太大了,我的 angular aplication/web 服务不支持。
我该怎么办?如何?
我正在尝试将这个 5 MB 的图像转换为 500 KB 的图像,但我没有成功。任何人都可以帮助我吗?
我不知道这是否可行,但我需要 javascript 中的一个函数来将 5MB 的图像转换为 500 KB 的图像,例如,我可以将其放大。
当我放一张 500 KB 的图片作为示例时,它在我的应用程序中的一切都是正确的。
var $scope.getData= function () {
var reader = new FileReader();
reader.onload = $('input[type=file]')[0].files;
var img = new Image();
img.src =(reader.onload[0].result);
img.onload = function() {
if(this.width > 640)
{
//Get resized image
img= imageToDataUri(this, 640, 480);
}
}
};
//Resize the image (in the example 640 x 480px)
function imageToDataUri(img, width, height) {
// create an off-screen canvas
const canvas = document.createElement('canvas'),
const 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();
}
如果您有权访问编码的 base64,只需使用此函数:
$scope.getFileSize = function (base64encoded) {
try {
var encodedString = base64encoded.split(',')[1]
} catch (errorMsg) {
return false;
}
var decodedBase64 = atob(encodedString);
return decodedBase64.length;
};
我看了很多答案,但我没有找到好的解决方案:
我的 $scope.file = /9j/4VeIRXhpZgAASUkqAAgAAAAL [..] 里有一张照片 它的大小是 5217984 = 5 MB
但是这张图片太大了,我的 angular aplication/web 服务不支持。
我该怎么办?如何?
我正在尝试将这个 5 MB 的图像转换为 500 KB 的图像,但我没有成功。任何人都可以帮助我吗?
我不知道这是否可行,但我需要 javascript 中的一个函数来将 5MB 的图像转换为 500 KB 的图像,例如,我可以将其放大。
当我放一张 500 KB 的图片作为示例时,它在我的应用程序中的一切都是正确的。
var $scope.getData= function () {
var reader = new FileReader();
reader.onload = $('input[type=file]')[0].files;
var img = new Image();
img.src =(reader.onload[0].result);
img.onload = function() {
if(this.width > 640)
{
//Get resized image
img= imageToDataUri(this, 640, 480);
}
}
};
//Resize the image (in the example 640 x 480px)
function imageToDataUri(img, width, height) {
// create an off-screen canvas
const canvas = document.createElement('canvas'),
const 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();
}
如果您有权访问编码的 base64,只需使用此函数:
$scope.getFileSize = function (base64encoded) {
try {
var encodedString = base64encoded.split(',')[1]
} catch (errorMsg) {
return false;
}
var decodedBase64 = atob(encodedString);
return decodedBase64.length;
};