Image upload to base64 in HTML5 - javascript

I'm using jasny bootstrap to include image uploads in my page. See http://jasny.github.io/bootstrap/javascript/#fileinput
My question: I want to save this image into a Javascript database like PouchDB - so I think my only option is to use Base64 (http://pouchdb.com/guides/attachments.html - I will be using webservices to copy this image to another website, so I think it has to be base64). But how can I convert the image to base64 string format?

HTML :
<input type='file' id="asd" />
<img id="img" src="" />
<div id="base"></div>
JS :
function readImage(input) {
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
$('#img').attr( "src", e.target.result );
$('#base').text( e.target.result );
};
FR.readAsDataURL( input.files[0] );
}
}
$("#asd").change(function(){
readImage( this );
});

You may also find blob-util to be useful. It has an imgSrcToBlob() method that takes an <img> src and converts it to an HTML5 Blob, and can also convert it to base64, binary string, ArrayBuffer, etc.

Related

Save exact storage size of file(image,audio,video) from Angularjs to WepApi

I tried to upload 2mb file but $scope.selectedFile.base64 length is more than 2mb but i want to save same file size
Html
<input type="file" id="fileUpload" name="files" ng-model="selectedFile" base-sixty-four-input>
<button ng-click="vm.saveFile()"> Upload </button>
Js
$scope.saveFile = function(){
var data = {
fileType: $scope.selectedFile.filetype,
fileName: $scope.selectedFile.filename,
fileBase64 : $scope.selectedFile.base64,
};
}
myService.uploaddDocument(data).then(function (response) {
}
I tried another way in this method, both (uploadFile.size and event.target.result.split(',')[1].length ) size are different
Html
<input type="file" id="fileUpload" name="files" onchange="angular.element(this).scope().fileChanged(event)">
Js
$scope.fileChanged = function (files) {
var uploadFile = document.getElementById("fileUpload").files[0];
console.log(uploadFile.size);
var fileReader = new FileReader();
fileReader.onload = function (event) {
console.log(event.target.result.split(',')[1].length);
}
}
So, Please tell me a solution for save same file size
When (any) base64 string converts into byteArray in c# then the size of byteArray is equal to original file size.
C# :
Convert.FromBase64String(base64);
We can Calculate the actual size of file from base64 ( like base64 length * 0.75 = actual file size)

Image cannot be read when pasted

I made a tool which converts images to base64 data.
<input id="inp" type='file'><br>
<br>
<textarea readonly placeholder="Base64 data" id="b64"></textarea>
<br>
<img id="img">
<script>
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.addEventListener("load", function(e) {
document.getElementById("img").src = e.target.result;
document.getElementById("b64").innerHTML = e.target.result;
});
FR.readAsDataURL( this.files[0] );
}
}
window.addEventListener('paste', e => {
document.getElementById("inp").files = e.clipboardData.files;
});
document.getElementById("inp").addEventListener("change", readFile);
</script>
Image can be uploaded either by using <input id="inp" type='file'>, or by directly copying and pasting the image from clipboard onto the window.
Here is the problem; when image is uploaded through the usual <input>, it renders the base64 data within seconds, however when pasting the image from clipboard onto the window, the input seems to recognize the image as image.png but no data gets rendered. How can I solve this problem?

Get image and save in storage

I have an web page which is a profile viewing page. Here I have an blank image. On click of this image I am able to prompt browse image option. But I don't know how to save the image into storage. Here is my code:
<div class="profileImage" >
<ul>
<li style="margin-top:5px;">
.Hii
</li>
<li>
<input type="file" id="my_file" style="display: none;" />
</li>
<li>
<img id="fileupload" name="filetoupload" src="../../static/img/img.png">
</li>
</ul>
</div>
$(document).ready(function(){
$("#fileupload").on("click", function() {
$("#my_file").click();
}
I tried this below jQuery to save image but is was of no use.
$(document).ready(function(){
$("#fileupload").on("click",function(){
$("#my_file").click();
userImage = document.getElementById('fileupload');
imgData = getBase64Image(userImage);
localStorage.setItem("imgData", imgData);
});
});
My requirement is I should be able to save the image from clicking add image i.e img.png in my code. I am using beego as web framework, but i will be happy if this get solved in jQuery or javascript.
jsBin demo
// https://stackoverflow.com/a/17711190/383904
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
localStorage.setItem("imgData", event.target.result); // Send to Localstorage
};
FR.readAsDataURL( this.files[0] );
}
}
$(document).ready(function(){
$("#fileupload").on("click",function(){
$("#my_file").click().change( readImage );
});
});
To save that image on server you'll need to send that data to PHP.
PHP can than convert your base64 string to an image.
Otherwise, why not simply send that image using AJAX to a PHP script that will put it inside a server folder?
Send Image to server using File input type
https://stackoverflow.com/a/17711190/383904

Display image thumbnail of image selected from filepicker

I'm using a regular HTML File Picker input form item to allow my users to select files. I'd like to show them a thumbnail of the file they selected as they will be required to select many images and it can get confusing.
Does anyone know if it's possible to display the image they selected without uploading it to the server? If so, how?
If someone can point me to a post or give me an idea of how I might do this it will be greatly appreciated.
<input type="file" name="image" accept="image/*">
<!-- Create an <img> element to preview the image -->
<img id="image-preview" width="320">
<!-- The <input> can go anywhere in your page or <form>. Note the "onchange" attribute -->
<input type="file" name="image" accept="image/*" onchange="handleFileChange">
Make sure the following JavaScript comes after the above <img> and <input> elements. You can put this in your .js file that is loaded at the end of the page or in a <script> element at the end of page.
// Select the preview image element
const imgElement = document.getElementById('image-preview');
function handleFileChange(e) {
// If no file was selected, empty the preview <img>
if(!e.target.files.length) return imgElement.src = '';
// Set the <img>'s src to a reference URL to the selected file
return imgElement.src = URL.createObjectURL(e.target.files.item(0))
}
This should get you started
http://jsfiddle.net/41go76g4/
Basically you read the file in with fileAPI in javascript and set the returned blob as the dataURL for an img tag.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
ref: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Display local android image in a webview using javascript or jquery

Scene: I am trying to display a file image selected from the gallery into a webview using javascricpt and/or jquery but I am not able to do so. The same works while opening the html in a desktop browser.
What I have tried so far is this in the android code is this:
Written the openFileChooser code and getting the image path and also the image bytes.
calling the following in onActivityResult method:
String js = "javascript:loadImage(file://" + imagePath + ")";
mWebView.loadUrl(js);
The html looks like this:
<div class="file_chooser">
<!-- <input type="submit" value="File chooser" id="btnSubmit" onclick="sayHello();" > -->
<input type="file" name="banner_image" id="banner_image" onChange="loadImage(this);" accept="image/*" />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<img alt="" id="image" src="" width="200px" height="200px" onclick="showSrc(this.src);">
</div>
and the javascript looks like this:
<script type="text/javascript">
function loadImage(input) {
if (input.files && input.files[0]) {
Android.alert('input: ' + input.files[0]);
var reader = new FileReader();
reader.onload = (function(input) {
return function(e) {
$('#image').attr('src', e.target.result);
console.log('onload stage finished');
};
})(input);
reader.onloadend = (function() {
// $('#image').src(file.name);
});
reader.readAsDataURL(input.files[0]);
//data:image/jpg;base64,xxxxxxxxxxxxxxxxxxxxxxxxxxxx -> this did not work
}
function showSrc(src) {
Android.alert('src : ' + src);
}
</script>
But i seem to be messing with the android code and also javascript, since i do not know jscript that well.
Please assist as to how to display an image after selection from the gallery.
EDIT:
I have gone through lotsa links that show how to call a javscript function from android , and how to display an image by calling loadBaseUrl with the new html code that has an image inside the src tag, like this, but this is not what I really want.
For those who fall into such a case:
I changed how the loadImage method functions to one that converts a file received into bytes
Steps:
1. Read a file from android and send the path over to the js function
2. Pass the path to a reader and when the reader loads the file, the onLoadEnd method gets called
3. Convert the file to bytes using the code
var stringToReplace = reader.result;
stringToReplace = stringToReplace.replace('data:base64,','data:image\/jpeg;base64,');
Set the image source to the string obtained in #3.

Categories

Resources