To handle the downsizing of large image files before uploading them to your server, you can use client-side JavaScript libraries to resize the images. One popular library for this purpose is pica, which is known for its high-quality image resizing. You can use this library in combination with FileReader and Canvas to resize the image before uploading it.
Here's a step-by-step solution:
-
Include the Pica library: You can include the Pica library in your project via a CDN or by installing it via npm.
-
Read the image file: Use the
FileReaderAPI to read the image file selected by the user. -
Resize the image: Use the Pica library to resize the image to the desired dimensions and quality.
-
Upload the resized image: Convert the resized image to a Blob and upload it to your server.
Here is a complete example using jQuery and Pica:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pica.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" accept="image/*">
<button id="uploadButton">Upload</button>
<script>
$(document).ready(function() {
$('#uploadButton').click(function() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.onload = function() {
const canvas = document.createElement('canvas');
const MAX_WIDTH = 1024; // Adjust as needed
const MAX_HEIGHT = 1024; // Adjust as needed
let width = img.width;
let height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
pica().resize(canvas, canvas, {
quality: 3,
alpha: true
}).then(result => {
return pica().toBlob(result, 'image/jpeg', 0.90);
}).then(blob => {
const formData = new FormData();
formData.append('file', blob, file.name);
$.ajax({
url: '/upload', // Your server-side upload URL
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log('Upload successful:', response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Upload failed:', textStatus, errorThrown);
}
});
});
};
};
reader.readAsDataURL(file);
} else {
alert('Please select a file to upload.');
}
});
});
</script>
</body>
</html>
Explanation:
- File Input: The user selects an image file using an input element.
- FileReader: Reads the selected file and loads it into an image element.
- Canvas: Draws the image onto a canvas element and resizes it to the desired dimensions.
- Pica: Uses the Pica library to resize the image with high quality.
- Blob: Converts the resized image to a Blob and appends it to a FormData object.
- AJAX: Sends the FormData object to the server using an AJAX request.
This approach ensures that the image is resized on the client side before being uploaded, reducing the file size and making the upload process more efficient, especially over 4G/5G networks.