Previewing the image
HTML:
<img id="profile-pic" alt="Profile picture" />
<h2>
Your profile picture
</h2>
<input type="file" id="my-file" />
<br>
<input type="button" value="Save changes" id="save" />
JavaScript:
document.getElementById("my-file").onchange = function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
// e.target.result is a base64-encoded url that contains the image data
document.getElementById('profile-pic').setAttribute('src', e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
Code adapted from this answer by Ivan Baev.
CSS:
#profile-pic {
float: left;
margin-right: 20px;
/* If you want to crop the image to a certain size, use something like this */
object-fit: cover;
width: 100px;
height: 100px;
}
Cropping code adapted from this answer by Vision Hive.
(JSFiddle)
Saving it
If you're trying to save the image so other users will see it, things get complicated. Especially with different pictures for different users, you'd want some sort of database to keep track of profiles and a server-side program to display the right one at the right time. If you're new to server programming, you can find tutorials for a language of your choice (or if you want to stick to JavaScript, see Node.js). There's a good chance StackOverflow has an answer for how to accept image uploads in your language. Once your server is ready to accept an image, take a look at this answer by Rudie for how to upload it from the browser.