How to get a user uploaded image cenverted to Base64 - javascript

I have already made a simple log system where i get the Base64 Code from a text string:
var myString = 'Hello everyone, my name is Dennis';
var b64 = btoa(myString);
var unicode = atob(b64);
console.log(b64);
console.log(unicode);
The output is a Base64 Code like i said, but what i am trying to is to convert an uploaded image to Base64. Here is what i got so far, the output what i get from this is the whole webpage in base64 code. i hope someone could help me out.
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
//use
var captcha = document.getElementById('logo').src;
toDataUrl(captcha, function(base64Img) {
log(captcha);
});
Thanks in advance!

There I made you a working example if the duplicate doens't help you:
(And be aware of CORS if your image is not heberged on the same domain of the request)
function toDataUrl(src, callback) {
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();
callback(dataURL);
};
img.src = src;
}
toDataUrl("http://i.imgur.com/rx3kylA.png", function(base64Img) {
console.log(base64Img);
});

Related

Use p5js script for an NFT?

I have seen people use this method for SVG-based NFTs:
function p5jsToImageURI(){
string memory baseURL = "data:image/svg+xml;base64,PUT-BASE64-HERE"
}
But, since I don't want to generate a fixed image how can I use my p5js script (that looks slightly different each time the js code runs)? Is there a way to just somehow pass the seed to my script and the script with the seed passed to it is stored on-chain?
var img,inpt,div
function convertImgToDataURLviaCanvas(url, 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.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
function convertFileToDataURLviaFileReader(url, callback){
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
function img2b64(imagefile){
var imageUrl = imagefile;
var convertType = 'Canvas';
var convertFunction = convertType === 'FileReader' ? convertFileToDataURLviaFileReader : convertImgToDataURLviaCanvas;
convertFunction(imageUrl, function(base64Img){
code='foto = "'+base64Img+'";'
inpt.value(code)
div.html('<img src="'+base64Img+'">');
});
}
function setup() {
but = createButton("CONVERT");
but.mousePressed(function () {
img2b64('nature100b.jpg');
});
inpt = createP('');
inpt = createElement("textarea",'');
inpt.elt.rows = 5;
inpt.elt.cols = 50;
div = createDiv('');
}
Try this
https://editor.p5js.org/josepssv/full/wsCZnJqkA

Can I load an image directly on to a canvas without using the image element

I am using the canvas control.
I use the image element to draw the image to the canvas on the image onload event.
I am looking to see if I can improve the performance by not loading into the image element first and directly locad the image to the canavs.
can this be done?
This is my current code:
desktopImage.src = "/Media/FrameHandler.ashx?camIndex=" + camIndex;
desktopImage.onload = function () {
ctxLiveViews.drawImage(desktopImage, 0, 0);
}
I have been playing around with this code but the blob requires an ArrayBuffer:
var blob = new Blob('data:image/jpeg;base64,' + jpeg, { type: "image/jpeg" });
var url = (URL || webkitURL).createObjectURL(blob);
(URL || webkitURL).revokeObjectURL(url);
AMENDED CODE:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/Media/FrameHandler.ashx?camIndex=' + camIndex, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
var uInt8Array = new Uint8ClampedArray(this.response);
imageData[camIndex].data.set(uInt8Array);
ctxLiveViews[camIndex].putImageData(imageData[camIndex], 0, 0);
};
xhr.send();
Generic Handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.ContentType = "image/jpeg";
var camIndex = Convert.ToInt16(context.Request.QueryString["camIndex"]);
context.Response.BinaryWrite( Shared.Feeder[camIndex].JpegData);
}
Image OutPut:
Here is a method to directly load the image data to canvas, without considering the data is right be drew:
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
var imageData = ctx.getImageData(0, 0, 256, 256);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://fiddle.jshell.net/img/logo.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
var uInt8Array = new Uint8ClampedArray(this.response);
imageData.data.set(uInt8Array);
ctx.putImageData(imageData, 0, 0);
};
xhr.send();
jsfiddle
If you want to get the blob:
xhr.onload = function (e) {
var uInt8Array = new Uint8Array(this.response);
var blob = new Blob([ uInt8Array ], { type: "image/png" });
var urlCreator = window.URL || window.webkitURL;
var url = urlCreator.createObjectURL(blob);
};

How to be able to convert image to base64 and avoid same-origin Policy

I'm trying to convert an image (link) to base64 to be able to store in the Browser side (IndexedDB), but i'm not able to do that, I have been looking for a solution for days and I didn't a solution to my problem.
In this awesome code I'm able to convert an image from internet to Base64, but the problem is that I can't do that for other images on internet because of the Same-origin policy.
How I would be able to avoid that problem or if you know any other solution to convert an image to Base64, that would be really helpful
function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64URL('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png', function(base64Img){
alert('it works');
$('.output').find('img').attr('src', base64Img);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"> <img> </div>
While converting into base64 you can use a proxy URL (https://cors-anywhere.herokuapp.com/) before your image path to avoid cross-origin issue
var getDataUri = function (targetUrl, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
var proxyUrl = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyUrl + targetUrl);
xhr.responseType = 'blob';
xhr.send();
};
getDataUri(path, function (base64) {
// base64 availlable here
})
You need to download the image to a byte array first:
Downloading binary data using XMLHttpRequest, without overrideMimeType
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
uInt8Array[i] = this.response[i];
}
var byte3 = uInt8Array[4]; // byte at offset 4
}
}
xhr.send();
Then you can use the byte array as follows: Javascript : How to display image from byte array using Javascript or Servlet?
<img id="ItemPreview" src="" />
document.getElementById("ItemPreview").src = "data:image/png;base64," + YourByteArray;
EDIT: I cannot try this ATM but you can alternatively save the file to the file system using the HTML5 FileSystem API: How to save a image to HTML5 filesystem with the url of image
window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);
function onFileSystemSuccess(fileSystem) {
fs = fileSystem;
console.log('File system initialized');
saveAsset('http://www.example-site-with-cors.com/test.png');
}
function saveAsset(url, callback, failCallback) {
var filename = url.substring(url.lastIndexOf('/')+1);
// Set callback when not defined
if (!callback) {
callback = function(cached_url) {
console.log('download ok: ' + cached_url);
};
}
if (!failCallback) {
failCallback = function() {
console.log('download failed');
};
}
// Set lookupTable if not defined
if (!window.lookupTable)
window.lookupTable = {};
// BlobBuilder shim
// var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// xhr.responseType = 'blob';
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) {
// Save this file in the path to URL lookup table.
lookupTable[filename] = fileEntry.toURL();
callback(fileEntry.toURL());
};
writer.onerror = failCallback;
// var bb = new BlobBuilder();
var blob = new Blob([xhr.response], {type: ''});
// bb.append(xhr.response);
writer.write(blob);
// writer.write(bb.getBlob());
}, failCallback);
}, failCallback);
});
xhr.addEventListener('error', failCallback);
xhr.send();
return filename;
}
function fail(evt) {
console.log(evt.target.error.code);
}
for same origin policy you must add headers for server side from where you want your images
here is how to do this -
http://enable-cors.org/server.html
for development purpose you can install 'CORS' extension in CHROME browser to allow cross origin request
hope this helps and solve your issue.

Android Browser only: canvas.toDataURL throws Uncaught Error: SecurityError: DOM Exception 18

I'm trying to convert a image to a base64 string and put it as source into an img tag. The picture is stored on a other subdomain then the scripts. So i put this in my .htaccess file to ensure, the access is allowed
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin http://xxx.mydomain.com
Header set Access-Control-Allow-Credentials true
</ifModule>
It's working pretty well on Desktop Browsers, Safari on iOS and Chrome on Android. But not in Androids native browser. All i got in the console is
Uncaught Error: SecurityError: DOM Exception 18
Any idea why it's working on all browser but not on the androids one? Here's my script
function convertImgToBase64(url, callback, outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL(outputFormat || 'image/jpg');
callback.call(this, dataURL);
canvas = null;
};
img.crossOrigin = 'anonymous';
img.src = url;
}
var imgString;
if (localStorage.getItem('xxxItemNamexxx')) {
imgString = localStorage.getItem('xxxItemNamexxx');
} else {
convertImgToBase64($('#my-picture').attr('src'), function(base64Img) {
imgString = base64Img;
localStorage.setItem('xxxItemNamexxx', base64Img);
});
}
$('#my-picture').attr('src', imgString);
Thanks for any inputs!
I had similar issue in android and this answer helped.
function convertImgToBase64(url, callback, outputFormat){
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (xhr.status == 200) {
var uInt8Array = new Uint8Array(xhr.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
var dataUrl = "data:" + (outputFormat || "image/png") + ";base64," + base64;
callback.call(this, dataUrl);
}
};
xhr.send();
}

Creating a Blob from an external image url

I have an file input that i used to get a file and turn it into a blob. Is there anyway I can get an external image url and turn that into a blob? Here is the code I am using to do it with just a file from a <input type="file" />:
//Process the file and resize it.
function processfile(file) {
if (!(/image/i).test(file.type)) {
alert("File " + file.name + " is not an image.");
return false;
}
// read the files
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
// blob stuff
var blob = new Blob([event.target.result]); // create blob...
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob); // and get it's URL
// helper Image object
var image = new Image();
image.src = blobURL;
image.onload = function () {
for (var x = 0; x < self.ThumbSizes.length; x++) {
// have to wait till it's loaded
var resized = resizeMe(image, self.ThumbSizes[x]); // send it to canvas
var resized_blob = dataURItoBlob(resized);
uploadFile(resized_blob, self.ThumbSizes[x].Name);
}
}
};
Instead of passing a file through I wanted to be able to structure this code to pass a image url and convert it into a blob.
I hope it helps you. (I didn't run it.)
function processfile(imageURL) {
var image = new Image();
var onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
canvas.toBlob(function(blob) {
// do stuff with blob
});
};
image.onload = onload;
image.src = imageURL;
}

Categories

Resources