You can draw the image in a canvas, encode it to base64 and then use it as a text. Almost all languages can convert between base64 and images.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img= new Image();
img.src = "your url to image";
ctx.drawImage(img,0,0);
c.toDataURL();
//c now contains the base64 encoding of your image
the canvas can also be created dynamically and not as a part of the page. You can also wait for the onLoad event on the image.
Answer from Kristian Ivanov on Stack OverflowYou can draw the image in a canvas, encode it to base64 and then use it as a text. Almost all languages can convert between base64 and images.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img= new Image();
img.src = "your url to image";
ctx.drawImage(img,0,0);
c.toDataURL();
//c now contains the base64 encoding of your image
the canvas can also be created dynamically and not as a part of the page. You can also wait for the onLoad event on the image.
Use canvas..Here is the code copied from a program
function fun_nam(url,back, op){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(op);
back(dataURL);
canvas = null;
};
img.src = url;
}
Some details ...
The HTMLCanvasElement.toDataURL() method returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.
Syntax: canvas.toDataURL(type, encoderOptions);
Parameters
type | Optional
- A DOMString indicating the image format. The default type is image/png.
encoderOptions | Optional
- A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored.
Return value
- A DOMString containing the requested data URI.
Actually we are drawing the image data with the drawImage function,Then use the toDataURL function to get a base-64 encoded image data: url.
The encoding should be do only after loading the full image.Else you will get some broken/grey type image after decoding.
There are multiple approaches you can choose from:
1. Approach: FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
Run code snippetEdit code snippet Hide Results Copy to answer Expand
This code example could also be implemented using the WHATWG fetch API:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
Run code snippetEdit code snippet Hide Results Copy to answer Expand
These approaches:
- have better compression
- work for other file types as well
Browser Support:
- http://caniuse.com/#feat=filereader
- http://caniuse.com/#feat=fetch
Tip: To convert local files, you can use live-server. Once started on the folder that contains the picture to transform, open the url in browser and using developer console you can convert the image to base 64.
2. Approach: Canvas (for legacy browsers)
Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
In detail
Supported input formats:
image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx
Supported output formats:
image/png, image/jpeg, image/webp(chrome)
Browser Support:
- http://caniuse.com/#feat=canvas
-
Internet Explorer 10 (Internet Explorer 10 just works with same origin images)
3. Approach: Images from the local file system
If you want to convert images from the users file system you need to take a different approach. Use the FileReader API:
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You can use the HTML5 <canvas> for it:
Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).
html - How to convert an image to a string using javascript? - Stack Overflow
How to convert an image string in javascript or jquery? - Stack Overflow
html - How to turn a string of data into an image in Javascript? - Stack Overflow
html - How to convert from image to text using Javascript - Stack Overflow
Having
<input type="file" id="picture">
You can add an event handler to it listening to the change event (this code has to come after the above HTML or be registered on the DOMContentLoaded event)
var input = document.getElementById('picture');
input.addEventListener('change', handleFiles, false);
Then your handleFiles event would draw the image into a canvas and extract the base64 string from the file:
function handleFiles(e) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
var base64 = canvas.toDataURL();
console.log(base64);
}
img.src = URL.createObjectURL(e.target.files[0]);
}
Running example bellow:
var input = document.getElementById('picture');
input.addEventListener('change', handleFiles, false);
function handleFiles(e) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
var base64 = canvas.toDataURL();
document.getElementById('result').value = base64;
}
img.src = URL.createObjectURL(e.target.files[0]);
}
textarea {
width: 350px;
height: 100px;
}
<input type="file" id="picture" />
<br /> <br />
<textarea id="result"></textarea>
If what you want is a dataURI version, use a FileReader and its readAsDataURL() method.
file_input.onchange = function(e) {
var fr = new FileReader();
fr.onload = function() {
output.src = this.result;
}
fr.readAsDataURL(this.files[0]);
};
<input type="file" id="file_input" />
<img id="output" />
If you just want to display it, then you can use the URL Constructor :
file_input.onchange = function(e) {
output.src = URL.createObjectURL(this.files[0]);
};
// don't forget to revoke the URLObject when you don't need it anymore
output.onload = function() {
URL.revokeObjectURL(this.src);
}
<input type="file" id="file_input" />
<img id="output" />
This looks like it's a combination of already answered questions. You need to ungzip the string and then convert from string to image. When dealing with problems like this it's best to break it down into the smallest chunks you can. That way your searches will yield more applicable results if you can't find your exact issue.
JavaScript implementation of Gzip
Javascript Hex String to Image
just simple example
<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
where iVBORw0KGgoAAAANSUhEUgAAADIA... - is your value..
If you want a dataURI version of your image, the best way is to set the XHR.responseType to "blob", and read the resulted response blob with a FileReader :
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
var reader = new FileReader();
reader.onload = function(){
img.src = this.result;
result.textContent = this.result;
};
reader.readAsDataURL(this.response);
};
xhr.open('GET', 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
xhr.send();
<img id="img"/>
<p id="result"></p>
Of course, you'll have to make the call to the same origin, or to an open server (such as wikimedia one).
You should convert the image to base64 first.
Try this link
How to convert image into base64 string using javascript
If you attach an event listener to the file input, you can then recognize text once the file has been loaded successfully, like so:
<html>
<body>
<input type="file" id="myFile" name="filename">
<br><br>
<label><b>Your Converted Text:</b></label><br><br>
<textarea cols="30" name="original" rows="10" style="width: 100%;" id="convertedText">
</textarea>
<script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>
<script>
var myFile = document.getElementById('myFile');
myFile.addEventListener('change', recognizeText);
async function recognizeText({ target: { files } }) {
Tesseract.recognize(files[0]).then(function(result) {
console.log("recognizeText: result.text:", result.text);
document.getElementById("convertedText").value = result.text;
});
}
</script>
</body>
</html>
Below code will convert any image to text!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image to Text Converter</title>
<script src="https://cdn.jsdelivr.net/npm/tesseract.js/dist/tesseract.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100vh;
background-color: #f3f4f6;
}
.container {
max-width: 500px;
width: 100%;
padding: 20px;
background: white;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
.container h1 {
font-size: 1.5rem;
margin-bottom: 20px;
}
input[type="file"] {
margin-bottom: 20px;
}
#output {
margin-top: 20px;
padding: 10px;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-radius: 5px;
overflow: auto;
max-height: 200px;
}
button {
padding: 10px 20px;
background-color: #2563eb;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
}
button:hover {
background-color: #1d4ed8;
}
</style>
</head>
<body>
<div class="container">
<h1>Image to Text Converter</h1>
<input type="file" id="imageInput" accept="image/*">
<button id="convertButton">Convert to Text</button>
<div id="output" hidden>
<h3>Extracted Text:</h3>
<p id="text"></p>
</div>
</div>
<script>
const imageInput = document.getElementById('imageInput');
const convertButton = document.getElementById('convertButton');
const outputDiv = document.getElementById('output');
const textOutput = document.getElementById('text');
convertButton.addEventListener('click', () => {
if (imageInput.files.length === 0) {
alert('Please upload an image.');
return;
}
const imageFile = imageInput.files[0];
const reader = new FileReader();
reader.onload = () => {
Tesseract.recognize(
reader.result, // Image data
'eng', // Language
{
logger: (info) => console.log(info) // Log progress
}
).then(({ data: { text } }) => {
textOutput.textContent = text.trim();
outputDiv.hidden = false;
}).catch((error) => {
console.error(error);
alert('Error processing the image.');
});
};
reader.readAsDataURL(imageFile);
});
</script>
</body>
</html>
Convert svg string to base64 and add base64 string to json as property.
Look at example: https://jsfiddle.net/wLftvees/1/

var decodedJson = {
img:
"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBB"+
"ZG9iZSBJbGx1c3RyYXRvciAxNS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9u"+
...
"NSw4LjU5NS0wLjA5NSwxMC42ODIsMS45MDMiLz4NCjwvc3ZnPg0K"
};
document.getElementById('image').src = 'data:image/svg+xml;base64,' + decodedJson.img;
First: Convert your image to String
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
Second: Convert String to image
public static BufferedImage decodeToImage(String imageString) {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
Now you can use 2 function and switch to Javascript to get Image. ^^