客户端调整图像和使用画布发布 [英] Client side resize Image and posting using canvas
本文介绍了客户端调整图像和使用画布发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图实现客户端调整图像大小,然后将其发布到后端。我不太了解画布。
有9张图片,我必须同时上传。我需要做的是
I am trying to implement client side resizing of images and then posting them to backend. I dont know much about canvas. There are 9 images which I have to upload simultaneously. What I need to do is
- 首先检查每个图片是否符合我们的尺寸要求。
- 第二个减少其重量,所以上传不需要很多时间。
- 右键知道它需要很多时间。
-
我试图通过getImageData来实现它,并在blob中转换数据。
- first check for every image if that fits our size requirements.
- second decrease its weight so it does not take much time to upload.
- right know it is taking a lot of time.
I tried to implement this by getImageData and convert that data in blob.
function readURL(input){
var mtype = jQuery('input[name="format"]:checked').val();
var resizedImage = '';
if (input.files && input.files[0]) {
var filetype = input.files[0].type.split('/')[1];
if(allowedExt.indexOf(filetype) < 0){
alert("Ce format de photo n’est pas pris en charge. Seules les photos au format JPG sont acceptées. ");
return false;
}
var reader = new FileReader();
reader.onload = function (e){
var im = new Image();
im.src = e.target.result;
im.onload = function(){
var imgHeight = im.height;
var imgWidth = im.width;
var minWidth = minHeight = 1440;
var maxWidth = maxHeight = 3600;
var minSizeError = 'La taille de votre photo est inférieure au minimum requis qui est 1440px X 1440px';
var minRatioError = 'Votre photo ne correspond pas au ratio 1:1 – Veuillez la recadrer ou en sélectionner une autre.';
var aspectRatio = 1;
var previmWidth = 107;
var previmHeight = 107;
if(mtype == 'h'){
minWidth = 1920;
minHeight = 1280;
maxWidth = 4800;
maxHeight = 3200;
minSizeError = 'La taille de votre photo est inférieure au minimum requis qui est 1920px X 1280px';
minRatioError = 'Votre photo ne correspond pas au ratio 3:2 – Veuillez la recadrer ou en sélectionner une autre.';
aspectRatio = 1.5;
previmWidth = 140;
}
if(imgWidth < minWidth && imgHeight < minHeight){
alert(minSizeError);
return false;
}else{
var imgAR = imgWidth/imgHeight;
var isunderacceptance = Math.abs(parseFloat(aspectRatio)-parseFloat(imgAR))*100;
if(isunderacceptance <= 2){
uploadedImg +=1;
//currentImg.parent('td').find('input[type="hidden"]').val(im.src);
currentImg.attr({'src':im.src,width:previmWidth,height:previmHeight});
}else{
alert(minRatioError);
return false;
}
}
}
im.onerror = function(){
alert('Please select a image file');
return false;
}
// Resize the image
var canvas = document.createElement('canvas'),
max_size = 1440,// TODO : pull max size from a site config
width = im.width,
height = im.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(im, 0, 0, width, height);
var ctx = canvas.getContext('2d');
var imgData = ctx.getImageData( 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
resizedImage = dataURLToBlob(imgData);
console.log(resizedImage);
}
console.log(input.files[0]);
//reader.readAsDataURL(input.files[0]);
reader.readAsBinaryString(resizedImage);
}
}
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
推荐答案
如何进一步减少上传重量
看起来像有损jpg另外将jpeg的图片质量设置为中等值,以使其更轻量级。
Looks like you're ok with "lossy" jpg so you could additionally set the jpeg's image quality to a medium value to make it even more "light weight".
var jpeg = canvas.toDataURL('image/jpeg',0.50);
要处理9个jpeg,您可以:
- 在数组中累积所有9个jpeg编码字符串:
var jpegs = [];
- 准备发送时,使用JSON来字符化javascript数组:
var jsonJpegs = JSON.stringify(jpegs)
- (可选)使用javascript ZIP脚本进一步降低编码图像的权重。一个示例zip库: https://stuk.github.io/jszip/
- Accumulate all 9 jpeg encoded strings in an array:
var jpegs=[];
- When ready to send, use JSON to stringify the javascript array:
var jsonJpegs=JSON.stringify(jpegs)
- Optionally, use a javascript ZIP script to further reduce the weight of the encoded images. One example zip library: https://stuk.github.io/jszip/
注释代码和演示
Annotated code and a Demo:
// canvas vars
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
// define max resulting image width,height (after resizing)
var maxW=100;
var maxH=100;
// listen for user to select files
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var img = new Image;
img.onload = function(){
var iw=img.width;
var ih=img.height;
// scale down, if necessary
if(iw>maxW || ih>maxH){
var scale=Math.min((maxW/iw),(maxH/ih));
iw*=scale;
ih*=scale
}
// set canvas width/height to scaled size
canvas.width=iw;
canvas.height=ih;
// draw+scale the img onto the canvas
ctx.drawImage(img,0,0,iw,ih);
// create a jpeg URL (with medium quality to save "weight")
var jpg=canvas.toDataURL('image/jpeg',0.60);
// In Demo: add the jpg to the window
// In production, accumulate jpg's & send to server
$('<img />',{src:jpg}).appendTo('body');
}
// In Demo: Just process the first selected file
// In production: process all selected files
img.src = URL.createObjectURL(e.target.files[0]);
}
img{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Select an image file for resizing</h4>
<input type="file" id="input"/><br>
这篇关于客户端调整图像和使用画布发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文