Convert image to jpg from html on client side (javascript)

I have an html form where users insert an image (input). My users may not be advanced users, so they may want to insert many different types of image formats. However, I only want the user to send jpg / gif / png files. One option is to simply block other types of files, however, I wandered if I could convert files on the client side (I do not want to send a very large file and convert it to the server). Therefore, the only way I can think of is to use javacript.

So, does anyone know how to do image format conversions in javascript? And put this image result as the html: input value?

Thank!

+3
source share
6 answers

tl; dr: don't worry

It may be theoretically possible, but I would highly recommend it. It is possible to create a javascript element Imgthat refers to the URL that the user typed. Then you can draw this image in HTML5 canvas.

Then you can manually access the data on the canvas and analyze / convert the image to the approriate format. Then it may be possible to send this Base64 or URL encoding to the server, which can then return the image to the client.

This, of course, is completely crazy and should NOT be undertaken. This solution will require the use of jpg compression in javascript, which, although technically possible, is probably not possible due to browser limitations (such as speed).

+3

. . javascript

+2

Java ( , Facebook / ), .

, , ( ). JavaScript, . , - . ( ).

( Apache Batik, Java) , .

+2

.

Javascript .

API - , Internet Explorer, Firefox, Safari, Chrome Opera, Javascript. , , API , , , - HTML CSS.

+1

, .

exif, , . , ajax. , "toDataURL" canvas:

function supportsToDataURL() {
    var c = document.createElement("canvas");
    var data = c.toDataURL("image/jpeg");
    return (data.indexOf("data:image/jpeg") == 0)        
}

, :

:

var img = new Image()
img.onload = function() {
    // do some stuff like rendering image to a canvas
}
var mpImg = new MegaPixImage(file);
mpImg.render(img, { quality: 1, maxWidth: 1024 });  

:

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

canvas.width = sourceWidth;
canvas.height = sourceHeight;

ctx.drawImage(img, 0, 0, sourceWidth, sourceHeight);
var url = canvas.toDataURL();
// or if you want a specific file type
var jpeg = canvas.toDataURL("image/jpeg");
var png = canvas.toDataURL("image/png");

. "toDataURL", . png .. , , .

, 16 -, .

, base64 ajax. serveride ( ) - , .

, , , .

0

jimp- (, WebWorkers).

https://github.com/oliver-moran/jimp/tree/master/browser

This library does not rely on the canvas toDataUrl method and thus, for example, also works with large images in iOS (see "Known issues" here http://caniuse.com/#search=toDataURL ).

0
source

Source: https://habr.com/ru/post/1787418/


All Articles