Javascript JIC-Java映像压缩器:无法执行';drawImage';在';CanvasRenderingContext2D';:未找到与签名匹配的函数
只是尝试使用JIC,但总是会遇到以下错误:Javascript JIC-Java映像压缩器:无法执行';drawImage';在';CanvasRenderingContext2D';:未找到与签名匹配的函数,javascript,angularjs,drawimage,image-compression,Javascript,Angularjs,Drawimage,Image Compression,只是尝试使用JIC,但总是会遇到以下错误: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature. 以下是我的代码: $scope.uploadJobImage = function($files){ //Images Objects var source_image = $files[0
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature.
以下是我的代码:
$scope.uploadJobImage = function($files){
//Images Objects
var source_image = $files[0],
target_img = $files[0];
console.log(source_image);
//(NOTE: see the examples/js/demo.js file to understand how this object could be a local image
//from your filesystem using the File API)
var output_format = {
resizeType : 'jpg',
resizeQuality : 80,
resizeMaxHeight : 456,
resizeMaxWidth : window.innerWidth,
};
target_img.src = jic.compress(source_image,output_format);
HTML视图:
<input type="file" ng-file-select="uploadJobImage($files)" class="upload" id="imgFle">
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(sourceImgObj, options){
console.log(sourceImgObj);
// var mime_type = "image/jpeg";
// if(typeof output_format !== "undefined" && output_format=="png"){
// mime_type = "image/png";
// }
// var cvs = document.createElement('canvas');
// cvs.width = source_img_obj.naturalWidth;
// cvs.height = source_img_obj.naturalHeight;
// var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
// var newImageData = cvs.toDataURL(mime_type, quality/100);
// var result_image_obj = new Image();
// result_image_obj.src = newImageData;
// return result_image_obj;
var outputFormat = options.resizeType;
var quality = options.resizeQuality * 100 || 70;
var mimeType = 'image/jpeg';
if (outputFormat !== undefined && outputFormat === 'png') {
mimeType = 'image/png';
}
var maxHeight = options.resizeMaxHeight || 300;
var maxWidth = options.resizeMaxWidth || 250;
var height = sourceImgObj.height;
var width = sourceImgObj.width;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
}
else {
if (height > maxHeight) {
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var cvs = document.createElement('canvas');
cvs.width = width; //sourceImgObj.naturalWidth;
cvs.height = height; //sourceImgObj.naturalHeight;
var ctx = cvs.getContext('2d').drawImage(sourceImgObj, 0, 0, width, height);
var newImageData = cvs.toDataURL(mimeType, quality / 100);
var resultImageObj = new Image();
resultImageObj.src = newImageData;
return resultImageObj.src;
},
/*!
* JIC JavaScript Library v1.1
* https://github.com/brunobar79/J-I-C/
*
* Copyright 2012, Bruno Barbieri
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Sat Mar 24 15:11:03 2012 -0200
*/
/**
* Create the jic object.
* @constructor
*/
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
// alert(source_img_obj.naturalWidth);
// alert(source_img_obj.naturalHeight);
console.log(source_img_obj);
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
console.log(newImageData);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
/**
* Receives an Image Object and upload it to the server via ajax
* @param {Image} compressed_img_obj The Compressed Image Object
* @param {String} The server side url to send the POST request
* @param {String} file_input_name The name of the input that the server will receive with the file
* @param {String} filename The name of the file that will be sent to the server
* @param {function} successCallback The callback to trigger when the upload is succesful.
* @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
* @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
* @param {Object} (OPTIONAL) customHeaders An object representing key-value properties to inject to the request header.
*/
upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){
var cvs = document.createElement('canvas');
cvs.width = compressed_img_obj.naturalWidth;
cvs.height = compressed_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
//ADD sendAsBinary compatibilty to older browsers
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
var type = "image/jpeg";
if(filename.substr(-4)==".png"){
type = "image/png";
}
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// Set custom request headers if customHeaders parameter is provided
if (customHeaders && typeof customHeaders === "object") {
for (var headerKey in customHeaders){
xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
}
}
// If a duringCallback function is set as a parameter, call that to notify about the upload progress
if (duringCallback && duringCallback instanceof Function) {
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
return (evt.loaded / evt.total)*100;
}
};
}
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
xhr.onreadystatechange = function() {
if (this.readyState == 4){
if (this.status == 200) {
successCallback(this.responseText);
}else if (this.status >= 400) {
if (errorCallback && errorCallback instanceof Function) {
errorCallback(this.responseText);
}
}
}
};
}
};
}
JIC压缩方法:
<input type="file" ng-file-select="uploadJobImage($files)" class="upload" id="imgFle">
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(sourceImgObj, options){
console.log(sourceImgObj);
// var mime_type = "image/jpeg";
// if(typeof output_format !== "undefined" && output_format=="png"){
// mime_type = "image/png";
// }
// var cvs = document.createElement('canvas');
// cvs.width = source_img_obj.naturalWidth;
// cvs.height = source_img_obj.naturalHeight;
// var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
// var newImageData = cvs.toDataURL(mime_type, quality/100);
// var result_image_obj = new Image();
// result_image_obj.src = newImageData;
// return result_image_obj;
var outputFormat = options.resizeType;
var quality = options.resizeQuality * 100 || 70;
var mimeType = 'image/jpeg';
if (outputFormat !== undefined && outputFormat === 'png') {
mimeType = 'image/png';
}
var maxHeight = options.resizeMaxHeight || 300;
var maxWidth = options.resizeMaxWidth || 250;
var height = sourceImgObj.height;
var width = sourceImgObj.width;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
}
else {
if (height > maxHeight) {
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var cvs = document.createElement('canvas');
cvs.width = width; //sourceImgObj.naturalWidth;
cvs.height = height; //sourceImgObj.naturalHeight;
var ctx = cvs.getContext('2d').drawImage(sourceImgObj, 0, 0, width, height);
var newImageData = cvs.toDataURL(mimeType, quality / 100);
var resultImageObj = new Image();
resultImageObj.src = newImageData;
return resultImageObj.src;
},
/*!
* JIC JavaScript Library v1.1
* https://github.com/brunobar79/J-I-C/
*
* Copyright 2012, Bruno Barbieri
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Sat Mar 24 15:11:03 2012 -0200
*/
/**
* Create the jic object.
* @constructor
*/
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
// alert(source_img_obj.naturalWidth);
// alert(source_img_obj.naturalHeight);
console.log(source_img_obj);
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
console.log(newImageData);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
/**
* Receives an Image Object and upload it to the server via ajax
* @param {Image} compressed_img_obj The Compressed Image Object
* @param {String} The server side url to send the POST request
* @param {String} file_input_name The name of the input that the server will receive with the file
* @param {String} filename The name of the file that will be sent to the server
* @param {function} successCallback The callback to trigger when the upload is succesful.
* @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
* @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
* @param {Object} (OPTIONAL) customHeaders An object representing key-value properties to inject to the request header.
*/
upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){
var cvs = document.createElement('canvas');
cvs.width = compressed_img_obj.naturalWidth;
cvs.height = compressed_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
//ADD sendAsBinary compatibilty to older browsers
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
var type = "image/jpeg";
if(filename.substr(-4)==".png"){
type = "image/png";
}
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// Set custom request headers if customHeaders parameter is provided
if (customHeaders && typeof customHeaders === "object") {
for (var headerKey in customHeaders){
xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
}
}
// If a duringCallback function is set as a parameter, call that to notify about the upload progress
if (duringCallback && duringCallback instanceof Function) {
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
return (evt.loaded / evt.total)*100;
}
};
}
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
xhr.onreadystatechange = function() {
if (this.readyState == 4){
if (this.status == 200) {
successCallback(this.responseText);
}else if (this.status >= 400) {
if (errorCallback && errorCallback instanceof Function) {
errorCallback(this.responseText);
}
}
}
};
}
};
非常感谢您在这方面的帮助。终于找到了问题所在,图像对象
source\u image
应该是dataURL base 64编码的图像格式,以便JIC正确处理。经过长时间的努力,解决了以下问题:
test.html文件
-为源图像和目标图像添加了两个div和一个文件选择器
<img src="" height="100%" align="middle" id="source_image">
<img src="" height="100%" align="middle" id="result_image">
<input type="file" ng-file-select="uploadJobImage($files)"
class="upload" id="imgFle">
2)使用Base 64编码
然后使用
$scope.convertImgToBase64URL(url,输出格式)使用base 64编码对其进行编码代码>方法:
代码:
<input type="file" ng-file-select="uploadJobImage($files)" class="upload" id="imgFle">
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(sourceImgObj, options){
console.log(sourceImgObj);
// var mime_type = "image/jpeg";
// if(typeof output_format !== "undefined" && output_format=="png"){
// mime_type = "image/png";
// }
// var cvs = document.createElement('canvas');
// cvs.width = source_img_obj.naturalWidth;
// cvs.height = source_img_obj.naturalHeight;
// var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
// var newImageData = cvs.toDataURL(mime_type, quality/100);
// var result_image_obj = new Image();
// result_image_obj.src = newImageData;
// return result_image_obj;
var outputFormat = options.resizeType;
var quality = options.resizeQuality * 100 || 70;
var mimeType = 'image/jpeg';
if (outputFormat !== undefined && outputFormat === 'png') {
mimeType = 'image/png';
}
var maxHeight = options.resizeMaxHeight || 300;
var maxWidth = options.resizeMaxWidth || 250;
var height = sourceImgObj.height;
var width = sourceImgObj.width;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
}
else {
if (height > maxHeight) {
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var cvs = document.createElement('canvas');
cvs.width = width; //sourceImgObj.naturalWidth;
cvs.height = height; //sourceImgObj.naturalHeight;
var ctx = cvs.getContext('2d').drawImage(sourceImgObj, 0, 0, width, height);
var newImageData = cvs.toDataURL(mimeType, quality / 100);
var resultImageObj = new Image();
resultImageObj.src = newImageData;
return resultImageObj.src;
},
/*!
* JIC JavaScript Library v1.1
* https://github.com/brunobar79/J-I-C/
*
* Copyright 2012, Bruno Barbieri
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Sat Mar 24 15:11:03 2012 -0200
*/
/**
* Create the jic object.
* @constructor
*/
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
// alert(source_img_obj.naturalWidth);
// alert(source_img_obj.naturalHeight);
console.log(source_img_obj);
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
console.log(newImageData);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
/**
* Receives an Image Object and upload it to the server via ajax
* @param {Image} compressed_img_obj The Compressed Image Object
* @param {String} The server side url to send the POST request
* @param {String} file_input_name The name of the input that the server will receive with the file
* @param {String} filename The name of the file that will be sent to the server
* @param {function} successCallback The callback to trigger when the upload is succesful.
* @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
* @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
* @param {Object} (OPTIONAL) customHeaders An object representing key-value properties to inject to the request header.
*/
upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){
var cvs = document.createElement('canvas');
cvs.width = compressed_img_obj.naturalWidth;
cvs.height = compressed_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
//ADD sendAsBinary compatibilty to older browsers
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
var type = "image/jpeg";
if(filename.substr(-4)==".png"){
type = "image/png";
}
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// Set custom request headers if customHeaders parameter is provided
if (customHeaders && typeof customHeaders === "object") {
for (var headerKey in customHeaders){
xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
}
}
// If a duringCallback function is set as a parameter, call that to notify about the upload progress
if (duringCallback && duringCallback instanceof Function) {
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
return (evt.loaded / evt.total)*100;
}
};
}
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
xhr.onreadystatechange = function() {
if (this.readyState == 4){
if (this.status == 200) {
successCallback(this.responseText);
}else if (this.status >= 400) {
if (errorCallback && errorCallback instanceof Function) {
errorCallback(this.responseText);
}
}
}
};
}
};
3)使用JIC压缩代码:
-在callback()
方法中,使用以下命令调用JIC图像压缩方法:result\u image.src=JIC.compress(source\u image,quality,'jpg').src代码>
代码:
<input type="file" ng-file-select="uploadJobImage($files)" class="upload" id="imgFle">
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(sourceImgObj, options){
console.log(sourceImgObj);
// var mime_type = "image/jpeg";
// if(typeof output_format !== "undefined" && output_format=="png"){
// mime_type = "image/png";
// }
// var cvs = document.createElement('canvas');
// cvs.width = source_img_obj.naturalWidth;
// cvs.height = source_img_obj.naturalHeight;
// var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
// var newImageData = cvs.toDataURL(mime_type, quality/100);
// var result_image_obj = new Image();
// result_image_obj.src = newImageData;
// return result_image_obj;
var outputFormat = options.resizeType;
var quality = options.resizeQuality * 100 || 70;
var mimeType = 'image/jpeg';
if (outputFormat !== undefined && outputFormat === 'png') {
mimeType = 'image/png';
}
var maxHeight = options.resizeMaxHeight || 300;
var maxWidth = options.resizeMaxWidth || 250;
var height = sourceImgObj.height;
var width = sourceImgObj.width;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
}
else {
if (height > maxHeight) {
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var cvs = document.createElement('canvas');
cvs.width = width; //sourceImgObj.naturalWidth;
cvs.height = height; //sourceImgObj.naturalHeight;
var ctx = cvs.getContext('2d').drawImage(sourceImgObj, 0, 0, width, height);
var newImageData = cvs.toDataURL(mimeType, quality / 100);
var resultImageObj = new Image();
resultImageObj.src = newImageData;
return resultImageObj.src;
},
/*!
* JIC JavaScript Library v1.1
* https://github.com/brunobar79/J-I-C/
*
* Copyright 2012, Bruno Barbieri
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Sat Mar 24 15:11:03 2012 -0200
*/
/**
* Create the jic object.
* @constructor
*/
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
// alert(source_img_obj.naturalWidth);
// alert(source_img_obj.naturalHeight);
console.log(source_img_obj);
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
console.log(newImageData);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
/**
* Receives an Image Object and upload it to the server via ajax
* @param {Image} compressed_img_obj The Compressed Image Object
* @param {String} The server side url to send the POST request
* @param {String} file_input_name The name of the input that the server will receive with the file
* @param {String} filename The name of the file that will be sent to the server
* @param {function} successCallback The callback to trigger when the upload is succesful.
* @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
* @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
* @param {Object} (OPTIONAL) customHeaders An object representing key-value properties to inject to the request header.
*/
upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){
var cvs = document.createElement('canvas');
cvs.width = compressed_img_obj.naturalWidth;
cvs.height = compressed_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
//ADD sendAsBinary compatibilty to older browsers
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
var type = "image/jpeg";
if(filename.substr(-4)==".png"){
type = "image/png";
}
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// Set custom request headers if customHeaders parameter is provided
if (customHeaders && typeof customHeaders === "object") {
for (var headerKey in customHeaders){
xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
}
}
// If a duringCallback function is set as a parameter, call that to notify about the upload progress
if (duringCallback && duringCallback instanceof Function) {
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
return (evt.loaded / evt.total)*100;
}
};
}
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
xhr.onreadystatechange = function() {
if (this.readyState == 4){
if (this.status == 200) {
successCallback(this.responseText);
}else if (this.status >= 400) {
if (errorCallback && errorCallback instanceof Function) {
errorCallback(this.responseText);
}
}
}
};
}
};
JIC开源映像压缩程序库:
<input type="file" ng-file-select="uploadJobImage($files)" class="upload" id="imgFle">
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(sourceImgObj, options){
console.log(sourceImgObj);
// var mime_type = "image/jpeg";
// if(typeof output_format !== "undefined" && output_format=="png"){
// mime_type = "image/png";
// }
// var cvs = document.createElement('canvas');
// cvs.width = source_img_obj.naturalWidth;
// cvs.height = source_img_obj.naturalHeight;
// var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
// var newImageData = cvs.toDataURL(mime_type, quality/100);
// var result_image_obj = new Image();
// result_image_obj.src = newImageData;
// return result_image_obj;
var outputFormat = options.resizeType;
var quality = options.resizeQuality * 100 || 70;
var mimeType = 'image/jpeg';
if (outputFormat !== undefined && outputFormat === 'png') {
mimeType = 'image/png';
}
var maxHeight = options.resizeMaxHeight || 300;
var maxWidth = options.resizeMaxWidth || 250;
var height = sourceImgObj.height;
var width = sourceImgObj.width;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
}
else {
if (height > maxHeight) {
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var cvs = document.createElement('canvas');
cvs.width = width; //sourceImgObj.naturalWidth;
cvs.height = height; //sourceImgObj.naturalHeight;
var ctx = cvs.getContext('2d').drawImage(sourceImgObj, 0, 0, width, height);
var newImageData = cvs.toDataURL(mimeType, quality / 100);
var resultImageObj = new Image();
resultImageObj.src = newImageData;
return resultImageObj.src;
},
/*!
* JIC JavaScript Library v1.1
* https://github.com/brunobar79/J-I-C/
*
* Copyright 2012, Bruno Barbieri
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Sat Mar 24 15:11:03 2012 -0200
*/
/**
* Create the jic object.
* @constructor
*/
var jic = {
/**
* Receives an Image Object (can be JPG OR PNG) and returns a new Image Object compressed
* @param {Image} source_img_obj The source Image Object
* @param {Integer} quality The output quality of Image Object
* @param {String} output format. Possible values are jpg and png
* @return {Image} result_image_obj The compressed Image Object
*/
compress: function(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement('canvas');
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
// alert(source_img_obj.naturalWidth);
// alert(source_img_obj.naturalHeight);
console.log(source_img_obj);
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
var newImageData = cvs.toDataURL(mime_type, quality/100);
console.log(newImageData);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
},
/**
* Receives an Image Object and upload it to the server via ajax
* @param {Image} compressed_img_obj The Compressed Image Object
* @param {String} The server side url to send the POST request
* @param {String} file_input_name The name of the input that the server will receive with the file
* @param {String} filename The name of the file that will be sent to the server
* @param {function} successCallback The callback to trigger when the upload is succesful.
* @param {function} (OPTIONAL) errorCallback The callback to trigger when the upload failed.
* @param {function} (OPTIONAL) duringCallback The callback called to be notified about the image's upload progress.
* @param {Object} (OPTIONAL) customHeaders An object representing key-value properties to inject to the request header.
*/
upload: function(compressed_img_obj, upload_url, file_input_name, filename, successCallback, errorCallback, duringCallback, customHeaders){
var cvs = document.createElement('canvas');
cvs.width = compressed_img_obj.naturalWidth;
cvs.height = compressed_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(compressed_img_obj, 0, 0);
//ADD sendAsBinary compatibilty to older browsers
if (XMLHttpRequest.prototype.sendAsBinary === undefined) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
var type = "image/jpeg";
if(filename.substr(-4)==".png"){
type = "image/png";
}
var data = cvs.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', upload_url, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// Set custom request headers if customHeaders parameter is provided
if (customHeaders && typeof customHeaders === "object") {
for (var headerKey in customHeaders){
xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
}
}
// If a duringCallback function is set as a parameter, call that to notify about the upload progress
if (duringCallback && duringCallback instanceof Function) {
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
return (evt.loaded / evt.total)*100;
}
};
}
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', atob(data), '--' + boundary + '--'].join('\r\n'));
xhr.onreadystatechange = function() {
if (this.readyState == 4){
if (this.status == 200) {
successCallback(this.responseText);
}else if (this.status >= 400) {
if (errorCallback && errorCallback instanceof Function) {
errorCallback(this.responseText);
}
}
}
};
}
};
但是这段代码在iPhone中仍然存在一些问题,iPhone中没有调用result_image.onload,但是调用了convertImgToBase64URL()的“img.onload”。无法理解此问题。您好!我陷入了同样的问题。我听了你的“图图”,但jic.compress给了我一个近乎空白的图像:你有什么线索可以解决这个问题吗?事实上,你在chrome上试过吗cos Safari当时不支持,我们使用blob而不是base 64格式。