美文网首页
blob,dataURL相互转换

blob,dataURL相互转换

作者: noyanse | 来源:发表于2019-01-19 15:48 被阅读0次
import React, { Component } from 'react';
import axios from '../../axios-orders';
import Aux from '../../hoc/Aux/Aux';

class MyPic extends Component {
    state = {
        smallSrc: null,
        subjects: null
    }
    /**
    * 根据图片 URL 直接获取到 DataURL
    **/
    convertImgToDataURLviaCanvas (url, callback, outputFormat) {
        const img = new Image()
        img.crossOrigin = 'Anonymous' // canvas 不能处理跨域图片,如果要处理,除了服务端要开启跨域外,执行canvas操作前也要开启跨域
        img.onload = function() {
            let canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            let dataURL = ''
            canvas.height = this.height
            canvas.width = this.width
            ctx.drawImage(this, 0, 0)
            dataURL = canvas.toDataURL(outputFormat)
            callback(dataURL)
            canvas = null
        }
        img.src = url
    }
    /**
    * 根据图片 URL 直接获取到 Blob
    **/
    convertImgToBlobviaCanvas (url, callback) {
        const img = new Image()
        img.crossOrigin = 'Anonymous' // canvas 不能处理跨域图片,如果要处理,除了服务端要开启跨域外,执行canvas操作前也要开启跨域
        img.onload = function() {
            let canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            let dataURL = ''
            canvas.height = this.height
            canvas.width = this.width
            ctx.drawImage(this, 0, 0)
            canvas.toBlob(callback)
            canvas = null
        }
        img.src = url
    }
    /**
    * 把文件转成 dataURL 通过 fileReader
    **/
    convertFileToDataURLviaFileReader (url, callback) {
        const xhr = new XMLHttpRequest()
        xhr.responseType = 'blob'
        xhr.onload = function() {
            const reader = new FileReader()
            reader.onloadend = function() {
                callback(reader.result)
            }
            reader.readAsDataURL(xhr.response)
        }
        xhr.open('GET', url)
        xhr.send()
    }
    /**
    * 把 dataURL 转成 blob
    **/
    dataURLToBlob (dataurl) {
        console.log('datarul', dataurl)
        let arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type:mime })
    }
    componentDidMount () {
        axios.get('http://localhost:3000/api/v2/movie/top250')
            .then(res => {
                const smallSrc = res.data.subjects[0].images.small
                this.setState({
                    // smallSrc: smallSrc,
                    subjects: res.data.subjects
                })
                console.log(this.state.smallSrc)
                console.log(this.state.subjects)
                // 通过 canvas 转为 base64
                this.convertImgToDataURLviaCanvas(smallSrc, (dataRUL) => {
                    let smallSrcBase64 = this.dataURLToBlob(dataRUL) // 将 base64 转为 blob
                    console.log('smallSrcBase64', smallSrcBase64)
                }, 'image/jpeg')
                // 通过 canvas 转为 blob
                this.convertImgToBlobviaCanvas(smallSrc, (blob) => {
                    // let newImg = document.createElement('img')
                    let url = URL.createObjectURL(blob)

                    // newImg.onload = function() {
                    //     // 用不到 blob ,所以回收 revoked
                    //     URL.revokeObjectURL(url)
                    // }
                    URL.revokeObjectURL(url)
                    // newImg.src = url
                    console.log('blob', blob)
                    console.log('blob url', url) // blob:http://localhost:3000/2976e241-a95f-4117-8b22-740d1ed6a1c5
                })
            })
    }
    render () {
        let picUrl = null
        if ( this.state.subjects ) {
            picUrl = this.state.subjects.map(item => {
                return (
                    <div key={ item.id }>
                        <img src={ item.images.large } alt="pic" />
                    </div>
                )
            })
        }
        return (
            <Aux>
                { picUrl }
            </Aux>
        )
    }
}
export default MyPic

/**
 * @description 将图片的base64 转变成Blob形式
 * */
function dataURLtoBlob(dataurl) {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]

    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}

/**
 * @description 使用canvas绘制缩略图
 * */
export const getImageByCanvas = function(url, callback) {
    getThumb(url, dataURL => {
        callback(window.URL.createObjectURL(dataURLtoBlob(dataURL)))
    })
}

相关文章

网友评论

      本文标题:blob,dataURL相互转换

      本文链接:https://www.haomeiwen.com/subject/lklzdqtx.html