admin管理员组文章数量:1241160
I have an html form where users insert an image (input). My users may be not advanced users, so they may want to insert many different types of image format. However, I only want the user to send jpg/gif/png files. One option is just block other file types, however, I was wandering if I could convert the files in the client side (I don't want to send a very large file, and convert it on the server). Therefore, the only way I can think of is using javacript.
So, does any one know how to make image format conversions in javascript? And put this image result as the value of an html:input?
Thanks!
I have an html form where users insert an image (input). My users may be not advanced users, so they may want to insert many different types of image format. However, I only want the user to send jpg/gif/png files. One option is just block other file types, however, I was wandering if I could convert the files in the client side (I don't want to send a very large file, and convert it on the server). Therefore, the only way I can think of is using javacript.
So, does any one know how to make image format conversions in javascript? And put this image result as the value of an html:input?
Thanks!
Share Improve this question asked Jan 24, 2011 at 10:31 MateuMateu 2,6986 gold badges38 silver badges56 bronze badges 2- If not possible, maybe using HTML5? – Mateu Commented Jan 24, 2011 at 10:41
- No, HTML 5 doesn't add that kind of functionality. – Michael Commented Jan 24, 2011 at 10:46
7 Answers
Reset to default 4tl;dr: Don't bother
This might be theoretically possible, but I would remend against it very strongly. It's possible to create a javascript Img
element which refers to an URL the user has typed in. You can then draw this image in an HTML5 canvas.
You can then manually access the data on the canvas and analyze/convert the image to the approriate format. It might then be possible to send this Base64 or URL-encode to a server which could then return the image to the client.
This is of course pletely crazy and should NOT be attempted. This solution would require implementing JPG pression in javascript which, although technically possible, is probably not feasible because of browser constraints (eg. speed).
You could use a Java applet (similar to the way the Facebook photo upload applet to pre-prepare/size images prior to upload), there aren't too many other options available to you.
Essentially, performing the transform client-side is going to be very difficult, but it is possible (using browser plug-ins). Solely relying on JavaScript, it isn't possible. Even if it were, it would be dangerous because of varying implementations across browsers. Other solutions won't be zero-footprint (the user will have to have the dependency installed on their puter).
The best and most reliable option would be to perform the transformation server-side (using Apache Batik if you're familiar with Java) in whatever technology you have available and are familiar with.
You could use Web assembly ImageMagick to convert the image client-side. WebAssembly is supported in most modern web browser.
Modern browser now provide the methods to convert images in the browser, if this is desired. The following method can be used on any browser that supports OffscreenCanvas
and the required file types:
/**
* Convert between any image formats the browser supports
* @param {Blob} source A Blob (or File) containing the image to convert
* @param {string} type The MIME type of the target format
* @returns {Promise<Blob>} The converted image
*/
async function convert(source, type) {
let image = await createImageBitmap(source);
let canvas = new OffscreenCanvas(image.width, image.height);
let context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
let result = await canvas.convertToBlob({ type });
image.close();
return result;
}
On browsers that don't support OffscreenCanvas
, such as (as of January 2023) Safari, the following method can be used:
/**
* Convert between any image formats the browser supports
* @param {Blob} source A Blob (or File) containing the image to convert
* @param {string} type The MIME type of the target format
* @returns {Promise<Blob>} The converted image
*/
async function convertLegacy(source, type) {
let image = await createImageBitmap(source);
let canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
let result = await new Promise((resolve, reject) => {
canvas.toBlob((blob) => {
if (blob != null) {
resolve(blob);
} else {
reject(new Error("Failed to convert file"));
}
}, type, 1);
});
image.close();
return result;
}
Note that the second method won't work in a WebWorker.
If an unsupported target format is given, the browser will default to PNG. There are probably no browser without JPEG support.
This is possible, but not remended.
For starters you need to get the exif data to rotate the image correctly if it's ing from a mobile. Then you need to verify the file type and convert it to something you can upload via ajax. To do this, you will require a browser that can handle "toDataURL" on the canvas object:
function supportsToDataURL() {
var c = document.createElement("canvas");
var data = c.toDataURL("image/jpeg");
return (data.indexOf("data:image/jpeg") == 0)
}
Once you get a file, I like to render it with megapix: megapixel library
Listen for the image onload event like this:
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 });
You could then write the image to a canvas:
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");
NOTE: some versions of android may support "toDataURL" but not the full spec. They may only render pngs, etc. This is only one of the many problems you will have trying to get cross browser patibility on image rendering.
Trust me, I have put about 16 hours into making a image cropping and adjustment tool for a mobile web app, and it's no easy task.
The better solution would be to have the user select a file, convert it to base64 and upload via ajax. Then convert things serverside and (if necessary) send something back to the user they can view.
I'm working on a plugin to allow mobile image uploads, I'll put the link in here when it's done.
Just impossible.
There's no client-side Javascript support for doing image manipulation.
You can use extensibility APIs from most popular web browsers in the market like Internet Explorer, Firefox, Safari, Chrome or Opera, but this isn't a standard Javascript-based solution. Anyway, it would be a client-side solution and some of these API support document manipulation, so, maybe you can handle some kind of clicks in certain HTML elements with an specific CSS class.
You could use jimp-browser (possibly with WebWorkers).
https://github./oliver-moran/jimp/tree/master/browser
This library isn't relying on the toDataUrl method of canvas and thus e.g. also works with bigger images in iOS (see "Known Issues" here http://caniuse./#search=toDataURL).
本文标签: Convert image to jpg from an html in client side (javascript)Stack Overflow
版权声明:本文标题:Convert image to jpg from an html in client side (javascript) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740090796a2223977.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论