Pages

Friday, 20 December 2024

Image Resizer Tool



Image Resizer Tool

Image Resizer Tool

Preview will appear here after selecting an image

body { font-family: Arial, sans-serif; background: linear-gradient(135deg, #84fab0, #8fd3f4); color: #333; margin: 0; padding: 0; } .container { max-width: 600px; margin: 50px auto; background: #fff; border-radius: 10px; padding: 20px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); text-align: center; } h1 { color: #444; } .button { display: inline-block; padding: 10px 20px; background: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; margin: 10px 0; } .button:hover { background: #0056b3; } .image-preview { margin: 20px 0; padding: 10px; border: 2px dashed #007bff; border-radius: 5px; background: #f9f9f9; min-height: 150px; display: flex; align-items: center; justify-content: center; } .image-preview img { max-width: 100%; max-height: 150px; border-radius: 5px; } .resizer { margin: 20px 0; } label { font-weight: bold; margin-right: 10px; } input[type="number"] { width: 100px; padding: 5px; margin: 5px; border: 1px solid #ccc; border-radius: 5px; } const imageUpload = document.getElementById("image-upload"); const imagePreview = document.getElementById("image-preview"); const widthInput = document.getElementById("width-input"); const heightInput = document.getElementById("height-input"); const resizeButton = document.getElementById("resize-button"); const downloadButton = document.getElementById("download-button"); let originalImage = null; let resizedCanvas = document.createElement("canvas"); imageUpload.addEventListener("change", (event) => { const file = event.target.files[0]; if (file && file.type.startsWith("image/")) { const reader = new FileReader(); reader.onload = () => { const img = new Image(); img.onload = () => { originalImage = img; displayImage(img); }; img.src = reader.result; }; reader.readAsDataURL(file); } else { alert("Please upload a valid image file."); } }); resizeButton.addEventListener("click", () => { if (!originalImage) { alert("Please upload an image first."); return; } const width = parseInt(widthInput.value, 10) || originalImage.width; const height = parseInt(heightInput.value, 10) || originalImage.height; resizedCanvas.width = width; resizedCanvas.height = height; const ctx = resizedCanvas.getContext("2d"); ctx.clearRect(0, 0, width, height); ctx.drawImage(originalImage, 0, 0, width, height); displayImage(resizedCanvas); downloadButton.disabled = false; }); downloadButton.addEventListener("click", () => { if (!resizedCanvas) { alert("Please resize the image first."); return; } resizedCanvas.toBlob((blob) => { saveAs(blob, "resized-image.png"); }); }); function displayImage(imageElement) { imagePreview.innerHTML = ""; imagePreview.appendChild(imageElement.cloneNode()); }