Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///// url to blob
- function loadXHR(url) {
- return new Promise(function(resolve, reject) {
- try {
- var xhr = new XMLHttpRequest()
- xhr.open("GET", url)
- xhr.responseType = "blob"
- xhr.onerror = function() {reject("Network error.")}
- xhr.onload = function() {
- if (xhr.status === 200) {resolve(xhr.response)}
- else {reject("Loading error:" + xhr.statusText)}
- }
- xhr.send()
- }
- catch(err) {reject(err.message)}
- })
- }
- loadXHR("url-to-image").then(function(blob) {
- // here the image is a blob
- })
- ///// img to blob
- var img = new Image
- var c = document.createElement("canvas")
- var ctx = c.getContext("2d")
- img.onload = function() {
- c.width = this.naturalWidth // update canvas size to match image
- c.height = this.naturalHeight
- ctx.drawImage(this, 0, 0) // draw in image
- c.toBlob(function(blob) { // get content as JPEG blob
- // here the image is a blob
- }, "image/jpeg", 0.75)
- };
- img.crossOrigin = "" // if from different origin
- img.src = "url-to-image"
- ///// input type=file to blob
- $('#done-button').on('click', function () {
- var file = $('#load-file')[0].files[0]
- var fileReader = new FileReader()
- fileReader.onloadend = function (e) {
- var arrayBuffer = e.target.result
- var fileType = $('#file-type').val()
- blobUtil.arrayBufferToBlob(arrayBuffer, fileType).then(function (blob) {
- console.log('here is a blob', blob)
- console.log('its size is', blob.size)
- console.log('its type is', blob.type)
- }).catch(console.log.bind(console))
- }
- fileReader.readAsArrayBuffer(file)
- })
- ///// submit blob
- var fd = new FormData()
- fd.append('fname', 'test.wav')
- fd.append('data', soundBlob)
- $.ajax({
- type: 'POST',
- url: '/upload.php',
- data: fd,
- processData: false,
- contentType: false,
- }).done(function(data) {
- console.log(data)
- })
- ///// dataURL from/to blob
- function dataURLtoBlob(dataurl) {
- var 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})
- }
- function blobToDataURL(blob, callback) {
- var a = new FileReader()
- a.onload = (e) => callback( e.target.result )
- a.readAsDataURL(blob)
- }
- var blob = dataURLtoBlob('data:text/plain;base64,YWFhYWFhYQ==')
- blobToDataURL(blob, function(dataurl){
- console.log(dataurl)
- })
Add Comment
Please, Sign In to add comment