Advertisement
Guest User

Isolate ImageCompressor

a guest
Jul 16th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 0.99 KB | None | 0 0
  1. import 'dart:io';
  2. import 'dart:isolate';
  3.  
  4. import 'dart:ui';
  5.  
  6. import 'package:image/image.dart';
  7.  
  8. class ImageCompressor{
  9.   ImageCompressor();
  10.  
  11.  
  12.  
  13.   static Future<void> getCompressedImage(SendPort sendPort) async {
  14.     ReceivePort receivePort = ReceivePort();
  15.  
  16.     sendPort.send(receivePort.sendPort);
  17.     List msg = (await receivePort.first) as List;
  18.  
  19.     File fileImg = msg[0];
  20.     SendPort replyPort = msg[1];
  21.  
  22.     Image image = decodeImage(await fileImg.readAsBytes());
  23.  
  24.     if (image.width > 800) {
  25.       image = copyResize(image, width: 800);
  26.     }
  27.  
  28.     replyPort.send(image);
  29.   }
  30.  
  31.  
  32.   static Future<Image> compressImage(File file) async {
  33.     ReceivePort receivePort = ReceivePort();
  34.  
  35.     await Isolate.spawn(getCompressedImage, receivePort.sendPort);
  36.     SendPort sendPort = await receivePort.first;
  37.  
  38.     ReceivePort receivePort2 = ReceivePort();
  39.  
  40.     sendPort.send([
  41.       file,
  42.       receivePort2.sendPort,
  43.     ]);
  44.  
  45.  
  46.     return await receivePort2.first;
  47.   }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement