서문: 프로젝트에서 이미지 다운로드 기능을 구현해야 합니다. 가장 먼저 염두에 두어야 할 것은 이를 달성하기 위해 a 태그의 다운로드 속성을 사용하는 것입니다. 그러나 다른 브라우저에서 테스트할 때 일부 브라우저에서 발견됩니다. 유효하지 않으며 클릭 후 이미지를 직접 미리 볼 수 있습니다. 따라서 온라인으로 이동하여 다른 브라우저와 호환되는 이미지를 다운로드하는 다른 방법을 찾았습니다. 즉, 캔버스를 사용하여 이미지를 처리하고 다운로드하는 것입니다.
1. 프로젝트에서 이벤트 바인딩을 클릭합니다.
<a href=# @click.prevent=downloadIamge(imgsrc, name)><span>{{name}}</span></a>
2. 클릭 이벤트에서의 동작:
downloadIamge(imgsrc, 이름) { const url = imgsrc this.convertUrlToBase64(url).then((base64) => { const blob = this.convertBase64UrlToBlob(base64) if (getBrowser() === 'IE' || getBrowser( ) === '가장자리') { window.navigator.msSaveBlob(blob, 이름) } else { const a = document.createElement('a') const body = document.querySelector('body') a.download = 이름 || '이미지' a.href = URL.createObjectURL(blob) a.style.display = ' 없음' body.appendChild(a) a.click() body.removeChild(a) window.URL.revokeObjectURL(a.href) } }) },
3.this.convertUrlToBase64(url)은 canvas와 toDataURL을 사용하여 이미지를 base64 형식으로 변환하고 반환합니다.
ConvertUrlToBase64 (url) { return new Promise((해결, 거부) => { const img = new Image() img.crossOrigin = 'Anonymous' img.src = url img.onload = function () { const canvas = document.createElement ('캔버스') canvas.width = img.width canvas.height = img.height const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0, img.width, img.height) const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase () const dataURL = canvas.toDataURL('image/' + ext) const base64 = { dataURL: dataURL, 유형: 'image/' + ext, ext: ext } 해결(base64) } }) },
img.crossOrigin = 'Anonymous'는 프런트 엔드에 의한 이미지의 도메인 간 처리입니다.
4.this.convertBase64UrlToBlob(base64)는 이미지 base64 스트림 파일을 Blob 파일로 변환합니다.
ConvertBase64UrlToBlob (base64) { const parts = base64.dataURL.split('base64,') const contentType = parts[0].split(':')[1] const raw = window.atob(parts[1]) const rawLength = raw.length const uInt8Array = new Uint8Array(rawLength) for (let i = 0; i < rawLength; i++) { uInt8Array[i] = raw.charCodeAt(i) } return new Blob([uInt8Array], { type: contentType }) },
5.getBrowser()는 브라우저를 결정하고 브라우저 호환성 문제를 해결하는 데 사용됩니다.
import { getBrowser } from '@/utils/utils'export function getBrowser () { const userAgent = navigator.userAgent if (userAgent.indexOf('OPR') > -1) { return 'Opera' } if (userAgent.indexOf( 'Firefox') > -1) { return 'FF' } if (userAgent.indexOf('Trident') > -1) { return 'IE' } if (userAgent.indexOf('Edge') > -1) { return 'Edge' } if (userAgent.indexOf('Chrome') > -1) { return 'Chrome' } if (userAgent.indexOf('Safari' ) > -1) { '사파리' 반환 }}
6. IE 또는 Edge 브라우저인 경우 window.navigator.msSaveBlob(blob, 이름)을 직접 사용하여 다운로드를 완료할 수 있습니다.
면책조항: iOS 시스템의 보안 제한으로 인해 위의 방법은 iOS에서 유효하지 않습니다.
위의 내용은 녹화 프로젝트에 사용되는 이미지 다운로드 및 브라우저 호환성 문제입니다. base64 및 blob과 관련된 지식 포인트와 원리는 아직 명확하지 않습니다. 시간이 있을 때 전체 방법을 연구해야 합니다. ; 테스트 및 피드백을 환영합니다. 또한 모든 사람들이 VeVb Wulin Network를 지지해주기를 바랍니다.