How to Display Selected Image in HTML


We can display a selected image in HTML by getting the Image path and setting it as an image source in our HTML page.

Here, I have one div and one input of type file with property display none to hide it from the page and used the div as an input field. When a click event occurs on div, the actual input button clicked by JQuery.

On the change of the input field, I made a URL object to get the path of the selected image and use it to update the div background image. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html>
<head>
    <title>Display Selected Image</title>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>

    <style type="text/css">
     .special_btn {
            background-image: url("https://cdn1.iconfinder.com/data/icons/ios-11-glyphs/30/camera-512.png");
            height: 300px;
            width: 300px;
            margin: auto;
            margin-top: 170px;
            background-size: cover;
            background-position: center center;
            background-color: rgba(0, 0, 0, 0.1);
        }

        #input_btn {
            display: none;
        }
    </style>
</head>
<body>

    <form method="POST" action="" enctype="multipart/form-data">
        <div class="special_btn"></div>
        <input id="input_btn" name="image" type='file' />
    </form>

    <script>
        $('.special_btn').bind("click", function () {
            $('#input_btn').click();
        });

        $('input[type="file"]').bind("change", function(){
   var path = URL.createObjectURL(event.target.files[0]);
   $('.special_btn').css('background-image','url('+ path +')');
  });
    </script>

</body>
</html>

No comments