compress gambar sebelum diupload dengan javascript

Bismillaahirrohmaanirrohiim…

Berikut ini cara kompress gambar sebelum diupload menggunakan javascript, tujuannya agar misalkan gambar dari HP yang ukurannya besar ini menjadi ringan saat upload.

Nah beginilah script kodenya:

<div class="mb-3">
                        <div class="" style="font-weight: 500;margin-bottom: .5rem;">Upload Foto/Video/File</div>
                        <div class="row" id="file_timeline_wrapper">
                            <div class="col-md-6 tr_file_timeline mb-2">
                                <table>
                                    <tr>
                                        <td style="width:30px;text-align: left;">
                                            <i class="bi bi-x-circle-fill" style="font-size: 150%;cursor: pointer;color: red;" onclick="hapus_file_timeline(this)"></i>
                                        </td>
                                        <td>
                                            <input type="file" id="id_tl_<?=getId()?>" class="form-control file_timeline" name="file_timeline[]" accept="image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx" />
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <button type="button" class="btn btn-sm btn-secondary" onclick="tambah_file_upload()">
                            <i class="bi bi-plus-circle"></i> Tambah File
                        </button>
                    </div>

                    <div class="mb-3">
                        <div id="previewFiles" class="mt-2"></div>
                    </div>

                    <span id="originalInfo"></span>
                    <span id="compressedInfo"></span>

Kode javascriptnya:

$(document).on("change", ".file_timeline", async function(e) {
    let id_tl = $(this).attr("id");
    

    const file = e.target.files[0];
    if (!file) return;
    if (!file.type.startsWith(\'image/\')) return;

    $("#originalInfo").text(`Ukuran file: ${(file.size / 1024).toFixed(2)} KB`);

    // kompres gambar
    const compressed = await compressImage(file, 0.7, 800, 800);
    const compressedUrl = URL.createObjectURL(compressed);

    $("#imagePreview").attr("src", compressedUrl).removeClass("d-none");
    $("#compressedInfo").text(` => compressed: ${(compressed.size / 1024).toFixed(2)} KB`);

    // Ganti isi input file dengan file hasil kompres
    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(compressed);
    document.getElementById(id_tl).files = dataTransfer.files;
});
async function compressImage(file, quality = 0.7, maxWidth = 1000, maxHeight = 1000) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = event => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            // hitung rasio baru
            let width = img.width;
            let height = img.height;

            if (width > maxWidth || height > maxHeight) {
              const ratio = Math.min(maxWidth / width, maxHeight / height);
              width *= ratio;
              height *= ratio;
            }

            const canvas = document.createElement(\'canvas\');
            const ctx = canvas.getContext(\'2d\');
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);

            canvas.toBlob(blob => {
              if (!blob) return reject(new Error(\'Gagal membuat blob\'));
              const compressedFile = new File([blob], file.name, { type: blob.type });
              resolve(compressedFile);
            }, \'image/jpeg\', quality);
          };
        };
        reader.onerror = err => reject(err);
      });
    }
function tambah_file_upload() {
    const file_timeline_wrapper = $("#file_timeline_wrapper");
    const new_file_timeline = file_timeline_wrapper.find(".tr_file_timeline").last().clone();
    new_file_timeline.find("input").val("").attr("id", "id_tl_"+randomId());
    file_timeline_wrapper.append(new_file_timeline);
}
function randomId() {
    return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
function hapus_file_timeline(element) {
    if ($(".tr_file_timeline").length > 1) {
        $(element).closest(".tr_file_timeline").remove();
    } else {
        //alert("File timeline minimal 1");
    }
}

Demikian, semoga bermanfaat

Baca Juga:   Cara setting htaccess di nginx

Bagikan

You May Also Like

About the Author: rasupe

Discover more from Rasupe

Subscribe now to keep reading and get access to the full archive.

Continue reading