Flutter & Firebase: Compression before upload image - firebase

I want to send photo selected by user in my app to Firebase Storage. I have a simple class with property _imageFile which is set like this:
File _imageFile;
_getImage() async {
var fileName = await ImagePicker.pickImage();
setState(() {
_imageFile = fileName;
});
}
after that I send photo like with this code:
final String rand1 = "${new Random().nextInt(10000)}";
final String rand2 = "${new Random().nextInt(10000)}";
final String rand3 = "${new Random().nextInt(10000)}";
final StorageReference ref = FirebaseStorage.instance.ref().child('${rand1}_${rand2}_${rand3}.jpg');
final StorageUploadTask uploadTask = ref.put(_imageFile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
print(downloadUrl);
The problem is that the photos are often very large. Is there any method in Flutter/Dart to compress and resize photo before upload? I am ok with loss of quality.

June 05, 2020 - Update
The image_picker plugin now supports an imageQuality paramater. You can do something like
ImagePicker imagePicker = ImagePicker();
PickedFile compressedImage = await imagePicker.getImage(
source: ImageSource.camera,
imageQuality: 85,
);
Old Answer
or if you want to compress an image without using ImagePicker
I ran into this and was able to accomplish compression / resizing with the Dart image package along with path provider. You can look at dart image api and examples for other ways and more help.
Here's what I did:
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart';
import 'dart:math' as Math;
void compressImage() async {
File imageFile = await ImagePicker.pickImage();
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
int rand = new Math.Random().nextInt(10000);
Im.Image image = Im.decodeImage(imageFile.readAsBytesSync());
Im.Image smallerImage = Im.copyResize(image, 500); // choose the size here, it will maintain aspect ratio
var compressedImage = new File('$path/img_$rand.jpg')..writeAsBytesSync(Im.encodeJpg(image, quality: 85));
}
Then I uploaded compressedImage to firebase storage. You can adjust the quality that the jpg is saved with using the quality property, in my case I chose 85 (out of 100).
Hope this helps! Let me know if you have any questions.

The image_picker plugin is currently very simple. It would be straightforward to add an option for specifying the desired size/quality of the picked image. If you do this, please send us a pull request!

Use image_picker plugin and call pick image function as
Future<File> imageFile = ImagePicker.pickImage(source: ImageSource.gallery , maxHeight: 200 , maxWidth: 200 );
change maxHeight and maxWidth to whatever size of image you need.

There are many solutions :
Use image_picker package:
You can use the built-in imageQuality property of ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the quality of the original image.
First, add image_picker as a dependency in your pubspec.yaml file.
Usage
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 25,
);
setState(() {
_image = image;
});
}
The advantage of this approach is that it is embedded in the
image_picker package and is therefore incredibly easy to use.
You can also adjust the quality from the Image widget.
Use filterQuality to set the FilterQuality of the image.
Example :
Image.asset('assets/kab1.png', filterQuality: FilterQuality.high,),
These properties are present in AssetImage , NetworkImage , FileImage and MemoryImage.
You can also simply resize the image (Resizing an image can compress it). To do so, try the ResizeImage widget
Another solution is to use flutter_image_compress package

Besides mentioning this native library:
https://pub.dartlang.org/packages/flutter_image_compress
This is a fully dart based compressor with isolates, which might make the compression parallel to UI thread in multi core CPUs.
You might want to use compute function which makes using isolates simpler:
https://docs.flutter.io/flutter/foundation/compute.html
https://flutter.io/cookbook/networking/background-parsing/
import 'package:image/image.dart' as ImageLib;
import 'package:path_provider/path_provider.dart';
Future<void> getCompressedImage(SendPort sendPort) async {
ReceivePort receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
List msg = (await receivePort.first) as List;
String srcPath = msg[0];
String name = msg[1];
String destDirPath = msg[2];
SendPort replyPort = msg[3];
ImageLib.Image image =
ImageLib.decodeImage(await new File(srcPath).readAsBytes());
if (image.width > 500 || image.height > 500) {
image = ImageLib.copyResize(image, 500);
}
File destFile = new File(destDirPath + '/' + name);
await destFile.writeAsBytes(ImageLib.encodeJpg(image, quality: 60));
replyPort.send(destFile.path);
}
Future<File> compressImage(File f) async {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(getCompressedImage, receivePort.sendPort);
SendPort sendPort = await receivePort.first;
ReceivePort receivePort2 = ReceivePort();
sendPort.send([
f.path,
f.uri.pathSegments.last,
(await getTemporaryDirectory()).path,
receivePort2.sendPort,
]);
var msg = await receivePort2.first;
return new File(msg);
}
if (false ==
await SimplePermissions.checkPermission(
Permission.ReadExternalStorage)) {
await SimplePermissions.requestPermission(
Permission.ReadExternalStorage);
}
File img = await ImagePicker.pickImage(
source: ImageSource.gallery);
if (null != img) {
img = await compressImage(img);
}

The following code is what I use to take an image with the camera and then compress it:
import 'dart:async' show Future;
import 'dart:io' show File;
import 'package:flutter/foundation.dart' show compute;
import 'package:flutter/material.dart' show BuildContext;
import 'package:image/image.dart' as Im;
import 'dart:math' as Math;
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;
Future<File> takeCompressedPicture(BuildContext context) async {
var _imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
if (_imageFile == null) {
return null;
}
// You can have a loading dialog here but don't forget to pop before return file;
final tempDir = await getTemporaryDirectory();
final rand = Math.Random().nextInt(10000);
_CompressObject compressObject =
_CompressObject(_imageFile, tempDir.path, rand);
String filePath = await _compressImage(compressObject);
print('new path: ' + filePath);
File file = File(filePath);
// Pop loading
return file;
}
Future<String> _compressImage(_CompressObject object) async {
return compute(_decodeImage, object);
}
String _decodeImage(_CompressObject object) {
Im.Image image = Im.decodeImage(object.imageFile.readAsBytesSync());
Im.Image smallerImage = Im.copyResize(
image, 1024); // choose the size here, it will maintain aspect ratio
var decodedImageFile = File(object.path + '/img_${object.rand}.jpg');
decodedImageFile.writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 85));
return decodedImageFile.path;
}
class _CompressObject {
File imageFile;
String path;
int rand;
_CompressObject(this.imageFile, this.path, this.rand);
}
You can call this very easy with this:
import 'path/to/compress_image.dart' as CompressImage;
// ...
File file = await CompressImage.takeCompressedPicture(context);

While i am using
package:image/image.dart
facing below issues
showing blank page while converting image ( may be taking so much process while compressing image)
After compression image was stretched and not looking good
Then used below plugin, same working fine without any issue, even faster and what i expected
https://github.com/btastic/flutter_native_image.git
steps and method available in above link.

You can use a plugin called flutter_image_compress
// Active image file
File _imageFile;
// Select an image via gallery or camera
Future<void> _pickImage(ImageSource source) async {
File selected = await ImagePicker.pickImage(source: source);
// Compress plugin
File compressedImage = await FlutterImageCompress.compressAndGetFile(
selected.path,
selected.path,
quality: 50,
);
setState(() {
_imageFile = compressedImage;
print('compressedimagesize: ${_imageFile.lengthSync()}');
});
}
Voila! Compressed file image

Since you are using Firebase, one option would be using the Extension - Resize Image. It gives you the option to keep or delete the original image and it is very easy to install and use.

You can do as follows,
//Compressing Image
File compressedImg = await FlutterNativeImage.compressImage(
_image.path,
quality: 70,
);
//Compressing Image

Well
1. If you are in mobile you could use flutter_image_compress: ^1.0.0 will do the work
Eg.
Pass youe Uint8List and quality, you will get compressed image in no time.
Future<Uint8List> testComporessList(Uint8List uint8List) async {
var result = await FlutterImageCompress.compressWithList(
uint8List,
quality: 50,
);
return result;
}
2. But If you are in flutter web then you won't get any other option than image picker etc etc.
I end up using javascript. You can find answer here.
Flutter Web: How Do You Compress an Image/File?

Update 2020 'pickImage' is deprecated and shouldn't be used. Use imagePicker.getImage() method instead**
ImagePicker picker = ImagePicker();
PickedFile compressedImage = await imagePicker.getImage(
source: ImageSource.camera,
imageQuality: 80,
);
Doc for ImageQuality :
Returns a PickedFile object wrapping the image that was picked. The
returned PickedFile is intended to be used within a single APP
session. Do not save the file path and use it across sessions. The
source argument controls where the image comes from. This can be
either ImageSource.camera or ImageSource.gallery. Where iOS supports
HEIC images, Android 8 and below doesn't. Android 9 and above only
support HEIC images if used in addition to a size modification, of
which the usage is explained below. If specified, the image will be at
most maxWidth wide and maxHeight tall. Otherwise the image will be
returned at it's original width and height. The imageQuality argument
modifies the quality of the image, ranging from 0-100 where 100 is the
original/max quality. If imageQuality is null, the image with the
original quality will be returned. Compression is only supported for
certain image types such as JPEG and on Android PNG and WebP, too. If
compression is not supported for the image that is picked, a warning
message will be logged. Use preferredCameraDevice to specify the
camera to use when the source is ImageSource.camera. The
preferredCameraDevice is ignored when source is ImageSource.gallery.
It is also ignored if the chosen camera is not supported on the
device. Defaults to CameraDevice.rear. Note that Android has no
documented parameter for an intent to specify if the front or rear
camera should be opened, this function is not guaranteed to work on an
Android device. In Android, the MainActivity can be destroyed for
various reasons. If that happens, the result will be lost in this
call. You can then call getLostData when your app relaunches to
retrieve the lost data.

Related

flutter with firebase - detect the url string whether it is image(jpg) or video(avi)

I'm beginner with these Google's products and got 'serious' problem.
I uploaded photos and videos to firebase storage and urls of the photos and videos in the firebase storage is generated and stored automatically in firebase database. In my flutter lib, I could call those urls by my own code and display the url's image on the avd screen.
Image.network(url) is the code to display image url from firebase. But I also wanna display video url's asset simultaneously with single code. That is, videos and photos should be in single screen! In this case, Image.network(url) doesn't work anymore..
If I change that image.network code for video format according to video_player plug-in, I cannot display image asset anymore and if I stay same with that Image.network(url) code, I cannot display video url from firebase. So here is the question:
How can I detect whether the firebase's url string is image or video with my flutter code, and display that asset on the 'single screen' whatever the file format is(at least video and photo) with integrated flutter code?
url example
It's not much of a deal since type of the media is in the URL. You can parse it as a
Uri object then extract the type.
import 'dart:core';
enum UrlType { IMAGE, VIDEO, UNKNOWN }
void main() async {
var imageUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.jpg?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
var videoUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.mp4?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
print(getUrlType(imageUrl));
print(getUrlType(videoUrl));
}
UrlType getUrlType(String url) {
Uri uri = Uri.parse(url);
String typeString = uri.path.substring(uri.path.length - 3).toLowerCase();
if (typeString == "jpg") {
return UrlType.IMAGE;
}
if (typeString == "mp4") {
return UrlType.VIDEO;
} else {
return UrlType.UNKNOWN;
}
}
Let me give you an idea.
Consider implementing this scenario.
var url = 'domain.com/file.jpg?querySegment';
In your widget area,
child: url.contains('.mp4?') ? VideoWidget() : ImageWidget()
also, even with multiple conditions,
child: (url.contains('.jpg?') || url.contains('.png?')) ? ImageWidget() : VideoWidget()
May this suits your case.
Improving upon the accepted answer, here is what I have in my code. I needed a way to identify many types of videos and images from the passed url.
Using path package to idetify the extension
Have a list of video and image extension
import 'package:path/path.dart' as p;
enum UrlType { IMAGE, VIDEO, UNKNOWN }
class UrlTypeHelper {
static List<String> _image_types = [
'jpg',
'jpeg',
'jfif',
'pjpeg',
'pjp',
'png',
'svg',
'gif',
'apng',
'webp',
'avif'
];
static List<String> _video_types = [
"3g2",
"3gp",
"aaf",
"asf",
"avchd",
"avi",
"drc",
"flv",
"m2v",
"m3u8",
"m4p",
"m4v",
"mkv",
"mng",
"mov",
"mp2",
"mp4",
"mpe",
"mpeg",
"mpg",
"mpv",
"mxf",
"nsv",
"ogg",
"ogv",
"qt",
"rm",
"rmvb",
"roq",
"svi",
"vob",
"webm",
"wmv",
"yuv"
];
static UrlType getType(url) {
try {
Uri uri = Uri.parse(url);
String extension = p.extension(uri.path).toLowerCase();
if (extension.isEmpty) {
return UrlType.UNKNOWN;
}
extension = extension.split('.').last;
if (_image_types.contains(extension)) {
return UrlType.IMAGE;
} else if (_video_types.contains(extension)) {
return UrlType.VIDEO;
}
} catch (e) {
return UrlType.UNKNOWN;
}
return UrlType.UNKNOWN;
}
}
/// Usage
if(UrlTypeHelper.getType(message) == UrlType.IMAGE) {
/// handle image
}
else if(UrlTypeHelper.getType(message) == UrlType.VIDEO) {
/// handle video
}

TesseractApi Xamarin Infinite Freeze

I am using Tessaract's Xamarin Forms Nuget(https://github.com/halkar/Tesseract.Xamarin), and am trying to scan a picture taken by the Android Device. This is the code that I am using:
private async System.Threading.Tasks.Task<string> OCRAsync(byte[] bytes)
{
TesseractApi api;
api = new TesseractApi(this, AssetsDeployment.OncePerInitialization);
await api.Init("bul");
await api.SetImage(bytes);
var detectedText = api.Results(PageIteratorLevel.Block);
result = string.Empty;
if (detectedText != null)
{
foreach (var annotation in detectedText)
{
result = FindWordInDictionary(annotation.Text);
}
}
return result;
}
The method is called from a synchronized method like this:
var task = OCRAsync(data);
result = task.Result;
Whenever the compiler gets to "await api.Init("bul");" the app freezes indefinitely. Do you know what may cause this problem? Thank you.
The problem was that I needed to give a file location in the .init function:
await api.Init(pathToDataFile, "bul");

Xamarin.Forms Document Scanner

I scan the document with camera and write in to stream. Now is the hardest part, i need to write code for Cropping & Perspective Correction on the document taken. There is a nuget packages and libraries but they are expensive. I want to try to make my own code but don't know from where to start.
This is my code :
var file = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() {
Directory = "Sample",
Name = "test.jpg",
SaveToAlbum = false,
});
if (file == null)
return;
Stream stream = file.GetStream();
var localPath = string.Empty;
localPath = Task.Run(() => DependencyService.Get<Shared.ISharedFunction>().SaveFileToDisk(stream, "picture.jpg")).Result;
ImageDoc = ImageSource.FromStream(() => stream);
Picture.Name = localPath;
ImagesNew.Add(Picture);
This is my code i'm using media library to take photo(document) , and saving in stream. Now for the stream i need to convert in pdf(it may be more then one image). I need Cropping & Perspective Correction on the image.

Flutter: How to read file from assets, asynchronously, without blocking the UI

In flutter, rootBundle.load() gives me a ByteData object.
What exactly is a ByteData object in dart? Can It be used to read files asynchronously?
I don't really understand the motive behind this.
Why not just give me a good ol' File object, or better yet the full path of the asset?
In my case, I want to read bytes from an asset file asynchronously, byte by byte and write to a new file. (to build an XOR decryption thingy that doesn't hang up the UI)
This is the best I could do, and it miserably hangs up the UI.
loadEncryptedPdf(fileName, secretKey, cacheDir) async {
final lenSecretKey = secretKey.length;
final encryptedByteData = await rootBundle.load('assets/$fileName');
final outputFilePath = cacheDir + '/' + fileName;
final outputFile = File(outputFilePath);
if (!await outputFile.exists()) {
Stream decrypter() async* {
// read bits from encryptedByteData, and stream the xor inverted bits
for (var index = 0; index < encryptedByteData.lengthInBytes; index++)
yield encryptedByteData.getUint8(index) ^
secretKey.codeUnitAt(index % lenSecretKey);
print('done!');
}
print('decrypting $fileName using $secretKey ..');
await outputFile.openWrite(encoding: AsciiCodec()).addStream(decrypter());
print('finished');
}
return outputFilePath;
}
In Dart a ByteData is similar to a Java ByteBuffer. It wraps a byte array, providing getter and setter functions for 1, 2 and 4 byte integers (both endians).
Since you want to manipulate bytes it's easiest to just work on the underlying byte array (a Dart Uint8List). RootBundle.load() will have already read the whole asset into memory, so change it in memory and write it out.
Future<String> loadEncryptedPdf(
String fileName, String secretKey, String cacheDir) async {
final lenSecretKey = secretKey.length;
final encryptedByteData = await rootBundle.load('assets/$fileName');
String path = cacheDir + '/' + fileName;
final outputFile = File(path);
if (!await outputFile.exists()) {
print('decrypting $fileName using $secretKey ..');
Uint8List bytes = encryptedByteData.buffer.asUint8List();
for (int i = 0; i < bytes.length; i++) {
bytes[i] ^= secretKey.codeUnitAt(i % lenSecretKey);
}
await outputFile.writeAsBytes(bytes);
print('finished');
}
return path;
}
If you are doing work that is expensive and you don't want to block the UI, use the compute method from package:flutter/foundation.dart. This will run the provided function in a separate isolate and return the results to you asynchronously. loadEncryptedPdf must be a top level or static function to use it here though, and you are limited to passing one argument (but you can put them in a Map).
import 'package:flutter/foundation.dart';
Future<String> loadEncryptedPdf(Map<String, String> arguments) async {
// this runs on another isolate
...
}
final String result = await compute(loadEncryptedPdf, {'fileName': /*.../*});
So, while the answers posted by #Jonah Williams and #Richard Heap don't suffice on their own, I tried a combination of both, and it works good for me.
Here is a complete solution -
uses path_provider package to get the cache directory
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
// Holds a Future to a temporary cache directory
final cacheDirFuture =
(() async => (await (await getTemporaryDirectory()).createTemp()).path)();
_xorDecryptIsolate(args) {
Uint8List pdfBytes = args[0].buffer.asUint8List();
String secretKey = args[1];
File outputFile = args[2];
int lenSecretKey = secretKey.length;
for (int i = 0; i < pdfBytes.length; i++)
pdfBytes[i] ^= secretKey.codeUnitAt(i % lenSecretKey);
outputFile.writeAsBytesSync(pdfBytes, flush: true);
}
/// decrypt a file from assets using XOR,
/// and return the path to a cached-temporary decrypted file.
xorDecryptFromAssets(String assetFileName, String secretKey) async {
final pdfBytesData = await rootBundle.load('assets/$assetFileName');
final outputFilePath = (await pdfCacheDirFuture) + '/' + assetFileName;
final outputFile = File(outputFilePath);
if ((await outputFile.stat()).size > 0) {
print('decrypting $assetFileName using $secretKey ..');
await compute(_xorDecryptIsolate, [pdfBytesData, secretKey, outputFile]);
print('done!');
}
return outputFilePath;
}

Xamarin Forms - Image To/From IRandomAccessStreamReference

For personal needs, for the Xamarin.Forms.Map control, I need to create a CustomPin extension. UWP part (PCL project)
I create a MapIcon like it:
nativeMap.MapElements.Add(new MapIcon()
{
Title = pin.Name,
Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Pin/customicon.png")),
Location = new Geopoint(new BasicGeoposition() { Latitude = pin.Position.Latitude, Longitude = pin.Position.Longitude }),
NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0)
});
However, by this way, I can't set the Image's size.
I then want to use an Image from my PCL part, resize it and convert it into a IRandomAccessStreamReference. To realize it, I need to convert my Image into a stream, but I can't find the way to make it works ><
Example of the function needed:
private IRandomAccessStreamReference ImageToIRandomAccessStreamReference(Image image)
{
//Here I can set the size of my Image
//I convert it into a stream
IRandomAccessStreamReference irasr = RandomAccessStreamReference.CreateFromStream(/* img? */);
//irasr is then created from img
//I return the IRandomAccessStreamReference needed by the MapIcon element
return irasr;
}
Note: The Image paramter img is a Xamarin.Forms.Image
So first, is it possible? If yes, then thank for any help which could help me.. I already search about how to resize the MapIcon and it's not possible directly from the class [MapIcon].(https://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.controls.maps.mapicon.aspx)
Thank for help !
You are right. We can't resize the MapIcon directly as it doesn't provide such properties or methods. MapIcon's size is mostly controlled by the size of image which is set by MapIcon.Image property. And we can set this image's size without using Xamarin.Forms.Image.
To set this image's size, we can take advantage of BitmapDecoder class, BitmapEncoder class and BitmapTransform class like following:
private async System.Threading.Tasks.Task<RandomAccessStreamReference> ResizeImage(StorageFile imageFile, uint scaledWidth, uint scaledHeight)
{
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
var decoder = await BitmapDecoder.CreateAsync(fileStream);
//create a RandomAccessStream as output stream
var memStream = new InMemoryRandomAccessStream();
//creates a new BitmapEncoder and initializes it using data from an existing BitmapDecoder
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);
//resize the image
encoder.BitmapTransform.ScaledWidth = scaledWidth;
encoder.BitmapTransform.ScaledHeight = scaledHeight;
//commits and flushes all of the image data
await encoder.FlushAsync();
//return the output stream as RandomAccessStreamReference
return RandomAccessStreamReference.CreateFromStream(memStream);
}
}
And then we can use this method to create a resized image stream reference first and then set it as MapIcon's Image like:
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Pin/customicon.png"));
var imageReference = await ResizeImage(file, 64, 64);
nativeMap.MapElements.Add(new MapIcon()
{
Title = pin.Name,
Image = imageReference,
Location = new Geopoint(new BasicGeoposition() { Latitude = pin.Position.Latitude, Longitude = pin.Position.Longitude }),
NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0)
});

Resources