Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
dd87538
scaling and image quality done
balvinderz Sep 25, 2021
c3c1344
image scaling and quality done
balvinderz Sep 25, 2021
cf0ee4d
implement max width max height and imageQuality for web
balvinderz Sep 27, 2021
130f78a
added maxWidth max height and imageQuality for web
balvinderz Sep 27, 2021
b8d3d65
dartfmt
balvinderz Sep 27, 2021
be720c2
revert pubspec.yaml of image_picker
balvinderz Sep 27, 2021
754cec5
run format
balvinderz Sep 27, 2021
942ac46
added image resizer class
balvinderz Sep 30, 2021
982d40a
Merge branch 'master' of https://github.com/flutter/plugins into comp…
balvinderz Sep 30, 2021
6145cf5
Merge branch 'compress_file_web' of https://github.com/balvinderz/plu…
balvinderz Sep 30, 2021
91f92e6
fix calculate size logic
balvinderz Sep 30, 2021
b10408f
fix if condition in resizeImage
balvinderz Sep 30, 2021
42d8191
image resizer done
balvinderz Sep 30, 2021
019a738
added utils test'
balvinderz Sep 30, 2021
2b1842d
update readme
balvinderz Sep 30, 2021
5f7a0dd
add image resizer tests
balvinderz Sep 30, 2021
f61b965
dartfmt
balvinderz Sep 30, 2021
5b477e6
add licenses
balvinderz Sep 30, 2021
60e0b9f
remove path dependancy
balvinderz Sep 30, 2021
7a63323
fix typo and remove extra space
balvinderz Sep 30, 2021
c75b036
fix doc comment
balvinderz Sep 30, 2021
f5e6d45
remove double spaces
balvinderz Sep 30, 2021
d38de67
review changes
balvinderz Oct 2, 2021
5c352f6
fix typo
balvinderz Oct 4, 2021
08b8240
use completeError
balvinderz Oct 4, 2021
7151d71
remove unused imports
balvinderz Oct 4, 2021
a3bbc58
dartfmt
balvinderz Oct 4, 2021
d81990b
fix typo
balvinderz Oct 4, 2021
c90eff3
remove 1 doc comment
balvinderz Oct 4, 2021
811b3fb
update tests and resizing algorithm
balvinderz Oct 5, 2021
3e4d7c1
Review changes
balvinderz Oct 5, 2021
554e996
move image resizer files in src
balvinderz Oct 6, 2021
d15b8b1
dartfmt
balvinderz Oct 6, 2021
b87f0cf
dartfmt again
balvinderz Oct 6, 2021
d99a702
Fix some review comments
ditman Oct 16, 2021
5e825ab
Slight update in the CHANGELOG
ditman Oct 16, 2021
c4d057e
Merge branch 'master' into compress_file_web
ditman Oct 16, 2021
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
Prev Previous commit
Next Next commit
added utils test'
  • Loading branch information
balvinderz committed Sep 30, 2021
commit 019a738ce899fca3b4a722d4c710c6027040713c
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,15 @@ class ImagePickerPlugin extends ImagePickerPlatform {

late html.Element _target;

final _imageResizer = ImageResizer();
late ImageResizer _imageResizer;

/// A constructor that allows tests to override the function that creates file inputs.
ImagePickerPlugin({
@visibleForTesting ImagePickerPluginTestOverrides? overrides,
}) : _overrides = overrides {
@visibleForTesting ImageResizer? imageResizer,
}) : _overrides = overrides
{
_imageResizer = imageResizer ?? ImageResizer();
_target = _ensureInitialized(_kImagePickerInputsDomId);
}

Expand Down Expand Up @@ -95,7 +98,7 @@ class ImagePickerPlugin extends ImagePickerPlatform {
String? capture,
}) {
html.FileUploadInputElement input =
createInputElement(accept, capture) as html.FileUploadInputElement;
createInputElement(accept, capture) as html.FileUploadInputElement;
_injectAndActivate(input);
return _getSelectedFile(input);
}
Expand Down Expand Up @@ -125,7 +128,8 @@ class ImagePickerPlugin extends ImagePickerPlatform {
accept: _kAcceptImageMimeType,
capture: capture,
);
return _imageResizer.resizeImageIfNeeded(files.first, maxWidth, maxHeight, imageQuality);
return _imageResizer.resizeImageIfNeeded(
files.first, maxWidth, maxHeight, imageQuality);
}

/// Returns an [XFile] containing the video that was picked.
Expand Down Expand Up @@ -161,10 +165,10 @@ class ImagePickerPlugin extends ImagePickerPlatform {
double? maxHeight,
int? imageQuality,
}) async {
return await Future.wait((await getFiles(
accept: _kAcceptImageMimeType, multiple: true))
.map((e) =>
_imageResizer.resizeImageIfNeeded(e, maxWidth, maxHeight, imageQuality)));
return await Future.wait(
(await getFiles(accept: _kAcceptImageMimeType, multiple: true)).map(
(e) => _imageResizer.resizeImageIfNeeded(
e, maxWidth, maxHeight, imageQuality)));
}

/// Injects a file input with the specified accept+capture attributes, and
Expand Down Expand Up @@ -216,7 +220,7 @@ class ImagePickerPlugin extends ImagePickerPlatform {
/// Returns a list of selected files.
List<html.File>? _handleOnChangeEvent(html.Event event) {
final html.FileUploadInputElement input =
event.target as html.FileUploadInputElement;
event.target as html.FileUploadInputElement;
return _getFilesFromInput(input);
}

Expand Down Expand Up @@ -256,9 +260,7 @@ class ImagePickerPlugin extends ImagePickerPlatform {
name: file.name,
length: file.size,
lastModified: DateTime.fromMillisecondsSinceEpoch(
file.lastModified ?? DateTime
.now()
.millisecondsSinceEpoch,
file.lastModified ?? DateTime.now().millisecondsSinceEpoch,
),
mimeType: file.type,
);
Expand All @@ -281,8 +283,7 @@ class ImagePickerPlugin extends ImagePickerPlatform {
var target = html.querySelector('#${id}');
if (target == null) {
final html.Element targetElement =
html.Element.tag('flt-image-picker-inputs')
..id = id;
html.Element.tag('flt-image-picker-inputs')..id = id;

html.querySelector('body')!.children.add(targetElement);
target = targetElement;
Expand All @@ -293,10 +294,11 @@ class ImagePickerPlugin extends ImagePickerPlatform {
/// Creates an input element that accepts certain file types, and
/// allows to `capture` from the device's cameras (where supported)
@visibleForTesting
html.Element createInputElement(String? accept,
String? capture, {
bool multiple = false,
}) {
html.Element createInputElement(
String? accept,
String? capture, {
bool multiple = false,
}) {
if (_hasOverrides) {
return _overrides!.createInputElement(accept, capture);
}
Expand All @@ -320,19 +322,18 @@ class ImagePickerPlugin extends ImagePickerPlatform {
}
}


// Some tools to override behavior for unit-testing
/// A function that creates a file input with the passed in `accept` and `capture` attributes.
@visibleForTesting
typedef OverrideCreateInputFunction = html.Element Function(
String? accept,
String? capture,
);
String? accept,
String? capture,
);

/// A function that extracts list of files from the file `input` passed in.
@visibleForTesting
typedef OverrideExtractMultipleFilesFromInputFunction = List<html.File>
Function(html.Element? input);
Function(html.Element? input);

/// Overrides for some of the functionality above.
@visibleForTesting
Expand Down
76 changes: 11 additions & 65 deletions packages/image_picker/image_picker_for_web/lib/image_resizer.dart
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import 'dart:async';
import 'dart:math';
import 'dart:ui';

import 'package:image_picker_for_web/image_resizer_utils.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
import 'dart:html' as html;

/// Resizes images
class ImageResizer {
/// Resizes the image if needed
/// Does not support gif image
///
Future<XFile> resizeImageIfNeeded(XFile file, double? maxWidth,
double? maxHeight, int? imageQuality) async {
if ((maxWidth == null &&
maxHeight == null
) || !_isImageQualityValid(imageQuality) ||
if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) ||
file.mimeType == "image/gif") {
//TODO Implement maxWidth and maxHeight for image/gif
return file;
Expand All @@ -28,8 +26,11 @@ class ImageResizer {

await imageLoadCompleter.future;

final newImageSize = calculateSize(imageElement.width!.toDouble(),
imageElement.height!.toDouble(), maxWidth, maxHeight);
final newImageSize = calculateSizeOfScaledImage(
imageElement.width!.toDouble(),
imageElement.height!.toDouble(),
maxWidth,
maxHeight);
final canvas = html.CanvasElement();
canvas.width = newImageSize.width.toInt();
canvas.height = newImageSize.height.toInt();
Expand All @@ -40,68 +41,13 @@ class ImageResizer {
context.drawImageScaled(
imageElement, 0, 0, canvas.width!, canvas.height!);
}
final calculatedImageQuality = ((min(imageQuality ?? 100, 100)) /
100.0);
final blob = await canvas.toBlob(
file.mimeType,
final calculatedImageQuality = ((min(imageQuality ?? 100, 100)) / 100.0);
final blob = await canvas.toBlob(file.mimeType,
calculatedImageQuality); // Image quality only works for jpeg and webp images
return XFile(html.Url.createObjectUrlFromBlob(blob),
mimeType: file.mimeType,
name: file.name,
name: "scaled_" + file.name,
lastModified: DateTime.now(),
length: blob.size);
}

/// Calculates the size of the scaled image from [maxWidth] and [maxHeigth.
Size calculateSize(double imageWidth, double imageHeight, double? maxWidth,
double? maxHeight) {
double originalWidth = imageWidth;
double originalHeight = imageHeight;

bool hasMaxWidth = maxWidth != null;
bool hasMaxHeight = maxHeight != null;
double width = hasMaxWidth ? min(maxWidth, originalWidth) : originalWidth;
double height =
hasMaxHeight ? min(maxHeight, originalHeight) : originalHeight;
bool shouldDownscaleWidth = hasMaxWidth && maxWidth < originalWidth;
bool shouldDownscaleHeight = hasMaxHeight && maxHeight < originalHeight;
bool shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight;
if (shouldDownscale) {
double downscaledWidth =
((height / originalHeight) * originalWidth).floorToDouble();
double downscaledHeight =
((width / originalWidth) * originalHeight).floorToDouble();

if (width < height) {
if (!hasMaxWidth) {
width = downscaledWidth;
} else {
height = downscaledHeight;
}
} else if (height < width) {
if (!hasMaxHeight) {
height = downscaledHeight;
} else {
width = downscaledWidth;
}
} else {
if (originalWidth < originalHeight) {
width = downscaledWidth;
} else if (originalHeight < originalWidth) {
height = downscaledHeight;
}
}
}
if (hasMaxHeight) {
assert(height <= maxHeight);
}
if (hasMaxWidth) {
assert(width <= maxWidth);
}
return Size(width, height);
}

bool _isImageQualityValid(int? imageQuality) {
return imageQuality == null || (imageQuality >= 0 && imageQuality <= 100);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import 'dart:math';

import 'dart:ui';

///a function that checks if an image needs to be resized or not
bool imageResizeNeeded(double? maxWidth, double? maxHeight, int? imageQuality) {
bool resizeNeeded =
(maxWidth != null || maxHeight != null || imageQuality != null);
if (resizeNeeded) {
if (imageQuality != null) {
return isImageQualityValid(imageQuality);
} else {
return true;
}
} else {
return false;
}
}

/// a function that checks if image quality is between [0,100] or null
bool isImageQualityValid(int imageQuality) {
return (imageQuality >= 0 && imageQuality <= 100);
}

/// a functions that calculates the size of the scaled image.
/// imageWidth is the width of the image
/// imageHeight is the height of the image
/// maxWidth is the maximum width of the scaled image
/// maxHeight is the maximum height of the scaled image
Size calculateSizeOfScaledImage(double imageWidth, double imageHeight,
double? maxWidth, double? maxHeight) {
double originalWidth = imageWidth;
double originalHeight = imageHeight;

bool hasMaxWidth = maxWidth != null;
bool hasMaxHeight = maxHeight != null;
double width = hasMaxWidth ? min(maxWidth, originalWidth) : originalWidth;
double height =
hasMaxHeight ? min(maxHeight, originalHeight) : originalHeight;
bool shouldDownscaleWidth = hasMaxWidth && maxWidth < originalWidth;
bool shouldDownscaleHeight = hasMaxHeight && maxHeight < originalHeight;
bool shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight;
if (shouldDownscale) {
double downscaledWidth =
((height / originalHeight) * originalWidth).floorToDouble();
double downscaledHeight =
((width / originalWidth) * originalHeight).floorToDouble();

if (width < height) {
if (!hasMaxWidth) {
width = downscaledWidth;
} else {
height = downscaledHeight;
}
} else if (height < width) {
if (!hasMaxHeight) {
height = downscaledHeight;
} else {
width = downscaledWidth;
}
} else {
if (originalWidth < originalHeight) {
width = downscaledWidth;
} else if (originalHeight < originalWidth) {
height = downscaledHeight;
}
}
}
return Size(width, height);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import 'dart:math';
import 'dart:ui';

import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker_for_web/image_resizer_utils.dart';

void main() {
group('Image Resizer Utils', () {
group("calculateSizeOfScaledImage", () {
test(
"scaled image height and width are same if max width and max height are same as image's width and height ",
() {
expect(calculateSizeOfScaledImage(500, 300, 500, 300), Size(500, 300));
});
test(
"scaled image height and width are same if max width and max height are null",
() {
expect(
calculateSizeOfScaledImage(500, 300, null, null), Size(500, 300));
});
test("image size is scaled when maxWidth is set", () {
final imageSize = Size(500, 300);
final maxWidth = 400;
final scaledSize = calculateSizeOfScaledImage(
imageSize.width, imageSize.height, maxWidth.toDouble(), null);
expect(scaledSize.height<=imageSize.height,true);
expect(scaledSize.width<=maxWidth,true);

});
test("image size is scaled when maxHeight is set", () {
final imageSize = Size(500, 300);
final maxHeight = 400;
final scaledSize = calculateSizeOfScaledImage(
imageSize.width, imageSize.height, null,maxHeight.toDouble());
expect(scaledSize.height<=maxHeight,true);
expect(scaledSize.width<=imageSize.width,true);

});
test("image size is scaled when both maxWidth and maxHeight is set", () {
final imageSize = Size(1120, 2000);
final maxHeight = 1200;
final maxWidth = 99;
final scaledSize = calculateSizeOfScaledImage(
imageSize.width, imageSize.height, maxWidth.toDouble(),maxHeight.toDouble());
expect(scaledSize.height<=maxHeight,true);
expect(scaledSize.width<=maxWidth,true);

});
});
group("imageResizeNeeded", () {
test("image needs to be resized when maxWidth is set", () {
expect(imageResizeNeeded(50, null, null), true);
});
test("image needs to be resized when maxHeight is set", () {
expect(imageResizeNeeded(null, 50, null), true);
});
test("image needs to be resized when imageQuality is set", () {
expect(imageResizeNeeded(null, null, 100), true);
});
test("image will not be resized when imageQuality is not valid", () {
expect(imageResizeNeeded(null, null, 101), false);
expect(imageResizeNeeded(null, null, -1), false);
});
});
group("isImageQualityValid", () {
test("image quality is valid in 0 to 100", () {
expect(isImageQualityValid(50), true);
expect(isImageQualityValid(0), true);
expect(isImageQualityValid(100), true);
});
test(
"image quality is not valid when imageQuality is less than 0 or greater than 100",
() {
expect(isImageQualityValid(-1), false);
expect(isImageQualityValid(101), false);
});
});
});
}