Image on Canvas to Jpeg File

Capture HTML Canvas as gif/jpg/png/pdf?

Original answer was specific to a similar question. This has been revised:

const canvas = document.getElementById('mycanvas')
const img = canvas.toDataURL('image/png')

with the value in IMG you can write it out as a new Image like so:

document.getElementById('existing-image-id').src = img

or

document.write('<img src="'+img+'"/>');

Converting the contents of a large Canvas to JPEG

You can use toBlob to achieve this

The HTMLCanvasElement.toBlob() method creates a Blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.

You'll notice the last two arguments I submitted were 'image/jpeg', 0.9 this is the type and quality you can leave these out if you ever want a PNG.

If type is not specified, the image type is image/png. The created image is in a resolution of 96dpi. The third argument is used with image/jpeg images to specify the quality of the output.





let canvas = document.querySelector('canvas');

ctx = canvas.getContext('2d');

ctx.beginPath();

ctx.moveTo(600, 0);

ctx.lineTo(1200, 1200);

ctx.lineTo(0, 1200);

ctx.closePath();

ctx.fillStyle = 'yellow';

ctx.fill();


canvas.toBlob((blob) => {

let img = document.createElement('img');

let url = URL.createObjectURL(blob);


img.src = url;

document.body.appendChild(img);

}, 'image/jpeg', 0.9);
<canvas width="1200" height="1200"></canvas>

Save canvas as jpg to desktop


Download attribute

There is a new download attribute in HTML5 that allow you to specify a file-name for links.

I made this for saving canvas. It has a link ("Download as image") -

<a id="downloadLnk" download="YourFileName.jpg">Download as image</a>

And the function:

function download() {
var dt = canvas.toDataURL('image/jpeg');
this.href = dt;
};
downloadLnk.addEventListener('click', download, false);

You can even change the file-name dynamically by setting the attribute downloadLnk.download = 'myFilename.jpg'.

Demo from the archives.

Image on canvas to JPEG file


  1. create an empty bitmap
  2. create a new Canvas object and pass this bitmap to it
  3. call view.draw(Canvas) passing it the canvas object you just created. Refer Documentation of method for details.
  4. Use Bitmap.compress() to write the contents of the bitmap to an OutputStream, file maybe.

Pseudo code:

Bitmap  bitmap = Bitmap.createBitmap( view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

Saving a canvas to a PNG or JPEG file

I finally found my error. The problem was that the draw funcation had a SetTimeOut function. So I was only writing a black image to my server because the DataToURL function triggered to fast.

The Solution is to put everything after the draw function in a write function. and give that function a timeOut to be sure an image is drawn.

Here is the corrected code :

document.addEventListener('DOMContentLoaded', function(){
var v = document.getElementById('v');
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');

var v = document.getElementById("v");
v.addEventListener('loadedmetadata', function() {
this.currentTime = this.duration / 3;
}, false);
v.addEventListener( "loadedmetadata", function () {
var cw = this.videoWidth;
var ch = this.videoHeight;
console.log(cw); //displaying the width of the video
console.log(ch); //displaying the height of the video
canvas.width = cw; //seting the width of the canvas
canvas.height = ch; //setting the height of the canvas
draw(this,context,cw,ch); // Drawing the image from the video onto the canvas
setTimeout(function() {
write(canvas);
}, 1000)
}, false );

},false);

function draw(v,c,w,h) {
c.drawImage(v,0,0,w,h);
setTimeout(draw,20,v,c,w,h);
}
function write(c) {
var dataURL = c.toDataURL('image/jpeg');
var image = document.createElement("img");
image.src=dataURL;
document.getElementById("placehere").appendChild(image);
$.ajax({
type: 'POST',
url: 'saveThumb.php',
data: 'img=' + dataURL
}).done(function(o) {
console.log(dataURL);
console.log('saved');
});
}

how to convert canvas image data:image/jpeg;base64,.. to normal image file - javascript

The string that you're getting can be used as the source attribute for an image, you just have to create a new Image element to which you can assign it:

var image = new Image();
image.src = canvas.toDataURL("image/png", 1);
// append image to DOM

EDIT: Given the comments, you want to turn this into something that be stored in a database. You should POST the result of toDataURL to your server. Use your server-side technology's IO/image/graphics libraries to decode the base64-encoded part of the data string and write that out to a new file. You can now store that path in your database.

Alternative: just store that whole data string in your database. Then when you render your <img> tag you can simply dump it into the src attribute:

<img src="<< base-64 encoded data string>>" />

send a canvas image to server format JPG javascript or jquery

First, you have to convert your image to base64 format using Javascript:

var canvas = document.getElementById("canvas");
var data = canvas.toDataURL("image/jpeg");

And send this data to your PHP server using ajax for example. Then, in your PHP file, you just have to use this code to convert the base64 data to an image:

file_put_contents("myimage.jpg", base64_decode(explode(",", $_GET['data'])[1]));

That's all !

Canvas Image to an Image file

You can easily do that this way (specifying the format as png in this case):

var img = canvas.toDataURL("image/png");

You can specify different image formats.
Take a look at this answer.

How to optimize canvas image and get jpg instead of png

When you' re making the data URI you can specify

canvas.toDataURL("image/jpeg", 0.95); 

or

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

which will generate a JPG. Just make sure your picture is opaque, because otherwise the background will become black.

How to convert a image from PNG to JPEG using javascript?


Cause

The reason for this to happen is due to canvas being transparent. However the transparancy color is black with a transparent alpha-channel so it won't show on screen.

JPEG on the other side doesn't support alpha-channel so that black color which is the default is stripped of its alpha channel leaving a black background.

You PNG supports alpha-channel so it is compatible with the way canvas work.

Solution

To get around this you will have to manually draw in a white background on the canvas before you draw in the image:

var canvas =  $('.jSignature')[0];
var ctx = canvas.getContext('2d');

ctx.fillStyle = '#fff'; /// set white fill style
ctx.fillRect(0, 0, canvas.width, canvas.height);

/// draw image and then use toDataURL() here


Related Topics



Leave a reply



Submit