├── .gitignore ├── tests ├── bir-react │ ├── public │ │ ├── robots.txt │ │ ├── favicon.ico │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ └── index.html │ ├── src │ │ ├── setupTests.js │ │ ├── App.test.js │ │ ├── index.css │ │ ├── reportWebVitals.js │ │ ├── index.js │ │ ├── App.css │ │ ├── App.js │ │ └── logo.svg │ ├── .gitignore │ ├── package.json │ └── README.md └── bir-vue │ ├── babel.config.js │ ├── src │ ├── main.js │ ├── assets │ │ └── logo.png │ ├── App.vue │ └── components │ │ └── HelloWorld.vue │ ├── public │ ├── favicon.ico │ └── index.html │ ├── vue.config.js │ ├── .gitignore │ ├── jsconfig.json │ ├── README.md │ └── package.json ├── replit.nix ├── src ├── browser_operations.js ├── data_operations.js ├── index.js └── scaling_operations.js ├── bin └── cut-release ├── dist ├── index.d.ts └── index.js ├── package.json ├── webpack.config.js ├── LICENSE ├── .github └── workflows │ └── npm-publish.yml ├── .replit └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .cache 3 | -------------------------------------------------------------------------------- /tests/bir-react/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /tests/bir-vue/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/cli-plugin-babel/preset' 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /tests/bir-vue/src/main.js: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue' 2 | import App from './App.vue' 3 | 4 | createApp(App).mount('#app') 5 | -------------------------------------------------------------------------------- /tests/bir-react/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericnograles/browser-image-resizer/HEAD/tests/bir-react/public/favicon.ico -------------------------------------------------------------------------------- /tests/bir-react/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericnograles/browser-image-resizer/HEAD/tests/bir-react/public/logo192.png -------------------------------------------------------------------------------- /tests/bir-react/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericnograles/browser-image-resizer/HEAD/tests/bir-react/public/logo512.png -------------------------------------------------------------------------------- /tests/bir-vue/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericnograles/browser-image-resizer/HEAD/tests/bir-vue/public/favicon.ico -------------------------------------------------------------------------------- /tests/bir-vue/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericnograles/browser-image-resizer/HEAD/tests/bir-vue/src/assets/logo.png -------------------------------------------------------------------------------- /replit.nix: -------------------------------------------------------------------------------- 1 | { pkgs }: { 2 | deps = [ 3 | pkgs.nodejs-16_x 4 | pkgs.nodePackages.typescript-language-server 5 | pkgs.yarn 6 | pkgs.replitPackages.jest 7 | ]; 8 | } -------------------------------------------------------------------------------- /tests/bir-vue/vue.config.js: -------------------------------------------------------------------------------- 1 | const { defineConfig } = require('@vue/cli-service') 2 | module.exports = defineConfig({ 3 | transpileDependencies: true, 4 | devServer: { 5 | allowedHosts: 'all' 6 | } 7 | }) 8 | -------------------------------------------------------------------------------- /src/browser_operations.js: -------------------------------------------------------------------------------- 1 | export function initializeOrGetImg () { 2 | return document.createElement('img'); 3 | } 4 | 5 | export function initializeOrGetCanvas () { 6 | return document.createElement('canvas'); 7 | } 8 | -------------------------------------------------------------------------------- /bin/cut-release: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eux -o pipefail 3 | 4 | # Usage: bin/cut-release 5 | # npm_version_type: major, minor, patch 6 | # Assumes you have proper access to NPM repo and GitHub repo 7 | npm version $1 8 | npm publish 9 | git push --tags 10 | -------------------------------------------------------------------------------- /dist/index.d.ts: -------------------------------------------------------------------------------- 1 | export interface Config { 2 | quality?: number 3 | maxWidth?: number 4 | maxHeight?: number 5 | debug?: boolean 6 | mimeType?: string 7 | } 8 | 9 | 10 | export function readAndCompressImage(file: File, userConfig?: Config): Promise; 11 | -------------------------------------------------------------------------------- /tests/bir-react/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /tests/bir-react/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /tests/bir-vue/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | 6 | # local env files 7 | .env.local 8 | .env.*.local 9 | 10 | # Log files 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | pnpm-debug.log* 15 | 16 | # Editor directories and files 17 | .idea 18 | .vscode 19 | *.suo 20 | *.ntvs* 21 | *.njsproj 22 | *.sln 23 | *.sw? 24 | -------------------------------------------------------------------------------- /tests/bir-vue/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "esnext", 5 | "baseUrl": "./", 6 | "moduleResolution": "node", 7 | "paths": { 8 | "@/*": [ 9 | "src/*" 10 | ] 11 | }, 12 | "lib": [ 13 | "esnext", 14 | "dom", 15 | "dom.iterable", 16 | "scripthost" 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/bir-react/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /tests/bir-react/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /tests/bir-vue/README.md: -------------------------------------------------------------------------------- 1 | # bir-vue 2 | 3 | ## Project setup 4 | ``` 5 | npm install 6 | ``` 7 | 8 | ### Compiles and hot-reloads for development 9 | ``` 10 | npm run serve 11 | ``` 12 | 13 | ### Compiles and minifies for production 14 | ``` 15 | npm run build 16 | ``` 17 | 18 | ### Lints and fixes files 19 | ``` 20 | npm run lint 21 | ``` 22 | 23 | ### Customize configuration 24 | See [Configuration Reference](https://cli.vuejs.org/config/). 25 | -------------------------------------------------------------------------------- /tests/bir-react/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /tests/bir-react/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | 7 | const root = ReactDOM.createRoot(document.getElementById('root')); 8 | root.render( 9 | 10 | 11 | 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /tests/bir-react/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /tests/bir-vue/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | <%= htmlWebpackPlugin.options.title %> 9 | 10 | 11 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "browser-image-resizer", 3 | "version": "2.4.1", 4 | "description": "A browser-based utility to downscale and resize images using ", 5 | "main": "dist/index.js", 6 | "author": "Eric Nograles ", 7 | "license": "MIT", 8 | "devDependencies": { 9 | "@babel/cli": "^7.2.3", 10 | "@babel/core": "^7.2.2", 11 | "@babel/preset-env": "^7.3.1", 12 | "babel-loader": "^8.0.5", 13 | "webpack": "^5.74.0", 14 | "webpack-cli": "^4.10.0" 15 | }, 16 | "scripts": { 17 | "build": "NODE_ENV=production webpack --mode=production", 18 | "dev": "webpack --watch --mode=development" 19 | }, 20 | "repository": "https://github.com/ericnograles/browser-image-resizer.git" 21 | } 22 | -------------------------------------------------------------------------------- /tests/bir-react/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | entry: './src/index.js', 5 | output: { 6 | path: path.resolve(__dirname, 'dist'), 7 | filename: 'index.js', 8 | library: 'BrowserImageResizer', 9 | libraryTarget: 'umd', 10 | umdNamedDefine: true 11 | }, 12 | module: { 13 | rules: [ 14 | { 15 | test: /\.js$/, 16 | use: { 17 | loader: 'babel-loader', 18 | options: { 19 | presets: [ 20 | [ 21 | "@babel/preset-env", 22 | { 23 | "targets": { 24 | "browsers": ["last 2 versions", "ie >= 11"] 25 | } 26 | } 27 | ] 28 | ] 29 | } 30 | } 31 | } 32 | ] 33 | } 34 | }; 35 | 36 | if (process.env.NODE_ENV !== 'production') { 37 | module.exports.devtool = 'eval-source-map' 38 | } 39 | -------------------------------------------------------------------------------- /tests/bir-react/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bir-react", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.16.5", 7 | "@testing-library/react": "^13.4.0", 8 | "@testing-library/user-event": "^13.5.0", 9 | "react": "^18.2.0", 10 | "react-dom": "^18.2.0", 11 | "react-scripts": "5.0.1", 12 | "web-vitals": "^2.1.4" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": [ 22 | "react-app", 23 | "react-app/jest" 24 | ] 25 | }, 26 | "browserslist": { 27 | "production": [ 28 | ">0.2%", 29 | "not dead", 30 | "not op_mini all" 31 | ], 32 | "development": [ 33 | "last 1 chrome version", 34 | "last 1 firefox version", 35 | "last 1 safari version" 36 | ] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/bir-vue/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bir-vue", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "core-js": "^3.8.3", 12 | "vue": "^3.2.13" 13 | }, 14 | "devDependencies": { 15 | "@babel/core": "^7.12.16", 16 | "@babel/eslint-parser": "^7.12.16", 17 | "@vue/cli-plugin-babel": "~5.0.0", 18 | "@vue/cli-plugin-eslint": "~5.0.0", 19 | "@vue/cli-service": "~5.0.0", 20 | "eslint": "^7.32.0", 21 | "eslint-plugin-vue": "^8.0.3" 22 | }, 23 | "eslintConfig": { 24 | "root": true, 25 | "env": { 26 | "node": true 27 | }, 28 | "extends": [ 29 | "plugin:vue/vue3-essential", 30 | "eslint:recommended" 31 | ], 32 | "parserOptions": { 33 | "parser": "@babel/eslint-parser" 34 | }, 35 | "rules": {} 36 | }, 37 | "browserslist": [ 38 | "> 1%", 39 | "last 2 versions", 40 | "not dead", 41 | "not ie 11" 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017-2021 Eric Nograles and others 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /tests/bir-react/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { readAndCompressImage } from "browser-image-resizer"; 3 | 4 | export default class App extends Component { 5 | state = { 6 | testType: "global", 7 | message: "Yo", 8 | image: null 9 | }; 10 | 11 | onChange = async event => { 12 | let image = await readAndCompressImage(event.target.files[0], { mimeType: 'image/jpeg', debug: true }); 13 | let base64Image = await this.convertToBase64(image); 14 | this.setState({ image: base64Image }); 15 | }; 16 | 17 | convertToBase64 = blob => { 18 | return new Promise(resolve => { 19 | var reader = new FileReader(); 20 | reader.onload = function() { 21 | resolve(reader.result); 22 | }; 23 | reader.readAsDataURL(blob); 24 | }); 25 | }; 26 | 27 | render() { 28 | const { image } = this.state; 29 | return ( 30 |
31 |

browser-image-resizer

32 |

Select a local file to compress

33 | 34 | compress-image-output 35 |
36 | ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/data_operations.js: -------------------------------------------------------------------------------- 1 | export function dataURItoBuffer(dataURI) { 2 | let byteString = atob(dataURI.split(',')[1]); 3 | let ab = new ArrayBuffer(byteString.length); 4 | let ia = new Uint8Array(ab); 5 | for (let i = 0; i < byteString.length; i++) { 6 | ia[i] = byteString.charCodeAt(i); 7 | } 8 | 9 | return ab; 10 | } 11 | 12 | export function dataURIToBlob(dataURI) { 13 | // convert base64 to raw binary data held in a string 14 | // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this 15 | let byteString = atob(dataURI.split(',')[1]); 16 | 17 | // separate out the mime component 18 | let mimeString = dataURI 19 | .split(',')[0] 20 | .split(':')[1] 21 | .split(';')[0]; 22 | 23 | // write the bytes of the string to an ArrayBuffer 24 | let ab = new ArrayBuffer(byteString.length); 25 | 26 | // create a view into the buffer 27 | let ia = new Uint8Array(ab); 28 | 29 | // set the bytes of the buffer to the correct values 30 | for (let i = 0; i < byteString.length; i++) { 31 | ia[i] = byteString.charCodeAt(i); 32 | } 33 | 34 | // write the ArrayBuffer to a blob, and you're done 35 | let blob = new Blob([ab], { type: mimeString }); 36 | return blob; 37 | } -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { initializeOrGetImg } from './browser_operations'; 2 | import { scaleImage } from './scaling_operations'; 3 | 4 | const DEFAULT_CONFIG = { 5 | quality: 0.5, 6 | maxWidth: 800, 7 | maxHeight: 600, 8 | autoRotate: true, 9 | debug: false, 10 | mimeType: 'image/jpeg' 11 | }; 12 | 13 | export function readAndCompressImage(file, userConfig) { 14 | return new Promise((resolve, reject) => { 15 | let img = initializeOrGetImg(); 16 | let reader = new FileReader(); 17 | let config = Object.assign({}, DEFAULT_CONFIG, userConfig); 18 | 19 | reader.onload = function(e) { 20 | img.onerror = function() { 21 | reject("cannot load image."); 22 | } 23 | img.onload = function() { 24 | let scaleImageOptions = { img, config } 25 | try { 26 | let blob = scaleImage(scaleImageOptions); 27 | resolve(blob) 28 | } catch (err) { 29 | reject(err) 30 | } 31 | }; 32 | img.src = e.target.result; 33 | }; 34 | 35 | try { 36 | reader.onerror = function() { 37 | reject("cannot read image file."); 38 | } 39 | reader.readAsDataURL(file); 40 | } catch (err) { 41 | reject(err) 42 | } 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Publish browser-image-resizer 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions/setup-node@v2 16 | with: 17 | node-version: 14 18 | - run: npm install 19 | 20 | publish-npm: 21 | needs: build 22 | runs-on: ubuntu-latest 23 | steps: 24 | - uses: actions/checkout@v2 25 | - uses: actions/setup-node@v1 26 | with: 27 | node-version: 12 28 | registry-url: https://registry.npmjs.org/ 29 | - run: npm publish 30 | env: 31 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 32 | 33 | # publish-gpr: 34 | # needs: build 35 | # runs-on: ubuntu-latest 36 | # steps: 37 | # - uses: actions/checkout@v2 38 | # - uses: actions/setup-node@v1 39 | # with: 40 | # node-version: 12 41 | # registry-url: https://npm.pkg.github.com/ 42 | # - run: npm ci 43 | # - run: npm publish 44 | # env: 45 | # NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} 46 | -------------------------------------------------------------------------------- /tests/bir-vue/src/App.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 44 | 45 | 58 | -------------------------------------------------------------------------------- /tests/bir-react/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /tests/bir-vue/src/components/HelloWorld.vue: -------------------------------------------------------------------------------- 1 | 32 | 33 | 41 | 42 | 43 | 59 | -------------------------------------------------------------------------------- /.replit: -------------------------------------------------------------------------------- 1 | 2 | hidden = [".config"] 3 | run = "npm i && npm run dev" 4 | 5 | [[hints]] 6 | regex = "Error \\[ERR_REQUIRE_ESM\\]" 7 | message = "We see that you are using require(...) inside your code. We currently do not support this syntax. Please use 'import' instead when using external modules. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)" 8 | 9 | [nix] 10 | channel = "stable-21_11" 11 | 12 | [env] 13 | XDG_CONFIG_HOME = "/home/runner/.config" 14 | PATH = "/home/runner/$REPL_SLUG/.config/npm/node_global/bin:/home/runner/$REPL_SLUG/node_modules/.bin" 15 | npm_config_prefix = "/home/runner/$REPL_SLUG/.config/npm/node_global" 16 | 17 | [gitHubImport] 18 | requiredFiles = [".replit", "replit.nix", ".config"] 19 | 20 | [packager] 21 | language = "nodejs" 22 | 23 | [packager.features] 24 | packageSearch = true 25 | guessImports = true 26 | enabledForHosting = false 27 | 28 | [unitTest] 29 | language = "nodejs" 30 | 31 | [languages.javascript] 32 | pattern = "**/{*.js,*.jsx,*.ts,*.tsx}" 33 | 34 | [languages.javascript.languageServer] 35 | start = [ "typescript-language-server", "--stdio" ] 36 | 37 | [debugger] 38 | support = true 39 | 40 | [debugger.interactive] 41 | transport = "localhost:0" 42 | startCommand = [ "dap-node" ] 43 | 44 | [debugger.interactive.initializeMessage] 45 | command = "initialize" 46 | type = "request" 47 | 48 | [debugger.interactive.initializeMessage.arguments] 49 | clientID = "replit" 50 | clientName = "replit.com" 51 | columnsStartAt1 = true 52 | linesStartAt1 = true 53 | locale = "en-us" 54 | pathFormat = "path" 55 | supportsInvalidatedEvent = true 56 | supportsProgressReporting = true 57 | supportsRunInTerminalRequest = true 58 | supportsVariablePaging = true 59 | supportsVariableType = true 60 | 61 | [debugger.interactive.launchMessage] 62 | command = "launch" 63 | type = "request" 64 | 65 | [debugger.interactive.launchMessage.arguments] 66 | args = [] 67 | console = "externalTerminal" 68 | cwd = "." 69 | environment = [] 70 | pauseForSourceMap = false 71 | program = "./index.js" 72 | request = "launch" 73 | sourceMaps = true 74 | stopOnEntry = false 75 | type = "pwa-node" 76 | -------------------------------------------------------------------------------- /tests/bir-react/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("BrowserImageResizer",[],e):"object"==typeof exports?exports.BrowserImageResizer=e():t.BrowserImageResizer=e()}(self,(()=>(()=>{"use strict";var t={d:(e,a)=>{for(var i in a)t.o(a,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:a[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function a(){return document.createElement("canvas")}function i(t){for(var e=atob(t.split(",")[1]),a=t.split(",")[0].split(":")[1].split(";")[0],i=new ArrayBuffer(e.length),o=new Uint8Array(i),r=0;r0&&t.maxSizet.height-1?t.height-1:Math.ceil(n),r=0;rt.width-1?t.width-1:Math.ceil(g),m=4*(r+e.width*o),f=4*(c+t.width*d),s=4*(l+t.width*d),u=4*(c+t.width*h),w=4*(l+t.width*h),p=g-c,y=n-d,v=i(t.data[f],t.data[s],t.data[u],t.data[w],p,y),e.data[m]=v,b=i(t.data[f+1],t.data[s+1],t.data[u+1],t.data[w+1],p,y),e.data[m+1]=b,x=i(t.data[f+2],t.data[s+2],t.data[u+2],t.data[w+2],p,y),e.data[m+2]=x,M=i(t.data[f+3],t.data[s+3],t.data[u+3],t.data[w+3],p,y),e.data[m+3]=M}(o,r,i),a.getContext("2d").putImageData(r,0,0),a}function n(t){var e=document.createElement("canvas");return e.width=t.width/2,e.height=t.height/2,e.getContext("2d").drawImage(t,0,0,e.width,e.height),e}t.r(e),t.d(e,{readAndCompressImage:()=>h});var d={quality:.5,maxWidth:800,maxHeight:600,autoRotate:!0,debug:!1,mimeType:"image/jpeg"};function h(t,e){return new Promise((function(h,g){var c=document.createElement("img"),l=new FileReader,m=Object.assign({},d,e);l.onload=function(t){c.onerror=function(){g("cannot load image.")},c.onload=function(){var t={img:c,config:m};try{var e=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.img,d=t.config,h=(t.orientation,a());h.width=e.width,h.height=e.height;var g=h.getContext("2d");"image/jpeg"===d.mimeType&&(g.fillStyle="#ffffff",g.fillRect(0,0,h.width,h.height),g.save()),g.drawImage(e,0,0),g.restore();for(var c=o(d,h);h.width>=2*c;)h=n(h);h.width>c&&(h=r(h,Object.assign(d,{outputWidth:c})));var l=h.toDataURL(d.mimeType,d.quality);return"function"==typeof d.onScale&&d.onScale(l),i(l)}(t);h(e)}catch(t){g(t)}},c.src=t.target.result};try{l.onerror=function(){g("cannot read image file.")},l.readAsDataURL(t)}catch(t){g(t)}}))}return e})())); -------------------------------------------------------------------------------- /tests/bir-react/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 39 | 40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /src/scaling_operations.js: -------------------------------------------------------------------------------- 1 | import { dataURIToBlob } from './data_operations'; 2 | import { initializeOrGetCanvas } from './browser_operations'; 3 | 4 | function findMaxWidth(config, canvas) { 5 | //Let's find the max available width for scaled image 6 | let ratio = canvas.width / canvas.height; 7 | let mWidth = Math.min( 8 | canvas.width, 9 | config.maxWidth, 10 | ratio * config.maxHeight 11 | ); 12 | if ( 13 | config.maxSize > 0 && 14 | config.maxSize < (canvas.width * canvas.height) / 1000 15 | ) 16 | mWidth = Math.min( 17 | mWidth, 18 | Math.floor((config.maxSize * 1000) / canvas.height) 19 | ); 20 | if (!!config.scaleRatio) 21 | mWidth = Math.min(mWidth, Math.floor(config.scaleRatio * canvas.width)); 22 | 23 | if (config.debug) { 24 | console.log( 25 | 'browser-image-resizer: original image size = ' + 26 | canvas.width + 27 | ' px (width) X ' + 28 | canvas.height + 29 | ' px (height)' 30 | ); 31 | console.log( 32 | 'browser-image-resizer: scaled image size = ' + 33 | mWidth + 34 | ' px (width) X ' + 35 | Math.floor(mWidth / ratio) + 36 | ' px (height)' 37 | ); 38 | } 39 | if (mWidth <= 0) { 40 | mWidth = 1; 41 | console.warn("browser-image-resizer: image size is too small"); 42 | } 43 | 44 | return mWidth; 45 | } 46 | 47 | function scaleCanvasWithAlgorithm(canvas, config) { 48 | let scaledCanvas = document.createElement('canvas'); 49 | 50 | let scale = config.outputWidth / canvas.width; 51 | 52 | scaledCanvas.width = canvas.width * scale; 53 | scaledCanvas.height = canvas.height * scale; 54 | 55 | let srcImgData = canvas 56 | .getContext('2d') 57 | .getImageData(0, 0, canvas.width, canvas.height); 58 | let destImgData = scaledCanvas 59 | .getContext('2d') 60 | .createImageData(scaledCanvas.width, scaledCanvas.height); 61 | 62 | applyBilinearInterpolation(srcImgData, destImgData, scale); 63 | 64 | scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0); 65 | 66 | return scaledCanvas; 67 | } 68 | 69 | function getHalfScaleCanvas(canvas) { 70 | let halfCanvas = document.createElement('canvas'); 71 | halfCanvas.width = canvas.width / 2; 72 | halfCanvas.height = canvas.height / 2; 73 | 74 | halfCanvas 75 | .getContext('2d') 76 | .drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height); 77 | 78 | return halfCanvas; 79 | } 80 | 81 | function applyBilinearInterpolation(srcCanvasData, destCanvasData, scale) { 82 | function inner(f00, f10, f01, f11, x, y) { 83 | let un_x = 1.0 - x; 84 | let un_y = 1.0 - y; 85 | return f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y; 86 | } 87 | let i, j; 88 | let iyv, iy0, iy1, ixv, ix0, ix1; 89 | let idxD, idxS00, idxS10, idxS01, idxS11; 90 | let dx, dy; 91 | let r, g, b, a; 92 | for (i = 0; i < destCanvasData.height; ++i) { 93 | iyv = i / scale; 94 | iy0 = Math.floor(iyv); 95 | // Math.ceil can go over bounds 96 | iy1 = 97 | Math.ceil(iyv) > srcCanvasData.height - 1 98 | ? srcCanvasData.height - 1 99 | : Math.ceil(iyv); 100 | for (j = 0; j < destCanvasData.width; ++j) { 101 | ixv = j / scale; 102 | ix0 = Math.floor(ixv); 103 | // Math.ceil can go over bounds 104 | ix1 = 105 | Math.ceil(ixv) > srcCanvasData.width - 1 106 | ? srcCanvasData.width - 1 107 | : Math.ceil(ixv); 108 | idxD = (j + destCanvasData.width * i) * 4; 109 | // matrix to vector indices 110 | idxS00 = (ix0 + srcCanvasData.width * iy0) * 4; 111 | idxS10 = (ix1 + srcCanvasData.width * iy0) * 4; 112 | idxS01 = (ix0 + srcCanvasData.width * iy1) * 4; 113 | idxS11 = (ix1 + srcCanvasData.width * iy1) * 4; 114 | // overall coordinates to unit square 115 | dx = ixv - ix0; 116 | dy = iyv - iy0; 117 | // I let the r, g, b, a on purpose for debugging 118 | r = inner( 119 | srcCanvasData.data[idxS00], 120 | srcCanvasData.data[idxS10], 121 | srcCanvasData.data[idxS01], 122 | srcCanvasData.data[idxS11], 123 | dx, 124 | dy 125 | ); 126 | destCanvasData.data[idxD] = r; 127 | 128 | g = inner( 129 | srcCanvasData.data[idxS00 + 1], 130 | srcCanvasData.data[idxS10 + 1], 131 | srcCanvasData.data[idxS01 + 1], 132 | srcCanvasData.data[idxS11 + 1], 133 | dx, 134 | dy 135 | ); 136 | destCanvasData.data[idxD + 1] = g; 137 | 138 | b = inner( 139 | srcCanvasData.data[idxS00 + 2], 140 | srcCanvasData.data[idxS10 + 2], 141 | srcCanvasData.data[idxS01 + 2], 142 | srcCanvasData.data[idxS11 + 2], 143 | dx, 144 | dy 145 | ); 146 | destCanvasData.data[idxD + 2] = b; 147 | 148 | a = inner( 149 | srcCanvasData.data[idxS00 + 3], 150 | srcCanvasData.data[idxS10 + 3], 151 | srcCanvasData.data[idxS01 + 3], 152 | srcCanvasData.data[idxS11 + 3], 153 | dx, 154 | dy 155 | ); 156 | destCanvasData.data[idxD + 3] = a; 157 | } 158 | } 159 | } 160 | 161 | export function scaleImage({ img, config, orientation = 1 } = {}) { 162 | let canvas = initializeOrGetCanvas() 163 | canvas.width = img.width; 164 | canvas.height = img.height; 165 | let ctx = canvas.getContext('2d'); 166 | if (config.mimeType === 'image/jpeg') { 167 | // Only apply to JPEGs, white background default, see #42 and #66 168 | ctx.fillStyle = '#ffffff'; 169 | ctx.fillRect(0, 0, canvas.width, canvas.height); 170 | ctx.save(); 171 | } 172 | 173 | // EXIF 174 | ctx.drawImage(img, 0, 0); 175 | ctx.restore(); 176 | 177 | let maxWidth = findMaxWidth(config, canvas); 178 | 179 | while (canvas.width >= 2 * maxWidth) { 180 | canvas = getHalfScaleCanvas(canvas); 181 | } 182 | 183 | if (canvas.width > maxWidth) { 184 | canvas = scaleCanvasWithAlgorithm( 185 | canvas, 186 | Object.assign(config, { outputWidth: maxWidth }) 187 | ); 188 | } 189 | 190 | let imageData = canvas.toDataURL(config.mimeType, config.quality); 191 | if (typeof config.onScale === 'function') config.onScale(imageData); 192 | return dataURIToBlob(imageData); 193 | } 194 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # browser-image-resizer 2 | 3 | A tiny (~7kb uncompressed, ~1kb compressed) browser-based library to downscale and/or resize images using ``. 4 | 5 | ## Introduction 6 | 7 | The code was part of Ross Turner's [HTML5-ImageUploader](https://github.com/rossturner/HTML5-ImageUploader). Note that this is meant to be a browser-only utility and will not work in Node.js. 8 | 9 | ## Demo 10 | 11 | - [Code Sandbox - NPM](https://codesandbox.io/s/6x20vw7l4r) 12 | - [Code Sandbox - In-Browser](https://codesandbox.io/s/nroxwpn21p) 13 | 14 | ## Installation 15 | 16 | ### NPM/Yarn 17 | 18 | - `npm install browser-image-resizer` 19 | - `yarn add browser-image-resizer` 20 | 21 | ### Browser 22 | 23 | ``` 24 | 25 | ``` 26 | 27 | ## Usage 28 | 29 | ### NPM/Yarn 30 | 31 | #### Promises 32 | 33 | ```javascript 34 | import { readAndCompressImage } from 'browser-image-resizer'; 35 | 36 | const config = { 37 | quality: 0.5, 38 | maxWidth: 800, 39 | maxHeight: 600, 40 | debug: true 41 | }; 42 | 43 | // Note: A single file comes from event.target.files on 44 | readAndCompressImage(file, config) 45 | .then(resizedImage => { 46 | // Upload file to some Web API 47 | const url = `http://localhost:3001/upload`; 48 | const formData = new FormData(); 49 | formData.append('images', resizedImage); 50 | const options = { 51 | method: 'POST', 52 | body: formData 53 | }; 54 | 55 | return fetch(url, options); 56 | }) 57 | .then(result => { 58 | // TODO: Handle the result 59 | console.log(result); 60 | }); 61 | ``` 62 | 63 | #### Async/Await 64 | 65 | ```javascript 66 | import { readAndCompressImage } from 'browser-image-resizer'; 67 | 68 | const config = { 69 | quality: 0.7, 70 | width: 800, 71 | height: 600 72 | }; 73 | 74 | // Note: A single file comes from event.target.files on 75 | async function uploadImage(file) { 76 | try { 77 | let resizedImage = await readAndCompressImage(file, config); 78 | 79 | const url = `http://localhost:3001/upload`; 80 | const formData = new FormData(); 81 | formData.append('images', resizedImage); 82 | const options = { 83 | method: 'POST', 84 | body: formData 85 | }; 86 | 87 | let result = await fetch(url, options); 88 | 89 | // TODO: Handle the result 90 | console.log(result); 91 | return result; 92 | } catch (error) { 93 | console.error(error); 94 | throw(error); 95 | } 96 | } 97 | ``` 98 | 99 | ### Browser 100 | 101 | #### Promises 102 | 103 | ```javascript 104 | const config = { 105 | quality: 0.5, 106 | maxWidth: 800, 107 | maxHeight: 600, 108 | debug: true 109 | }; 110 | 111 | // Note: A single file comes from event.target.files on 112 | BrowserImageResizer.readAndCompressImage(file, config) 113 | .then(resizedImage => { 114 | // Upload file to some Web API 115 | const url = `http://localhost:3001/upload`; 116 | const formData = new FormData(); 117 | formData.append('images', resizedImage); 118 | const options = { 119 | method: 'POST', 120 | body: formData 121 | }; 122 | 123 | return fetch(url, options); 124 | }) 125 | .then(result => { 126 | // TODO: Handle the result 127 | console.log(result); 128 | }); 129 | ``` 130 | 131 | #### Async/Await 132 | 133 | ```javascript 134 | 135 | const config = { 136 | quality: 0.7, 137 | width: 800, 138 | height: 600 139 | }; 140 | 141 | // Note: A single file comes from event.target.files on 142 | async function uploadImage(file) { 143 | try { 144 | let resizedImage = await BrowserImageResizer.readAndCompressImage(file, config); 145 | 146 | const url = `http://localhost:3001/upload`; 147 | const formData = new FormData(); 148 | formData.append('images', resizedImage); 149 | const options = { 150 | method: 'POST', 151 | body: formData 152 | }; 153 | 154 | let result = await fetch(url, options); 155 | 156 | // TODO: Handle the result 157 | console.log(result); 158 | return result; 159 | } catch (error) { 160 | console.error(error); 161 | throw(error); 162 | } 163 | } 164 | ``` 165 | 166 | 167 | ### readAndCompressImage(file, config) => Promise 168 | 169 | #### Inputs 170 | 171 | * `file`: A File object, usually from an `` 172 | * `config`: See below 173 | 174 | | Property Name | Purpose | Default Value | 175 | | ------------- |-------------| -----:| 176 | | `quality` | The quality of the image | 0.5 | 177 | | `maxWidth` | The maximum width for the downscaled image | 800 | 178 | | `maxHeight` | The maximum height for the downscaled image | 600 | 179 | | `autoRotate` | Reads EXIF data on the image to determine orientation | true | 180 | | `debug` | console.log image update operations | false | 181 | | `mimeType` | specify image output type other than jpeg | 'image/jpeg' | 182 | 183 | ### Outputs 184 | 185 | A Promise that yields an Image Blob 186 | 187 | ## Contributing 188 | 189 | The fastest way to contribute back is to fork the repl.it of this repo (https://replit.com/@grales/browser-image-resizer). Please open any Issues if you have trouble spinning it up. 190 | 191 | ### repl.it First-time Setup 192 | 193 | Upon forking of the repl.it, open a new Shell and follow these instructions: 194 | 195 | 1. Execute `npm link` at the top `~/browser-image-resizer` folder 196 | 1. Execute `cd tests/bir-vue` 197 | 2. Execute `npm i && npm link browser-image-resizer && npm run serve` 198 | 3. Your repl.it should automatically boot to a webview of a Vue 3 CLI SPA 199 | - This SPA will point to your built copy of browser-image-resizer that runs automatically when the repl.it boots 200 | 4. Modify any code at the top level `src/` and it will reflect on your Vue 3 CLI SPA test app 201 | 202 | ### repl.it Specifics 203 | 204 | - The repl.it above is configured to run the `dev` script of the library, which is a webpack-dev-server that auto-generates the `dist/` library which is the entry point of this library 205 | - The subsequent commands gives you an actual web application on which to verify your changes 206 | - If you prefer, you can do this locally as well, but the repl.it ensures a faster and more consistent onboarding 207 | --------------------------------------------------------------------------------