js 获取网络图片的Base64、实际大小、宽高


// 由Image对象获取图片的Base64
// img: Image对象, width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
function getBase64Image (img, width, height) {
  const canvas = document.createElement('canvas')
  canvas.width = width || img.width
  canvas.height = height || img.height
  const ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
  const dataURL = canvas.toDataURL()
  return dataURL
}
// 根据网络地址获取图片的Base64
function getBase64 (img) {
  const image = new Image()
  image.crossOrigin = ''
  image.src = img
  return new Promise((resolve, reject) => {
    image.onload = function () {
      const base64Data = getBase64Image(image)
      resolve(base64Data)
    }
  })
}
// 根据网络地址获取图片的宽高
function getBase64 (img) {
  const image = new Image()
  image.crossOrigin = ''
  image.src = img
  return new Promise((resolve, reject) => {
    image.onload = function () {
      const { width, height } = image
      resolve({ width, height })
    }
  })
}
// 获取图片的实际大小
export function getImageSize(img) {
  return fetch(img).then((res) => {
    return res.blob()
  })
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM