image.ts 1.6 KB

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