Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
50bc1f1
added callback to resize function, added test case, edited README.md
hendrik-scholz Aug 22, 2018
466a5eb
moved index.js, edited README.md
hendrik-scholz Aug 22, 2018
a3b8b88
changed name of resized image parameter
hendrik-scholz Aug 22, 2018
8ae7186
renamed resize function, edited example
hendrik-scholz Aug 22, 2018
5285669
added input validation
hendrik-scholz Aug 22, 2018
c550ae5
added typeof check to Base64 input parameter
hendrik-scholz Aug 23, 2018
91a484c
edited description, authors, dependencies, and version number
hendrik-scholz Aug 23, 2018
9f564c5
added description of input parameters
hendrik-scholz Aug 23, 2018
9b45062
changed indentation
hendrik-scholz Aug 23, 2018
e6d0edd
added export
hendrik-scholz Aug 23, 2018
eff6e5b
increased version number, added description of usage
hendrik-scholz Aug 23, 2018
ff25e25
added input validation for height and width
hendrik-scholz Aug 24, 2018
dcb343c
increased version number
hendrik-scholz Aug 24, 2018
0ba0d7b
made function IE compatible
Aug 24, 2018
71ba9f2
increased version number
Aug 24, 2018
1f8ded4
added test cases for input validation of height and width
hendrik-scholz Aug 24, 2018
8d3a403
Merge branch 'develop' of https://github.com/hendrik-scholz/resize-ba…
hendrik-scholz Aug 24, 2018
7cd9894
added files array to exclude test folder
hendrik-scholz Aug 25, 2018
817f8cf
added URL to issue tracker
hendrik-scholz Aug 25, 2018
81ac51a
added link to Angular example project
hendrik-scholz Aug 25, 2018
acff59e
fixed typo
hendrik-scholz Aug 25, 2018
7343b0e
edited input validation
hendrik-scholz Aug 26, 2018
ec0c739
edited retrictions section and usage section
hendrik-scholz Aug 26, 2018
0673ee8
moved input validation to separate function
hendrik-scholz Sep 27, 2018
c9b3358
created functions for proportional and free resizing
hendrik-scholz Sep 27, 2018
844f1a4
edited description
hendrik-scholz Sep 27, 2018
e1859fa
added ration for width and height
hendrik-scholz Sep 27, 2018
f658ec0
increased version number
hendrik-scholz Sep 27, 2018
5de13bc
edited test description
hendrik-scholz Sep 27, 2018
d3fc503
fixed typo
hendrik-scholz Sep 29, 2018
94faa3e
changed way of test execution
hendrik-scholz Nov 1, 2018
f9f4d46
removed conditions in function resizeBase64ForMaxWidthAndMaxHeight to…
Nov 26, 2018
e5873f1
added missing lets
Jan 3, 2019
0de10fe
Merge pull request #1 from denwehrle/master
hendrik-scholz Jan 4, 2019
adb3bec
changed parameter name in description
hendrik-scholz Mar 26, 2019
135c552
removed bower.json
hendrik-scholz Sep 6, 2019
28e4a99
removed links to Angular and Vue example projects
hendrik-scholz Mar 6, 2020
f5db2dc
added package-lock.json
hendrik-scholz Mar 6, 2020
eb64d0e
add CHANGELOG file
hendrik-scholz Mar 6, 2020
86de5da
added LICENSE file
hendrik-scholz Mar 6, 2020
d32c2a4
fixed link in CHANGELOG file
hendrik-scholz Mar 6, 2020
3fb9839
updated version number
hendrik-scholz Mar 6, 2020
ada6a67
updated README file
hendrik-scholz Nov 3, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/resize-base64.code-workspace
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.2.1] - 2020-03-06
### Fixed
- fixed link in CHANGELOG file

## [1.2.0] - 2020-03-06
### Added
- added CHANGELOG file
- added LICENSE file

## [1.1.3] - 2018-11-26
### Removed
- removed conditions in function resizeBase64ForMaxWidthAndMaxHeight to allow free resizing

[Unreleased]: https://github.com/hendrik-scholz/resize-base64/compare/1.2.1...HEAD
[1.2.1]: https://github.com/hendrik-scholz/resize-base64/compare/1.2.0...1.2.1
[1.2.0]: https://github.com/hendrik-scholz/resize-base64/compare/1.1.3...1.2.0
[1.1.3]: https://github.com/hendrik-scholz/resize-base64/releases/tag/1.1.3
11 changes: 11 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
ISC License (ISC)

Copyright 2020 hendrik-scholz

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
68 changes: 60 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,73 @@
## When passing an image base64 as first argument to the function, it returns the base64 of the resized image. maxWidth and maxHeight are optional.
# resize-base64

#### Note: This is a font-end package.
Functions that resize a Base64 image. Pass a Base64 string of an image, the maximum width, the maximum height, a success callback, and an error callback to the function. The function returns the resized image in the success callback.

| Function | Description |
| ------ | ----------- |
| resizeBase64ForMaxWidth | resizes an image to the maximum width, the aspect ratio of the image is maintained |
| resizeBase64ForMaxHeight | resizes an image to the maximum height, the aspect ratio of the image is maintained |
| resizeBase64ForMaxWidthAndMaxHeight | resizes an image to the maximum width and maximum height, the aspect ratio of the image is not maintained |

#### What is it for?
`If you have a base64 image and you would like to resize it, this function will return a base64 image resizes to your height and width specifications.`
Every function takes the parameters listed below.

| Parameter | Description |
| ------ | ----------- |
| base64String | the image to resize as a Base64 string |
| maxWidth | the maxmium width that the image should be resized to |
| maxHeight | the maxmium height that the image should be resized to |
| successCallback | the callback that contains the resized image as a Base64 string |
| errorCallback | the callback that contains the error that occurred during resizing |

#### How do I install it?
`bower install resize-base64 --save`
## Restrictions

* The function can only be used in frontend code.
* Since enlarging images is not desirable due to the loss of quality, the functions resizeBase64ForMaxWidth and resizeBase64ForMaxHeight do not support it. Use the function resizeBase64ForMaxWidthAndMaxHeight for free resizing (shrinking and enlarging).

## Installation

##### To use
```
var image = resizebase64(base64, maxWidth, maxHeight);
npm i --save https://github.com/hendrik-scholz/resize-base64/#master
```

## Test

1. Copy the index.js and the test folder with all its files to an HTTP server.
2. Request the HTML file for the test case in the browser, e.g. http://localhost/resize-base64/test/resizeBase64ImageFrom320x240ToMaxHeight120.html

## Example

```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="module">
import { resizeBase64ForMaxHeight } from '../index.js';

let base64Image_320x240 = 'data:image/jpeg;base64,/9j/4AAQSk...';
let maxWidth = 2;
let maxHeight = 120;

let successCallback = function(resizedImage) {
document.getElementById('originalImage').src = base64Image_320x240;
document.getElementById('resizedImage').src = resizedImage;
};

let errorCallback = function(errorMessage) {
alert(errorMessage);
};

resizeBase64ForMaxHeight(base64Image_320x240, maxWidth, maxHeight, successCallback, errorCallback);
</script>
</head>
<body>
<img id="originalImage">

<img id="resizedImage">
</body>
</html>
```

See test/resizeBase64ImageFrom320x240ToMaxHeight120.html for details.

![Resize Example](screenshots/resize.png "Resize Example")
24 changes: 0 additions & 24 deletions bower.json

This file was deleted.

179 changes: 143 additions & 36 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,143 @@
resizebase64 = function(base64, maxWidth, maxHeight){


// Max size for thumbnail
if(typeof(maxWidth) === 'undefined') maxWidth = 500;
if(typeof(maxHeight) === 'undefined') maxHeight = 500;

// Create and initialize two canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
var copyContext = canvasCopy.getContext("2d");

// Create original image
var img = new Image();
img.src = base64;

// Determine new ratio based on max size
var ratio = 1;
if(img.width > maxWidth)
ratio = maxWidth / img.width;
else if(img.height > maxHeight)
ratio = maxHeight / img.height;

// Draw original image in second canvas
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);

// Copy and resize second canvas to first canvas
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

return canvas.toDataURL();
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(search, pos) {
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
};
}

const DEFAULT_RATIO = 1;

function validateInput(base64String, maxWidth, maxHeight) {
let validationResult = {
isValid: false,
errorMessage: 'An error occurred.'
};

if(!base64String) {
validationResult.errorMessage = 'The input parameter base64String is ' + base64String + '.';
} else if(typeof(base64String) != 'string') {
validationResult.errorMessage = 'The input parameter base64String is not of type \'string\'.';
} else if(!base64String.startsWith('data:image')) {
validationResult.errorMessage = 'The input parameter base64String does not start with \'data:image\'.';
} else if(!maxWidth) {
validationResult.errorMessage = 'The input parameter maxWidth is ' + maxWidth + '.';
} else if(typeof(maxWidth) != 'number') {
validationResult.errorMessage = 'The input parameter maxWidth is not of type \'number\'.';
} else if(maxWidth < 2) {
validationResult.errorMessage = 'The input parameter maxWidth must be at least 2 pixel.';
} else if(!maxHeight) {
validationResult.errorMessage = 'The input parameter maxHeight is ' + maxHeight + '.';
} else if(typeof(maxHeight) != 'number') {
validationResult.errorMessage = 'The input parameter maxHeight is not of type \'number\'.';
} else if(maxHeight < 2) {
validationResult.errorMessage = 'The input parameter maxHeight must be at least 2 pixel.';
} else {
validationResult.isValid = true;
validationResult.errorMessage = null;
}

return validationResult;
}

function maxWidthRatioFunction(imageWidth, imageHeight, targetWidth, targetHeight) {
let ratio = DEFAULT_RATIO;

if(imageWidth > targetWidth) {
ratio = targetWidth / imageWidth;
}

return {
width: ratio,
height: ratio
};
}

function maxHeightRatioFunction(imageWidth, imageHeight, targetWidth, targetHeight) {
let ratio = DEFAULT_RATIO;

if(imageHeight > targetHeight) {
ratio = targetHeight / imageHeight;
}

return {
width: ratio,
height: ratio
};
}

function maxWidthMaxHeightRatioFunction(imageWidth, imageHeight, targetWidth, targetHeight) {
let widthRatio = targetWidth / imageWidth;
let heightRatio = targetHeight / imageHeight;

return {
width: widthRatio,
height: heightRatio
};
}

function resizeBase64ForMaxWidth(base64String, maxWidth, maxHeight, successCallback, errorCallback) {
let validationResult = validateInput(base64String, maxWidth, maxHeight);

if(validationResult.isValid === true) {
resizeBase64(base64String, maxWidth, maxHeight, maxWidthRatioFunction, successCallback, errorCallback);
} else {
errorCallback(validationResult.errorMessage);
}
}

function resizeBase64ForMaxHeight(base64String, maxWidth, maxHeight, successCallback, errorCallback) {
let validationResult = validateInput(base64String, maxWidth, maxHeight);

if(validationResult.isValid === true) {
resizeBase64(base64String, maxWidth, maxHeight, maxHeightRatioFunction, successCallback, errorCallback);
} else {
errorCallback(validationResult.errorMessage);
}
}

function resizeBase64ForMaxWidthAndMaxHeight(base64String, maxWidth, maxHeight, successCallback, errorCallback) {
let validationResult = validateInput(base64String, maxWidth, maxHeight);

if(validationResult.isValid === true) {
resizeBase64(base64String, maxWidth, maxHeight, maxWidthMaxHeightRatioFunction, successCallback, errorCallback);
} else {
errorCallback(validationResult.errorMessage);
}
}

function resizeBase64(base64String, maxWidth, maxHeight, ratioFunction, successCallback, errorCallback) {
// Create and initialize two canvas
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let canvasCopy = document.createElement("canvas");
let copyContext = canvasCopy.getContext("2d");

// Create original image
let img = new Image();
img.src = base64String;

img.onload = function() {
let ratioResult = ratioFunction(img.width, img.height, maxWidth, maxHeight);
let widthRatio = ratioResult.width;
let heightRatio = ratioResult.height;

// Draw original image in second canvas
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);

// Copy and resize second canvas to first canvas
canvas.width = img.width * widthRatio;
canvas.height = img.height * heightRatio;
ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

successCallback(canvas.toDataURL());
};

img.onerror = function() {
errorCallback('Error while loading image.');
};
};

export { resizeBase64ForMaxWidth };
export { resizeBase64ForMaxHeight };
export { resizeBase64ForMaxWidthAndMaxHeight };
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 15 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
{
"name": "resize-base64",
"version": "1.0.13",
"description": "A function that resizes a base64 image",
"version": "1.2.1",
"description": "A function that resizes a Base64 image",
"files": [
"index.js",
"README.md"
],
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
Expand All @@ -13,8 +17,13 @@
"picture"
],
"author": "Daniel Izhar <dizhar888@gmail.com> (http://daniwebmaster.com)",
"license": "ISC",
"dependencies": {
"create-readme": "^1.1.0"
}
"contributors": [
{
"name": "Hendrik Scholz"
}
],
"bugs": {
"url": "https://github.com/hendrik-scholz/resize-base64/issues"
},
"license": "ISC"
}
Binary file added screenshots/resize.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions test/resizeBase64ImageFrom320x240ToMaxHeight120.html

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions test/resizeBase64ImageFrom320x240ToMaxHeight480.html

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions test/resizeBase64ImageFrom320x240ToMaxWidth100xMaxHeight100.html

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions test/resizeBase64ImageFrom320x240ToMaxWidth160.html

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions test/resizeBase64ImageFrom320x240ToMaxWidth640.html

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions test/resizeBase64ImageInvalidBase64String.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="module">
import { resizeBase64ForMaxWidthAndMaxHeight } from '../index.js';

let base64Image_320x240 = 'data:image/jpeg;base64,invalidBase64String';
let maxWidth = 75;
let maxHeight = 75;

let successCallback = function(resizedImage) {
document.getElementById('resizedImage').src = resizedImage;
};

let errorCallback = function(errorMessage) {
alert(errorMessage);
};

resizeBase64ForMaxWidthAndMaxHeight(base64Image_320x240, maxWidth, maxHeight, successCallback, errorCallback);
</script>
</head>
<body>
<img id="resizedImage">
</body>
</html>
Loading