1. 程式人生 > 程式設計 >JS實現按比例縮小圖片寬高

JS實現按比例縮小圖片寬高

本文例項為大家分享了JS實現按比例縮小圖片寬高的具體程式碼,供大家參考,具體內容如下

<!DOCTYPE html>
<html>
<head>
 <title>JS 按比例縮小圖片寬高</title>
</head>
 
<body>
 <div>
 <input type="file" name="" id="upload">
 <img src="" alt="JS實現按比例縮小圖片寬高" id="preview">
 </div>
</body>
<script>
 var upd =document.getElementById('upload');
 upd.addEventListener('change',function(e){
 var file=e.target.files[0]; 
 var reader=new FileReader();
 var img = document.createElement('img');
 var canvas=document.createElement('canvas');
 var context=canvas.getContext('2d'); 
 
 reader.onload=function(e){ 
 img.src = e.target.result;
 img.onload = function () {
 var imgWidth=this.width;//上傳圖片的寬
 var imgHeight = this.height;//上傳圖片的高 
 //按比例縮放後圖片寬高 
 var targetWidth = imgWidth;
 var targetHeight = imgHeight; 
 var maxWidth=1920;//圖片最大寬
 var maxHeight = 1080;//圖片最大高 
 var scale = imgWidth / imgHeight;//原圖寬高比例
 
 //如果原圖寬大於最大寬度
 if(imgWidth>maxWidth){
 targetWidth = maxWidth;
 targetHeight = targetWidth/scale;
 }
 //縮放後高度仍然大於最大高度繼續按比例縮小
 if(targetHeight>maxHeight){
 targetHeight = maxHeight
 targetWidth = targetHeight*scale;
 }
 canvas.width=targetWidth;//canvas的寬=圖片的寬
 canvas.height=targetHeight;//canvas的高=圖片的高
 
 context.clearRect(0,targetWidth,targetHeight)//清理canvas
 context.drawImage(img,targetHeight)//canvas繪圖
 var newUrl=canvas.toDataURL('image',0.92);//canvas匯出成為base64
 preview.src=newUrl
 }
 }
 reader.readAsDataURL(file);
 })
</script>
 
</html>

小編再為大家分享一段:圖片按寬高比例進行自動縮放程式碼

/**
 * 圖片按寬高比例進行自動縮放
 * @param ImgObj
 * 縮放圖片源物件
 * @param maxWidth
 * 允許縮放的最大寬度
 * @param maxHeight
 * 允許縮放的最大高度
 * @usage 
 * 呼叫:<img src="圖片" onload="javascript:DrawImage(this,100,100)">
 */
function DrawImage(ImgObj,maxWidth,maxHeight){
 var image = new Image();
 //原圖片原始地址(用於獲取原圖片的真實寬高,當<img>標籤指定了寬、高時不受影響)
 image.src = ImgObj.src;
 // 用於設定圖片的寬度和高度
 var tempWidth;
 var tempHeight;
 
 if(image.width > 0 && image.height > 0){
 //原圖片寬高比例 大於 指定的寬高比例,這就說明了原圖片的寬度必然 > 高度
 if (image.width/image.height >= maxWidth/maxHeight) {
  if (image.width > maxWidth) {
  tempWidth = maxWidth;
  // 按原圖片的比例進行縮放
  tempHeight = (image.height * maxWidth) / image.width;
  } else {
  // 按原圖片的大小進行縮放
  tempWidth = image.width;
  tempHeight = image.height;
  }
 } else {// 原圖片的高度必然 > 寬度
  if (image.height > maxHeight) { 
  tempHeight = maxHeight;
  // 按原圖片的比例進行縮放
  tempWidth = (image.width * maxHeight) / image.height; 
  } else {
  // 按原圖片的大小進行縮放
  tempWidth = image.width;
  tempHeight = image.height;
  }
 }
 // 設定頁面圖片的寬和高
 ImgObj.height = tempHeight;
 ImgObj.width = tempWidth;
 // 提示圖片的原來大小
 ImgObj.alt = image.width + "×" + image.height;
 }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。