Anyone have experience with uploading image files,...
# prisma-whats-new
m
Anyone have experience with uploading image files, then cropping and saving cropped image file (usually base64 encoded) back into GraphQL? What I have so far: https://gist.github.com/heymartinadams/d082a1bda3e40c663140649ac999f646#file-base64-image-then-upload-to-graphcool-js
a
@martin I would do that server-side in a webtask. Then use any of the standard node.js libraries to crop (like node-easyimage or sharp), and upload the file from there. Beware that the way to interact with the File API is... not optimal... So it might need some tweaking.
m
Thank you, @agartha, for pointing me in the right direction… (sigh… why can’t things be simpler for a simpleton like me?)
a
It's development 😄
😢 1
😂 1
We do things no other industry does, we reinvent the wheel, over and over and over again, then form a consortium to decide on the shape of the wheel, decide that square is the best, and stick to that decision for 10 years, regardless what anyone, especially the user, thinks 😄
🤔 1
😂 2
m
That sounds about right. Especially as js devs.
g
This is what I do, all in browser:
Copy code
const optimizeImage = (file, maxWidth = 960) =>
    new Promise(resolve => {
        const filesize = file.size / 1024;

        let reader = new FileReader();
        reader.onload = e => {
            let imageDataUrl = e.target.result;

            if (filesize <= 500) {
                return resolve(imageDataUrl);
            }

            // Create a temporary image so that we can compute the height of the downscaled image.
            const image = new Image();
            image.onload = () => {
                const oldWidth = image.width;
                const oldHeight = image.height;
                const newHeight = Math.floor(oldHeight / oldWidth * maxWidth);

                // Create a temporary canvas to draw the downscaled image on.
                const canvas = document.createElement('canvas');
                canvas.width = maxWidth;
                canvas.height = newHeight;

                // Draw the downscaled image on the canvas and return the new data URL.
                const ctx = canvas.getContext('2d');
                ctx.drawImage(image, 0, 0, maxWidth, newHeight);
                resolve(canvas.toDataURL('image/jpeg', 0.7));
            };

            image.src = imageDataUrl;
        };
        reader.readAsDataURL(file);
    });
m
Thanks, @gildas. We were able to figure it out, too. Noted here: https://github.com/graphcool-examples/functions/tree/master/cloudinary-images