Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an image into a html textarea [closed]

I'm wondering how to pass an image from an image-gallery into a html-textarea. Should i use jquery/javascript and do you know some good tutorial on this function?

like image 689
SvenSune Avatar asked Dec 03 '25 16:12

SvenSune


1 Answers

After choosing an image via os built-in selector

<input type="file"../>

you can pass image data(base64 encoded string) to an image tag located within a editable div by using file reader api.

Full example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title></title>
</head>
<style>

#textarea {
    -moz-appearance: textfield-multiline;
    -webkit-appearance: textarea;
    border: 1px solid gray;
    font: medium -moz-fixed;
    font: -webkit-small-control;
    height: 28px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
}

</style>
<body>

<input class="file" type='file' id="imgSel" />

<div id="textarea" contenteditable>

  <img contenteditable="false" style="width:45px" id="myimg" />
  I look like a textarea

</div>

<script type="text/javascript">

    function readURL(input) {

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

            reader.onload = function (e) {
                document.getElementById('myimg').setAttribute('src',e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }


    document.getElementById('imgSel').onchange = function () { //set up a common class
        readURL(this);
    };


</script>

</body>

</html>

How to make and editable div look like a textarea element:

#textarea {
    -moz-appearance: textfield-multiline;
    -webkit-appearance: textarea;
    border: 1px solid gray;
    font: medium -moz-fixed;
    font: -webkit-small-control;
    height: 118px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
}
<div id="textarea" contenteditable>
  
  <img contenteditable="false" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Koala-ag1.jpg" width="120" height="100"/>
  
  I look like a textarea</div>

you can set contenteditable="false" on img element to make it not editable.

https://jsfiddle.net/ThinkingStiff/AbKTQ/

like image 190
Blauharley Avatar answered Dec 06 '25 08:12

Blauharley