-2

I have an cdn Image https://cdn.shopify.com/s/files/1/0234/8017/2591/products/young-man-in-bright-fashion_925x_f7029e2b-80f0-4a40-a87b-834b9a283c39.jpg, and want to convert it into Thumbnail

Kumar
  • 436
  • 1
  • 4
  • 16
  • What does this have to do with React? – T J Apr 30 '21 at 08:15
  • What exactly do you mean by thumnbnail? Looks smaller? Less size? another format? – T J Apr 30 '21 at 08:17
  • i have been working on react App and i have to show users, thumbnails instead of original Image. – Kumar Apr 30 '21 at 08:21
  • I removed the reactjs tag because you didn't ask a question specific to React, share any React code, etc.. If React is relevant then please include your React code for context. Even your answer is completely React unrelated. Just because you are working with React doesn't mean it's relevant to the issue of image conversion/resizing. – Drew Reese Apr 30 '21 at 08:22
  • Please only add tags relevant to the question. For eg. if you are working on a windows machine it doesn't mean you should tag the question with windows. – T J Apr 30 '21 at 08:24
  • yeah sure, i will keep in mind next time. And Thnx for guide me – Kumar Apr 30 '21 at 08:27

1 Answers1

0

Converting Image into Thumbnail
if we have CDN or Image URL link then, we need to convert that link into blob or base64 and then base64 into FILE type Object. Here is the answer that convert CDN into base64 and base64 into FILE type object https://stackoverflow.com/a/62227874/13081559

Here is example of `FILE type Object`

: File
lastModified: 1591250106736
lastModifiedDate: Thu Jun 04 2020 11:25:06 GMT+0530 (India Standard 
Time) {}
name: "img.jpeg"
size: 369742
type: "image/jpeg"
webkitRelativePath: ""

Now, Here is the code that convert FILE type Object into thumbnail. It take two arguments, first argument is file (it will be converted FILE object) and the other is Bound-box [x,y] for thumbnail.

let boundBox = [100,100]
const toThumbnail = (file, boundBox) => {
if (!boundBox || boundBox.length != 2) {
throw "You need to give the boundBox"
}
var reader = new FileReader();
var canvas = document.createElement("canvas")
var ctx = canvas.getContext('2d');
return new Promise((resolve, reject) => {
reader.onload = function (event) {
  var img = new Image();
  img.onload = function () {
    var scaleRatio = Math.min(...boundBox) / Math.max(img.width, img.height)
    let w = img.width * scaleRatio
    let h = img.height * scaleRatio
    canvas.width = w;
    canvas.height = h;
    ctx.drawImage(img, 0, 0, w, h);
    let data = canvas.toDataURL(file.type)
    let myData = {
      url: data
    }
     // Here is thumbnail data >>>>>
    return resolve(myData) 
  }
  img.src = event.target.result;
}
reader.readAsDataURL(file);
})
}
Kumar
  • 436
  • 1
  • 4
  • 16