gpt4 book ai didi

javascript - 使用 HTML5 在上传前调整图片大小

转载 作者:IT王子 更新时间:2023-10-29 02:46:45 24 4
gpt4 key购买 nike

我在 stackoverflow 上找到了一些不同的帖子甚至问题来回答这个问题。我基本上实现了与 this post 相同的东西.

所以这是我的问题。当我上传照片时,我还需要提交表格的其余部分。这是我的 html:

<form id="uploadImageForm" enctype="multipart/form-data">
<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<input id="name" value="#{name}" />
... a few more inputs ...
</form>

以前,我不需要调整图像的大小,所以我的 javascript 看起来像这样:

window.uploadPhotos = function(url){
var data = new FormData($("form[id*='uploadImageForm']")[0]);

$.ajax({
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
... handle error...
}
}
});
};

这一切都很好......现在我需要调整图像的大小......我如何替换表单中的图像以便发布调整后的图像而不是上传的图像?

window.uploadPhotos = function(url){

var resizedImage;

// Read in file
var file = event.target.files[0];

// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');

// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {

// Resize the image
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
resizedImage = canvas.toDataURL('image/jpeg');
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}


// TODO: Need some logic here to switch out which photo is being posted...

var data = new FormData($("form[id*='uploadImageForm']")[0]);

$.ajax({
url: url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
... handle error...
}
}
});
};

我考虑过将文件输入移出表单并在表单中隐藏输入,我将其值设置为调整大小后的图像的值......但我想知道是否可以替换表格中已有的图像。

最佳答案

这是我最终做的,效果很好。

首先,我将文件输入移到了表单之外,这样它就不会被提交:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
... a few more inputs ...
</form>

然后我更改了 uploadPhotos 函数以仅处理调整大小:

window.uploadPhotos = function(url){
// Read in file
var file = event.target.files[0];

// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');

// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {

// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};

如您所见,我正在使用 canvas.toDataURL('image/jpeg'); 将调整后的图像更改为 dataUrl,然后调用函数 dataURLToBlob(dataUrl) ; 将 dataUrl 转换为一个 blob,然后我可以将其附加到表单。创建 blob 后,我触发了一个自定义事件。这是创建 blob 的函数:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];

return new Blob([raw], {type: contentType});
}

var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;

var uInt8Array = new Uint8Array(rawLength);

for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}

return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */

最后,这是我的事件处理程序,它从自定义事件中获取 blob,附加表单,然后提交它。

/* Handle image resized events */
$(document).on("imageResized", function (event) {
var data = new FormData($("form[id*='uploadImageForm']")[0]);
if (event.blob && event.url) {
data.append('image_data', event.blob);

$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});

关于javascript - 使用 HTML5 在上传前调整图片大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23945494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com