0

A situation I'm trying to solve. I'm loading an image onto a canvas, then making some edits(resize, crop etc.) to it and saving the resultant image to a folder. Now if the original image is larger than the canvas dimensions, the resultant image is cropped. Hence I'm trying to scale the image to a smaller size that fits in the canvas, apply the effects, and then scale it back to the original dimensions and save it. Is there a way to do this?

My JS pseudo code is somewhat like this:

//load the image using drawimage
//compare image dimensions with canvas dimensions, scale down the image if large
//apply the effects
(I have done till here)

//scale it back to original size
//save

How do I scale it to and fro using canvas scale method? I'm assuming I have to calculate a widths ratio for scaling down and up like so:

scale_down_width = image_orig_width / canvas_width
scale_down_height = image_orig_height / canvas_height

//For scaling down
scale(1*scale_down_width, 1*scale_down_height)

//For scaling up
scale(1/scale_down_width, 1/scale_down_height)

Am I doing this correct? Scale down works fine, but scale up doesn't, how do I do it right?

Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87
  • Do you use `ctx.scale`? If so, I believe you're doing it the other way round - you're scaling up with a factor of 2 when the image is twice as wide. – pimvdb Dec 07 '12 at 21:21
  • Yep, I'm using scale. I don't understand how it works exactly! – Rutwick Gangurde Dec 08 '12 at 16:17
  • 1
    Btw, I found if I set the canavas height and width attributes (inline `height` and `width`) to a value larger than any of my images drawn, and use css style `height` and `width` properties to keep the canvas small, the image fits inside the canvas, but saves in the original size! – Rutwick Gangurde Dec 08 '12 at 16:20
  • I'm not sure what exactly you're trying to accomplish. If you scale down the image, apply effects, and scale it up again, the quality of the new image will obviously be lower than the original image. Note that canvas is pixel based. – pimvdb Dec 08 '12 at 19:10
  • I found out I don't need to use `scale`. Please see this: http://stackoverflow.com/questions/13779429/canvas-inline-height-and-width-attributes-overridden-with-css-styles-is-this-is – Rutwick Gangurde Dec 09 '12 at 05:52

0 Answers0