0

I have an html5 mobile web app (http://app.winetracker.co) and I'm working on feature that remembers user's state when they come back to the app in their browser (which always automatically refreshes in iOS safari). I'm storing the URL and form-field data via local storage. One of the form field data items is an file-input for images. I am successfully converting images to a base64 via canvas and storing it to localStorage.

function storeTheImage() {
    var imgCanvas = document.getElementById('canvas-element'),
        imgContext = imgCanvas.getContext("2d");

    var img = document.getElementById('image-preview');
    // Make sure canvas is as big as the picture BUT make it half size to the file size is small enough
    imgCanvas.width = (img.width/4);
    imgCanvas.height = (img.height/4);

    // Draw image into canvas element
    imgContext.drawImage(img, 0, 0, (img.width/4), (img.height/4));

    // Get canvas contents as a data URL
    var imgAsDataURL = imgCanvas.toDataURL("image/png");

    // Save image into localStorage
    try {
        window.localStorage.setItem("imageStore", imgAsDataURL);
        $('.localstorage-output').html( window.localStorage.getItem('imageStore') );
    }
    catch (e) {
        console.log("Storage failed: " + e);
    }
}

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#image-preview').attr('src', e.target.result);
            storeTheImage(); 
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$('.file-input').on('change', function() {
    readURL(this);
});

see this jsFiddle: https://jsfiddle.net/tonejac/ceLwh9qp/19/

How might I convert the localStore image dataURL string back to an image file so I can upload it to my server?

tonejac
  • 1,083
  • 3
  • 18
  • 32

3 Answers3

1

How might I convert the localStore image dataURL string back to an image file

See your fiddle, Javascript pane line 25.

 // recompose image :
var imgRecomposed = document.createElement('img');
$('.image-recomposed').append(imgRecomposed);
imgRecomposed.src = window.localStorage.getItem('imageStore');

We create an image element and fill the src attibute with the data of the stored 'dataImage'.

Anonymous0day
  • 3,012
  • 1
  • 14
  • 16
1

In your Fiddle:

// Save image into localStorage
    try {
        window.localStorage.setItem("imageStore", imgAsDataURL);
        $('.localstorage-output').html( window.localStorage.getItem('imageStore') );
    }
    catch (e) {
        console.log("Storage failed: " + e);
    }

Place any of the following in your try/catch:

$('#canvas-element').context.drawImage(imgAsDataURL);

$('#canvas-element').context.drawImage(imgAsDataURL, 0, 0);

$('#canvas-element').replace(imgAsDataURL);

This will place the stored image into the Canvas you have displayed. It is already an 'image' - you can use it as the src for an element etc. Sending it to your server is depends on the environment you have - basically an Ajax POST or similar sending the base64 string?.

Steve Padmore
  • 1,710
  • 1
  • 12
  • 18
1

You will first have to convert this dataURL to a blob, then use a FormData object to send this blob as a file.

To convert the dataURL to a blob, I do use the function from this answer.

function upload(dataURI, url){
  // convert our dataURI to blob
  var blob = dataURItoBlob(dataURI);
  // create a new FormData
  var form = new FormData();
  // append the blob as a file (accessible through e.g $_FILES['your_file'] in php and named "your_filename.extension")
  form.append('your_file', blob, 'your_filename.'+blob.type.split('image/')[1]);
  // create a new xhr
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url);
  // send our FormData
  xhr.send(form);
  }

// from https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata/5100158#5100158
function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
}

var savedIntoLocalStorage = 'data:image/png;base64,...=';

// execute the request
upload(savedIntoLocalStorage, 'http://yourserver.com/upload.php');
Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285