chore: Adjust image and thumbnail compression

This commit is contained in:
Krille Fear 2021-11-26 16:12:52 +01:00
parent 7d6af9bf59
commit 08601b351c
3 changed files with 38 additions and 22 deletions

View File

@ -29,11 +29,7 @@ class _SendFileDialogState extends State<SendFileDialog> {
Future<void> _send() async {
var file = widget.file;
if (file is MatrixImageFile && !origImage) {
try {
file = await file.resizeImage();
} catch (e) {
// couldn't resize
}
file = await file.resizeImage(quality: 40, max: 1200);
}
await widget.room.sendFileEventWithThumbnail(file);
}

View File

@ -10,11 +10,23 @@ import 'package:image/image.dart';
import 'package:matrix/matrix.dart';
extension ResizeImage on MatrixFile {
static const int max = 1200;
static const int max = 800;
static const int quality = 20;
Future<MatrixImageFile> resizeImage({bool calcBlurhash = true}) async {
final bytes = await compute<Uint8List, Uint8List>(resizeBytes, this.bytes);
Future<MatrixImageFile> resizeImage({
bool calcBlurhash = true,
int max = ResizeImage.max,
int quality = ResizeImage.quality,
}) async {
final bytes = mimeType == 'image/gif'
? this.bytes
: await compute<_ResizeBytesConfig, Uint8List>(
resizeBytes,
_ResizeBytesConfig(
this.bytes,
max: max,
quality: quality,
));
final blurhash = calcBlurhash
? await compute<Uint8List, BlurHash>(createBlurHash, bytes)
: null;
@ -31,17 +43,29 @@ Future<BlurHash> createBlurHash(Uint8List file) async {
return BlurHash.encode(image, numCompX: 4, numCompY: 3);
}
Future<Uint8List> resizeBytes(Uint8List file) async {
var image = decodeImage(file)!;
Future<Uint8List> resizeBytes(_ResizeBytesConfig config) async {
var image = decodeImage(config.bytes)!;
// Is file already smaller than max? Then just return.
if (math.max(image.width, image.height) > ResizeImage.max) {
if (math.max(image.width, image.height) > config.max) {
// Use the larger side to resize.
final useWidth = image.width >= image.height;
image = useWidth
? copyResize(image, width: ResizeImage.max)
: copyResize(image, height: ResizeImage.max);
? copyResize(image, width: config.max)
: copyResize(image, height: config.max);
}
return Uint8List.fromList(encodeJpg(image, quality: ResizeImage.quality));
return Uint8List.fromList(encodeJpg(image, quality: config.quality));
}
class _ResizeBytesConfig {
final Uint8List bytes;
final int max;
final int quality;
const _ResizeBytesConfig(
this.bytes, {
this.max = ResizeImage.max,
this.quality = ResizeImage.quality,
});
}

View File

@ -29,16 +29,12 @@ extension RoomSendFileExtension on Room {
bool waitUntilSent,
}) async {
MatrixFile thumbnail;
try {
if (file is MatrixImageFile) {
thumbnail = await file.resizeImage();
if (file is MatrixImageFile) {
thumbnail = await file.resizeImage();
if (thumbnail.size > file.size ~/ 2) {
thumbnail = null;
}
if (thumbnail.size > file.size ~/ 2) {
thumbnail = null;
}
} catch (e) {
// send no thumbnail
}
return sendFileEvent(