Image Resize

5 * 1024 * 1024) { die(“Maximum 5MB image allowed”); } $file = $_FILES[‘image’][‘tmp_name’]; $size = intval($_POST[‘size’]); $unit = $_POST[‘unit’]; $format = $_POST[‘format’]; $bg = $_POST[‘bgcolor’]; $targetBytes = ($unit === ‘MB’) ? $size * 1024 * 1024 : $size * 1024; $srcData = file_get_contents($file); $srcImg = imagecreatefromstring($srcData); if (!$srcImg) die(“Invalid Image”); $w = imagesx($srcImg); $h = imagesy($srcImg); // New image with background $newImg = imagecreatetruecolor($w, $h); list($r,$g,$b) = sscanf($bg, “#%02x%02x%02x”); $bgColor = imagecolorallocate($newImg, $r, $g, $b); imagefill($newImg, 0, 0, $bgColor); imagecopy($newImg, $srcImg, 0, 0, 0, 0, $w, $h); // Exact size logic $min = 1; $max = 100; $final = null; while ($min <= $max) { $q = floor(($min + $max) / 2); ob_start(); if ($format === 'png') { imagepng($newImg, null, 9); } else { imagejpeg($newImg, null, $q); } $data = ob_get_clean(); $len = strlen($data); if ($len > $targetBytes) { $max = $q – 1; } elseif ($len < $targetBytes) { $final = $data; $min = $q + 1; } else { $final = $data; break; } } if (!$final) die("Exact size not possible, change size slightly"); // Fast download if ($format === 'png') { header("Content-Type: image/png"); $ext = "png"; } else { header("Content-Type: image/jpeg"); $ext = $format; } header("Content-Disposition: attachment; filename=Resized_Image.$ext"); header("Content-Length: " . strlen($final)); header("Cache-Control: no-store, no-cache"); echo $final; exit; } ?> Exact Image Resizer Tool

Exact Image Resizer (Same Page)

Scroll to Top