question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

getCroppedImg function in the FAQ section loses resolution

See original GitHub issue

See the screenshot below which was cropped from a very high res image and run through the example function:

image (4)

We were able to modify the function like so to not lose quality (while limiting the final size of the image):

export const getBlobFromCroppedImage = (image, crop, maxHeight) => {
  const canvas = document.createElement('canvas');
  console.warn(image.naturalWidth, image.naturalHeight);
  const scaleX = image.naturalWidth / image.width;
  const scaleY = image.naturalHeight / image.height;
  const aspectRatio = crop.width/crop.height;

  let canvasHeight = crop.height * scaleY;
  let canvasWidth = crop.width * scaleX;

  if (maxHeight && (canvasHeight > maxHeight)) {
    canvasHeight = maxHeight;
    canvasWidth = Math.round(canvasHeight * aspectRatio);
  }

  canvas.height = canvasHeight;
  canvas.width = canvasWidth;

  const ctx = canvas.getContext('2d');

  ctx.drawImage(
    image,
    crop.x * scaleX,
    crop.y * scaleY,
    crop.width * scaleX,
    crop.height * scaleY,
    0,
    0,
    canvasWidth,
    canvasHeight,
  );

  return new Promise((resolve) => {
    canvas.toBlob((blob) => {
      resolve(blob);
    }, 'image/jpeg', 1);
  });
};

Could we consider updating the example, or make it clear that the current example doesn’t work well for cases where the displayed image/crop is much smaller than the natural size of the image?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
SkrewEverythingcommented, Jun 17, 2021

@ryshep111 Some lines were missing in the FAQ code, which are present in the codesandbox.

@DominicTobias Maybe you need to update the code snippet in the FAQ

These 5 lines must be added:

  const pixelRatio = window.devicePixelRatio;
  canvas.width = crop.width * pixelRatio;
  canvas.height = crop.height * pixelRatio;

  ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  ctx.imageSmoothingQuality = "high";

The full code in the FAQ must be:

/**
 * @param {HTMLImageElement} image - Image File Object
 * @param {Object} crop - crop Object
 * @param {String} fileName - Name of the returned file in Promise
 */
export function getCroppedImg(image, crop, fileName) {
  const canvas = document.createElement("canvas");
  const scaleX = image.naturalWidth / image.width;
  const scaleY = image.naturalHeight / image.height;
  canvas.width = crop.width;
  canvas.height = crop.height;
  const ctx = canvas.getContext("2d");

  // New lines to be added
  const pixelRatio = window.devicePixelRatio;
  canvas.width = crop.width * pixelRatio;
  canvas.height = crop.height * pixelRatio;
  ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  ctx.imageSmoothingQuality = "high";

  ctx.drawImage(
    image,
    crop.x * scaleX,
    crop.y * scaleY,
    crop.width * scaleX,
    crop.height * scaleY,
    0,
    0,
    crop.width,
    crop.height
  );

  // As Base64 string
  // const base64Image = canvas.toDataURL("image/jpeg");
  // return base64Image;

  // As a blob
  return new Promise((resolve, reject) => {
    canvas.toBlob(
      (blob) => {
        blob.name = fileName;
        resolve(blob);
      },
      "image/jpeg",
      1
    );
  });
}
0reactions
DominicTobiascommented, Jun 22, 2021

Thanks @SkrewEverything will update it

Read more comments on GitHub >

github_iconTop Results From Across the Web

Retain Image Quality after Crop on front-end? #263 - GitHub
function getCroppedImg(image, crop) { const cropWidth = image.naturalWidth * (crop.width / 100) const cropHeight ... Cropping without losing resolution #373.
Read more >
React Image-crop showing error as it is not uploading the ...
I am new to react and javascript so lots of things, still confuses me. Can anyone please have a look at the code...
Read more >
Photoshop Printing FAQs: Image re-sizing, cropping, & more
Frequently asked questions regarding Adobe Photoshop including image re-sizing, cropping, resolution adjustments, nesting images, and the ...
Read more >
Top React image cropping libraries - LogRocket Blog
Image cropping is a method for manipulating images to remove any unwanted elements. By changing the aspect ratio or orientation, ...
Read more >
Crop images in Illustrator - Adobe Support
The Crop Image feature works only on the currently selected image. Also, linked images become embedded after you crop them.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found