לחצו על הכפתור, ובחרו את קובץ התמונה לטובת ביצוע המרת הפורמט
function initializeImageConverter() {
// בדיקה אם ה-div קיים
const containerDiv = document.getElementById('changepic');
if (!containerDiv) {
console.error('אלמנט עם מזהה changepic לא נמצא');
return;
}
// יצירת הכפתור
const button = document.createElement('button');
button.textContent = 'טען והמר תמונה';
containerDiv.appendChild(button);
// יצירת אלמנט input מסוג file והסתרתו
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*';
fileInput.style.display = 'none';
containerDiv.appendChild(fileInput);
// הוספת מאזין לחיצה לכפתור
button.addEventListener('click', () => {
fileInput.click();
});
// הוספת מאזין לשינוי בקובץ הנבחר
fileInput.addEventListener('change', handleFileSelect);
}
// פונקציה לטיפול בבחירת קובץ
async function handleFileSelect(event) {
const file = event.target.files[0];
if (file) {
const image = await createImageBitmap(file);
// יצירת קנבס עם חצי מהרזולוציה המקורית
const canvas = document.createElement('canvas');
canvas.width = image.width / 2;
canvas.height = image.height / 2;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
// המרה ל-WebP
canvas.toBlob((blob) => {
// יצירת URL לתמונה החדשה
const url = URL.createObjectURL(blob);
// יצירת קישור להורדה
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = 'converted_image.webp';
downloadLink.textContent = 'הורד תמונה ממורת';
// הוספת הקישור ל-div
const containerDiv = document.getElementById('changepic');
containerDiv.appendChild(downloadLink);
}, 'image/webp');
}
}
// הפעלת הפונקציה כאשר ה-DOM נטען במלוא
document.addEventListener('DOMContentLoaded', initializeImageConverter);
