HTML5 Pre-resize images before uploading

前端 未结 10 2467
野的像风
野的像风 2020-11-22 15:53

Here\'s a noodle scratcher.

Bearing in mind we have HTML5 local storage and xhr v2 and what not. I was wondering if anyone could find a work

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 16:11

    The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).

    I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):

    private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
        if (width <= maxWidth && height <= maxHeight)
          return { width, height };
        else if (width / maxWidth > height / maxHeight)
          return { width: maxWidth, height: height * maxWidth / width};
        else
          return { width: width * maxHeight / height, height: maxHeight };
      }
    

提交回复
热议问题