In Javascript you have the ByteArray type and some views on it as described here:
https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays
is it possible to store image data in such bytes and if yes, how can i display such an image? png or jpg?
Yes, you can store an image using the typed arrays.
Im not sure what you want actually.
If you want to create an HTMLImageElement from a ByteArray, you can do something similar as cited in here and here.
If you want to get the bytes from an Image, that would be trickier. You can draw the ImageElement to HTML canvas, and them get the URI back using toDataURL.
I just tried to get the data using canvas and it worked.
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
myCanvas.width = img.width;
myCanvas.height = img.height;
ctx.drawImage(img,0,0); // Or at whatever offset you like
alert(myCanvas.toDataURL());
};
img.src = "logo4w.png";
Although, the method toDataURL() do not allow you to perform this operation if the image you draw on canvas comes from outside the website domain.
Related
So, I have a user input which serve to upload pictures. This is a simple example:
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
console.log (img);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
<input type="file" onchange="handleImage(event)"><br>
As you can see, I display an Image () on the console. I want to convert this Image into a jpg file.
I understood how to get the pixels of the picture but it's completely crazy to send it to a server: It's to large!
I also tried to access to the jpg file stored in the computer but I do not achieve to anything.
The only way I found is to send it with a form like this:
<form action="anything.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
And in PHP:
$_FILES["fileToUpload"]["tmp_name"]
Why not with JS?
My final goal is to send the jpg file with AJAX.
Tell me if you have some questions.
The simplest way is to use a canvas element and then invoke a download action allowing the user to select where to save the image.
You mention that the image is large, but not how much - be aware that with canvas you will also run into restrictions when the image source starts to touch around the 8k area in pixel size.
A simplified example (IE will require a polyfill for toBlob()).:
Load image source via input
Use File blob directly as image source via URL.createObjectURL()
When loaded, create a temporary canvas, set canvas size = image size and draw in image
Use toBlob() (more efficient on memory and performance and require no transcoding to/from Base64) to obtain a Blob.
We'll convert the Blob to File (a subset object and it will reference the same memory) so we can also give a filename as well as (important!) a binary mime-type.
Since the mime-type for the final step is binary the browser will invoke a Save as dialog.
document.querySelector("input").onchange = function() {
var img = new Image;
img.onload = convert;
img.src = URL.createObjectURL(this.files[0]);
};
function convert() {
URL.revokeObjectURL(this.src); // free up memory
var c = document.createElement("canvas"), // create a temp. canvas
ctx = c.getContext("2d");
c.width = this.width; // set size = image, draw
c.height = this.height;
ctx.drawImage(this, 0, 0);
// convert to File object, NOTE: we're using binary mime-type for the final Blob/File
c.toBlob(function(blob) {
var file = new File([blob], "MyJPEG.jpg", {type: "application/octet-stream"});
window.location = URL.createObjectURL(file);
}, "image/jpeg", 0.75); // mime=JPEG, quality=0.75
}
// NOTE: toBlob() is not supported in IE, use a polyfill for IE.
<label>Select image to convert: <input type=file></label>
Update: If you just are after a string (base-64 encoded) version of the newly created JPEG simply use toDataURL() instead of toBlob():
document.querySelector("input").onchange = function() {
var img = new Image;
img.onload = convert;
img.src = URL.createObjectURL(this.files[0]);
};
function convert() {
URL.revokeObjectURL(this.src); // free up memory
var c = document.createElement("canvas"), // create a temp. canvas
ctx = c.getContext("2d");
c.width = this.width; // set size = image, draw
c.height = this.height;
ctx.drawImage(this, 0, 0);
// convert to File object, NOTE: we're using binary mime-type for the final Blob/File
var jpeg = c.toDataURL("image/jpeg", 0.75); // mime=JPEG, quality=0.75
console.log(jpeg.length)
}
<label>Select image to convert: <input type=file></label>
JavaScript on the client side can not save files.
You have multiple options:
Render the image on an <canvas> element. This way it can be saved with right click -> save image
Inset the image as <img> element. This way it can be saved with right click -> save image
Send the image data as base64 string to the server. Do the processing there
Use a server side language like PHP or Node.js to save the file
Long story short, you have to use some server side logic to save the file on disk
I have an existing PNG data URI like:
let dataURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMAQMAAABsu86kAAAABlBMVEUAAAD+qAB849H0AAAAAXRSTlMAQObYZgAAAAxJREFUCNdjSEsgiACnWAlJEDYe/gAAAABJRU5ErkJggg==";
I want to use that as a texture in my canvas that I am doing some draw operations on. I've tried a few things with canvas.fillStyle, but I'm not seeing that working. Colors work fine.
What would be the way to use a dataURI as a texture in drawing operations?
You need to load it as an image first (be sure to handle the asynchronous aspect), so basically to set an image as pattern:
var img = new Image;
img.onload = imageIsReady;
img.src = "data: ....."; // full uri here
function imageIsReady() {
var pattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = pattern;
// fill, etc.
}
I'm still new in coding and HTML5.
I have a HTML5 stage with multiple canvas. I need to get the base64 image from that stage and resize it, then get the base64 image of the resized canvas.
This is the code I use:
stage.toDataURL({
callback: function(dataUrl) {
var tmp_img = new Image();
tmp_img.src = dataUrl;
//resize image to 45x75
var canvas = document.getElementById('hidden_canvas');
canvas.width = 45;
canvas.height = 75;
var ctx = canvas.getContext("2d");
ctx.drawImage(tmp_img, 0, 0, canvas.width, canvas.height);
dataUrl = canvas.toDataURL();
)};
The dataUrl is correct in Chrome but when I run the code in Firefox, it seems that the Firefox didn't generate the correct base64 code.
I would really appreciate any help
You've stumbled upon a common problem.
tmp_img.src loads the dataUrl into your new image--but that takes time. So javascript continues with your code below that even before the image is loaded. The result is that you are sometimes trying to ctx.drawImage before tmp_img has been fully loaded and is ready to use.
The fix is to refactor your code to use tmp_img.onload. The .onload triggers a callback function when tmp_img is finally ready to use. The refactoring might look like this:
var tmp_img = new Image();
tmp_img.onload=function(){
//resize image to 45x75
var canvas = document.getElementById('hidden_canvas');
canvas.width = 45;
canvas.height = 75;
var ctx = canvas.getContext("2d");
ctx.drawImage(tmp_img, 0, 0, canvas.width, canvas.height);
dataUrl = canvas.toDataURL();
}
tmp_img.src = dataUrl;
// more javascript
JavaScript will execute the above code in this order:
Create a new Image object
See tmp_img.onload and make a not that it should do that code when the image is fully loaded
Set tmp_img.src and start loading the image.
Continue with "more javascript"
When the image is fully loaded, execute everything in the .onload callback function.
It looks like you're using KineticJS--are you?
If so, then instead of stage.toDataURL you could use stage.toImage. That way you already have the image loaded when the stage.toImage callback is executed (you don't have to worry about waiting for the image to load). Then just .drawImage the image that KineticJS provides in the callback.
After seing alot of examples here, and try to use them they work in some degree, but it doesn't true convert the image.
The image as the extension now png and open as such, but if I go into properties it stills says :
on C# and HTML the image shows without any problem, but I'm using the language c++ and it won't show on the QPushButton
This is an example of the code that I'm using on the javascript to convert the image:
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
So the image is saved throught base64 to png opens as such on many programs but on the one that I'm trying to do it wont.
How to I properly convert an image to png ?! Since this method isn't working
I have a function that encodes an image into base64 string and stores it into localStorage. I am trying to retrieve the image from localStorage and use it to set a background-image with jQuery.
Everything is working right, but the image isn't displaying. When I inspect the element in the browser, the single quotes around the 'data' uri aren't being inserted. I don't know if this is the problem or not.
Here is my code
function to encode and store image:
var img = document.getElementById("elephant");
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);
return dataURL;
}
jQuery to set the image:
localStorage.setItem("background" , getBase64Image(img));
console.log(localStorage);
background = localStorage.getItem("background")
console.log(background);
$("#elephant2").css('background-image' , 'url(' +background+ ')');
I thought the issue was missing quotes, but it was actually corrupted/incomplete base64 data string. I placed the function inside window.onload = function () so the image loaded entirely before converting to a string and it works like a charm/