Skip to content

Commit a6f2f72

Browse files
committed
Enhance image preview functionality by adding cropping and scaling for uploaded images
1 parent 44ca0e5 commit a6f2f72

File tree

1 file changed

+58
-11
lines changed

1 file changed

+58
-11
lines changed

qgisfeedproject/static/js/feed_item_form.js

Lines changed: 58 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,65 @@ titleField.addEventListener("input", function () {
5050
// Update image in preview when input change
5151
imageField.addEventListener("change", function () {
5252
let selectedImage = imageField.files[0];
53-
imagePreview.forEach((item) => {
54-
if (selectedImage) {
55-
let imageURL = URL.createObjectURL(selectedImage);
56-
item.innerHTML =
57-
'<img src="' + imageURL + '" style="border-radius:20px;">';
58-
imageFileName.innerHTML = selectedImage.name;
59-
} else {
53+
if (selectedImage) {
54+
let imageURL = URL.createObjectURL(selectedImage);
55+
let img = new Image();
56+
img.onload = function () {
57+
// Target dimensions
58+
const targetWidth = 500;
59+
const targetHeight = 354;
60+
const targetAspect = targetWidth / targetHeight;
61+
62+
// Source dimensions
63+
const sourceAspect = img.width / img.height;
64+
65+
// Calculate crop dimensions
66+
let cropWidth, cropHeight, cropX, cropY;
67+
68+
if (sourceAspect > targetAspect) {
69+
// Image is wider, crop width
70+
cropHeight = img.height;
71+
cropWidth = img.height * targetAspect;
72+
cropX = (img.width - cropWidth) / 2;
73+
cropY = 0;
74+
} else {
75+
// Image is taller, crop height
76+
cropWidth = img.width;
77+
cropHeight = img.width / targetAspect;
78+
cropX = 0;
79+
cropY = (img.height - cropHeight) / 2;
80+
}
81+
82+
// Create canvas and crop/scale image
83+
const canvas = document.createElement('canvas');
84+
canvas.width = targetWidth;
85+
canvas.height = targetHeight;
86+
const ctx = canvas.getContext('2d');
87+
88+
ctx.drawImage(
89+
img,
90+
cropX, cropY, cropWidth, cropHeight,
91+
0, 0, targetWidth, targetHeight
92+
);
93+
94+
// Convert to data URL and display
95+
const croppedImageURL = canvas.toDataURL('image/jpeg', 0.9);
96+
imagePreview.forEach((item) => {
97+
item.innerHTML =
98+
'<img src="' + croppedImageURL + '" style="max-width:100%;height:auto;border-radius:20px;">';
99+
});
100+
101+
URL.revokeObjectURL(imageURL);
102+
};
103+
img.src = imageURL;
104+
imageFileName.innerHTML = selectedImage.name;
105+
} else {
106+
imagePreview.forEach((item) => {
60107
item.innerHTML = "";
61-
imageFileName.innerHTML =
62-
"<i>No image chosen. Click here to add an image.</i>";
63-
}
64-
});
108+
});
109+
imageFileName.innerHTML =
110+
"<i>No image chosen. Click here to add an image.</i>";
111+
}
65112
checkFormValid();
66113
});
67114

0 commit comments

Comments
 (0)