File size: 1,689 Bytes
89ce340 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
interface ImageSize {
width: number
height: number
}
/**
* 获取图片的原始宽高
* @param src 图片地址
*/
export const getImageSize = (src: string): Promise<ImageSize> => {
return new Promise(resolve => {
const img = document.createElement('img')
img.src = src
img.style.opacity = '0'
document.body.appendChild(img)
img.onload = () => {
const imgWidth = img.clientWidth
const imgHeight = img.clientHeight
img.onload = null
img.onerror = null
document.body.removeChild(img)
resolve({ width: imgWidth, height: imgHeight })
}
img.onerror = () => {
img.onload = null
img.onerror = null
}
})
}
/**
* 读取图片文件的dataURL
* @param file 图片文件
*/
export const getImageDataURL = (file: File): Promise<string> => {
return new Promise(resolve => {
const reader = new FileReader()
reader.addEventListener('load', () => {
resolve(reader.result as string)
})
reader.readAsDataURL(file)
})
}
/**
* 判断是否为SVG代码字符串
* @param text 待验证文本
*/
export const isSVGString = (text: string): boolean => {
const svgRegex = /<svg[\s\S]*?>[\s\S]*?<\/svg>/i
if (!svgRegex.test(text)) return false
try {
const parser = new DOMParser()
const doc = parser.parseFromString(text, 'image/svg+xml')
return doc.documentElement.nodeName === 'svg'
}
catch {
return false
}
}
/**
* SVG代码转文件
* @param svg SVG代码
*/
export const svg2File = (svg: string): File => {
const blob = new Blob([svg], { type: 'image/svg+xml' })
return new File([blob], `${Date.now()}.svg`, { type: 'image/svg+xml' })
} |