ericnograles / browser-image-resizer

A tiny browser-based library to downscale and/or resize images using canvas
MIT License
98 stars 42 forks source link

Quick Crop #9

Open taviroquai opened 5 years ago

taviroquai commented 5 years ago

Thanks for this lib! :)

Is it hard to implement a quick crop based on options width/height and center on the image?

Thanks!

ericnograles commented 5 years ago

@taviroquai thanks for using the library!

Hm, in terms of technical feasibility, it's doable. The way we scale the image is using canvas, so I imagine we could repurpose the drawImage function to do this: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

Based on that function signature, just shooting from the hip, we could have a config object that looks like the following:

const config = {
  quality: 0.5,
  maxWidth: 800,
  maxHeight: 600,
  autoRotate: true,
  crop: {
    left: 10,
    top: 20,
    width: 200,
    height: 100
  }
};

However, come to think of it, a better option would be to just create a separate, global cropImage function so it's not so tightly coupled to the readAndCompressImage function. That way, we keep single responsibility intact and doesn't confuse the API surface area of readAndCompressImage whose primary job already is to scale an image proportionally given a maximum height/width constraint.

This new cropImage function would probably take the crop property above as its config object and then do the necessary cropping work, e.g.

await cropImage(file, {
    left: 10,
    top: 20,
    width: 200,
    height: 100
  })

As for implementing this, I don't have much free time to do devote to this enhancement, so if you'd like to take a stab at a PR with the direction above, I can perhaps guide you through it? Otherwise, I can put it on deck for a future release when I have a bit more free time.