Convert Link from Image URL from s3 into File Object using JavaScript - javascript

I want to convert my s3 image link into a file object using JavaScript.
I've found out how to do this with an image URI but wasn't able to figure out how to convert the image URL into a URI. Once I do this I could convert it into a file object
Heres the image link:
http://s3.us-east-2.amazonaws.com/rentpop/298%2F2014-mclaren-650s-Spyder-Tarocco-Orange-2.jpg

Source for this code
function getDataUri(url, callback) {
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
// Get raw image data
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// Usage
getDataUri('local_location_to_image.extension', function(dataUri) {
// Do whatever you'd like with the Data URI!
});

Related

Save the blob url image from using viewer.screenshot() to server/database

I used forge viewer api. Viewer.screenshot() to get the image of a component. It returns a blob url as the image. E.g “blob:localhost:3000/afdijhejsbjdjd”. But I need to save this image to my local server, how can I achieve this? Using Nodejs.
How can I change this blob url to a transferable image url?
We can convert the image Blob URL to a based64 encoded string like the below, and then
function getScreenShotImageBase64(viewer, width, height) {
return new Promise((resolve) => {
viewer.getScreenShot(width, height, blobURL => {
let img = new Image();
let tmpCanvas = document.createElement('canvas');
let ctx = tmpCanvas.getContext('2d');
tmpCanvas.width = width;
tmpCanvas.height = height;
img.onload = function() {
// draw viewer image on canvas
ctx.drawImage(img, 0, 0, width, height);
resolve(tmpCanvas.toDataURL('image/png'));
};
img.src = blobURL;
});
});
}
let imageBase64 = await getScreenShotImageBase64(viewer, viewer.container.offsetWidth, viewer.container.offsetHeight);
Here is the preview of the result:
Afterward, send the base64 string to your backend server, and then you can either save the image base64 string to your database,
Or resave the base64 string to file. For example in nodejs.
fs.writeFileSync(path.join(uploadPath, fileName), new Buffer(base64, 'base64'))
ref: How to upload image using Base64 string in NodeJs

why image is not converted into base64?

I am trying to convert my attached image into base64 .I tried like this, but getting error .
https://jsbin.com/lubosabore/edit?html,js,console,output
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
$(function(){
// alert()
$('#fileId').on('change', function (e) {
console.log('ddd');
var file = e.target.files[0];
console.log(getBase64Image(file))
})
})
i attached one png value
it is not printing the base64 value
When I run this code, I get the following error:
TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
So a File object like e.target.files[0] won't work. We need to convert it into an HTMLImageElement first. Here is how to do that (from another answer):
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
Now you have a HTMLImageElement. However, you really don't need it, or the canvas at all: event.target.result from the FileReader is already a data: URL like you want.

Adding raw SVG code to HTML Canvas

Earlier this day, I have succeed in converting SVG file to JPEG using javascript. The main steps are:
Get SVG image from a url
Add image to HTML5 Canvas
Convert the Canvas to JPEG encoded in base64
I replicate the getImageFromUrl function on jsPDF-master to achieve this.
var getImageFromUrl = function (url, callback) {
var img = new Image,
data, ret = {
data: null,
pending: true
};
img.onError = function () {
throw new Error('Cannot load image: "' + url + '"');
}
img.onload = function () {
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
// Grab the image as a jpeg encoded in base64, but only the data
data = canvas.toDataURL('image/jpeg').slice('data:image/jpeg;base64,'.length);
// Convert the data to binary form
data = atob(data)
document.body.removeChild(canvas);
ret['data'] = data;
ret['pending'] = false;
if (typeof callback === 'function') {
callback(data);
}
}
img.src = url;
return ret;
}
From that function, the image to be converted is actually a file. In my case, I don't have a file but only the raw code (text when you open a SVG file with text editor).
My question is:
How do you add raw code of a SVG file into the HTML canvas? Is this process also have .onload event attribute like image object?
Thank you
You can convert a "raw" (inline) SVG to image by converting it to a Blob and then use that as an image source:
function drawInlineSVG(ctx, rawSVG, callback) {
var
/// create Blob of inlined SVG
svg = new Blob([rawSVG], {type:"image/svg+xml;charset=utf-8"}),
/// create URL (handle prefixed version)
domURL = self.URL || self.webkitURL || self,
url = domURL.createObjectURL(svg),
/// create Image
img = new Image;
/// handle image loading
img.onload = function () {
/// draw SVG to canvas
ctx.drawImage(this, 0, 0);
domURL.revokeObjectURL(url);
callback(this);
};
img.src = url;
}
Then call it like this:
var rawSVG = '<svg ... >';
drawInlineSVG(ctx, rawSVG, function(img) {
console.log('done!');
});
An error handler should of course be included for production code (not shown here).
Important to note: You cannot draw inline SVG's if they contain external references (CSS styles, images and so on). This is due to browser's security policies. You would have to convert all external references to inline data (ie. images to data-uris and so on).

How can I get Image data or the path of cache of Image on WebPage in chrome or firefox?

I'm making an plugin(add-on) to upload image on any page.
I only can get the url of the image, but I want to get the image data or local cache of image.
by javascript on chrome or firefox.
I did it in my extension via canvas.
I created two functions. First getting image data from canvas using "toDataURL()" method (Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element (such as img)), and then using this data to get BLOB object.
function getImageDataURL(url) {
var data, canvas, ctx, blob;
var img = new Image();
img.onload = function() {
canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
try {
data = canvas.toDataURL();
blob = dataURIToBlob(data);
} catch(e) {
// Handle errors here
alert(e);
}
};
img.src = url;
};
function dataURIToBlob (dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var ab = [];
for (var i = 0; i < byteString.length; i++)
ab.push(byteString.charCodeAt(i));
return new Blob([new Uint8Array(ab)], { type: mimeString });
};
Here in the "blob" variable we have BLOB object with full image data.
You could use indexeDB (internal browser data base) that takes objets to store instead of URL. See Google dev tutorials for detailled use.

How to base64 encode an image in javascript

I am developing a phonegap application and using the navigator.getPicture method to get the images.
The way I am getting the picture is:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
Just like the example in phonegap doc's.
I want to be able to use the imageURI and then convert it to image data in order to upload it later. (I don't want to use phonegap's FileTransfer)
So far I have tried both Get image data in JavaScript? and How can you encode a string to Base64 in JavaScript?
When I try the following,
function onSuccess(imageURI) {
getBase64Image(imageURI);
}
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL); //here is where I get 'data:,'
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
And print dataURL before returning. I just get data:, as the content.
Any ideas on what I'm doing wrong?
Well you can try getting it as a DATA_URL. Your mileage may vary as you could run into an out of memory error when the image is converted to a Base64 string.
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
Alternatively you can use the FileReader.readAsDataURL().
The canvas.toDataURL method is not implemented on earlier versions of Android.

Categories