1

I want to resize image and convert it to base64 before sending via network. It takes so long if it is 10MB or more image so I need first to resize it on front, convert it and then send it to the server

html:

<div class="file__item ui-state-default current_ad current_ad_files">
       <img width="88px" height="88px" src="{{ photo.image.url }}" alt="">
       <input type="hidden" class="photo-base64" id="{{ photo.pk }}"
       value="{{ photo.get_base64_image }}" multiple>
       <a href="" class="file__delete" atr='sorok'></a>
</div>

js:

function convertToBase64(file, inputId) {
        var reader = new FileReader();
        reader.onload = function () {
            let base64String = reader.result.replace("data:", "")
                .replace(/^.+,/, "");
            $(`#${inputId}`).val(base64String)
        }
        reader.readAsDataURL(file);
    }

function getUploadedFileNode(file) {
        let randomId = getRandomID();
        return {
            inputId: randomId,
            node: `
            <div class="file__item ui-state-default file__item--sortable ui-sortable-handle">
                <img width="88px" height="88px" src="${URL.createObjectURL(file)}" alt="">
                <input type="hidden" class="photo-base64" id="${randomId}" value="" multiple>
                <a href="" class="file__delete"></a>
            </div>
            `
        }
    }

let addedFileNode = getUploadedFileNode(lastFile) // lastFile is an regular image from looping over multiupload
convertToBase64(lastFile, addedFileNode.inputId)

PS: front is written in pure javascript and jquery.

James Z
  • 12,104
  • 10
  • 27
  • 43
  • Does this answer your question? [Resize image with javascript canvas (smoothly)](https://stackoverflow.com/questions/19262141/resize-image-with-javascript-canvas-smoothly) – Yogi May 24 '22 at 23:12
  • Hmm, maybe yes, but just in case I'll wait for other option. Btw, is canvas built in js? Or I have to install it? – Pythonista May 24 '22 at 23:15
  • This is very easy to do and there are many pages of duplicate questions on SO to guide you. All modern browsers support canvas. – Yogi May 24 '22 at 23:16
  • Oh okay, you believe this is all I need to do? :( – Pythonista May 24 '22 at 23:18
  • I've used this method in production applications to resize images before upload and it's never been a problem. – Yogi May 24 '22 at 23:20
  • Huge thanks to you. May I ask few silly questions? – Pythonista May 24 '22 at 23:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/245011/discussion-between-pythonista-and-yogi). – Pythonista May 24 '22 at 23:31

0 Answers0