How to get base64 encoded data from html image - javascript

I have a registration form where users can choose an avatar. They have 2 possibilities:
Choose a default avatar
Upload their own avatar
In my HTML page I have this.
<img id="preview" src="img/default_1.png">
It displays the chosen avatar.
I use the File Api to let users upload their own image.
That makes the src of the HTML image to something like this.
<img id="preview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA... />
When they post the registration form. The data will be sent to a REST service.
I can send the base64 encoded data when a user uploaded an avatar himself. But how do I handle the default avatar? It is an url instead of base64 encoded data.

You can try following sample
http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );

Related

Set Image src from image blob

I have trying to request an image from an API and set the src of an img in my web page. The API returns a blob that represents a .png file. At this time, I'm requesting the image using the following:
const fetchResult = await fetch(imageApiUrl);
const resultBlob = await fetchResult.blob();
console.log(resultBlob);
In the console, I can see:
Blob {size: [some number], type: "image/png" }
So, I know that I have a result. I assume a blob. I now need to set this blob as the source of an img in my HTML, which looks like this:
<img id="profilePicture" alt="Profile Picture" height="250" width="250" />
I have this:
var profilePicture = document.getElementById('profilePicture');
How do I set the src of the profilePicture element to the blob?
You could use URL.createObjectURL in order to create a temporary URL that points to the in-memory image:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;

Is it possible to display an image that has been selected by an input element?

I wish to display an input element's selected image. Can this be performed on a local file, accessing the image client side, or would I need to upload the image to a server?
Here's my attempt in React. I can access the correct file name from the input element using inputElem.files[0].name. As soon as I am trying to set an image element to it, the broken image icon is displayed, and no error is surfaced.
const App = () => {
// state to keep track of img elements src. The default works fine.
const [imgSrc, setImgSrc] = useState('/images/test.jpg')
function handleImgUpload() {
const url = '/images/' + e.target.files[0].name
setImgSrc(url)
console.log(url) // /images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG
}
function handleImgLoadSuccess() {
console.log('image loaded!')
}
function handleImgLoadError() {
console.log('image not loaded')
}
return (
<div>
<div>
<label htmlFor="img">Select an image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg"
onChange={(e) => handleImgUpload(e)}
/>
</div>
<img
src={imgSrc}
alt="Your upload"
onLoad={handleImgLoadSuccess}
onError={handleImgLoadError}
/>
</div>
)
}
In the console, however, the url seems to be correct.
<img src="/images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG" height="100" width="200" alt="Input" class="jsx-855240488">
Hey – I see what you're trying to do, but it doesn't look like this will work. You need to create a new file reader.
const showTempImage = (e) => {
const file = e.target.files[0];
const img = document.createElement("img");
const reader = new FileReader();
reader.addEventListener('load', (e) => {
img.src = e.target.result;
});
reader.readAsDataURL(file);
// Append the img tag to the dom somewhere
}
This did the trick by creating a correct blob url.
const inputImg = e.target.files[0]
const url = URL.createObjectURL(inputImg)
// blob:http://localhost:3000/test-img.jpg
The resulting file stays in memory and needs to be removed in order to create memory leaks.
URL.revokeObjectURL(url)
This also seems to be accomplishable with FileReader, though there are differences.

Retrieve image data from file input without a server

For context, I'm trying to create a "click image" file uploader. Initially there is a default image, which I then click. I trigger a file upload, and the user picks an image file they want. Then I will set the image to replace the default (and do other things with it later). Right now, the front end looks something like this:
<div class="right-preview">
<input type="image" src="img/logo.png" height="240px" width="240px" ng-click="uploadImage('right-image')" id="upload-right-image"/>
<input type="file" id="upload-right" style="visibility: hidden">
</div>
When the image is clicked, it triggers an upload action.
$scope.uploadImage = function(side) {
$image = $('#upload-' + side);
$fileInput = $('#upload-right');
$fileInput.change(function(changeEvent) {
var files = changeEvent.target.files;
for(var i = 0; i < files.length; i++) {
file = files[i];
console.log(file);
}
});
$fileInput.trigger('click');
}
When the change event is fired after the user finishes picking their file, I have the changeEvent and I know they've selected their file. Each of the files has some properties (like name and size) but I'm not seeing anything for accessing the raw data so I can set the src on my other element.
Am I just completely missing how to get the image data, or is there a better way to do this? I have no server (right now) to post this to. Perhaps there is a better way to approach this?
This link may be helpful to you - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
I took one method from that page and added some additional functionality to hide the file upload button and have the image placeholder trigger its click event.
$('#placeholder').click(function() {
$('#img-upload').trigger('click');
});
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img width="250" height="250" id="placeholder" src="http://place-hold.it/250x250&text='click to upload'">
<input class="hidden" type="file" onchange="previewFile()" id="img-upload">

convert to base64 and send image using ajax in Javascript

I need to send selected image to the server, here is already I have tried
here is HTML part
<div class="row">
<input type="file" name="filUpload" id="filUpload" onchange="showimagepreview(this)">
<br />
<img id="imgprvw" alt="uploaded image preview" class="img-thumbnail" />
</div>
I need to get encoded image into javascript variable,But I have no idea
for uploading image on to server you need to send image data via AJAX to server side.
for reference you can see this link :
http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php
http://phppot.com/php/php-ajax-image-upload/
you can try using jquery's base64 plugin. Jquery.Base64 plugin
and do it like this:
function showimagepreview(c) {
var file = c;
if(file.files.length)
{
var reader = new FileReader();
reader.onload = function(e)
{
var b = $.base64.encode(e.target.result);
$("#imgprvw").attr("src", "data:image/png;base64," + b);
};
reader.readAsBinaryString(file.files[0]);
}
}

JavaScript sending base64 image string to servlet

my html code for selecting image and by clicking browserbutton,
<input id="image_file" type="file" class="frmitm" onChange="fileSelected();">
here for selcted code preview showing,
<img id="preview" width="50px" height="50px" border="1" />
here javascript code for selected image & preview showing on page but when i alert or storing in the key its not getting full of string.
function selectedImage(){
var oFile = document.getElementById('image_file').files[0];
var oImage = document.getElementById('preview');
var oReader = new FileReader();
oReader.onload = function(e){
oImage.src = e.target.result;
var resultStr = oImage.src;
var result = resultStr.split(",");
$('#ImageKey').val(result[1]);
};
oReader.readAsDataURL(oFile);
}
here alert($('#ImageKey').val()) i got only half string only like,
/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+ESC.....etc,
how to get full length of string value.or any other way to convert image to base64 string..
if i saved server response base64 string in var tempImgStr = response.ImgStr;("/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/+ESC..etc")
then alert(tempImgStr), i will get half of string value only.
any suggestions please..

Categories