flutter image picker reduce file size with provider and flutter_image_compress - flutter

I am using image picker to pick image from device(App) and after that stored that file in provider class like that.
File? _img;
get img=> _img;
void putbannerimg(File img) {
_img = img;
notifyListeners();
}
I found out that image picker does not compress png images, I tried compressing it with flutter_image_compress
compressFile() async {
final formservice = Provider.of<PostForm>(context, listen: false);
File file = formservice.bannerfile;
final result = await FlutterImageCompress.compressWithFile(
file.absolute.path,
quality: 54,
);
formservice.putbannerimg(File.fromRawPath(result!));
}
I tried this way And other multiple ways but getting different different errors I want to upload this file in firebase storage like this
var task = storageicon.putFile(formservice.iconfile);
please tell me where I am going wrong, without compress file all things are working fine
Edit: I found out that path should be a string how can I parse local code file in that

If you are using the "flutter_image_compress" package
You may have to use the compress function for files stored on the phone like this:
Future<File> testCompressAndGetFile(File file, String targetPath) async {
var result = await FlutterImageCompress.compressAndGetFile(
file.absolute.path, targetPath,
quality: 88,
rotate: 180,
);
print(file.lengthSync());
print(result.lengthSync());
return result;
}
"compressAndGetFile()" returns a file while "compressWithFile()" returns a Uint8List.
If i understand your last question right, you want to use an image built into your application by default.
For this, you have to open your "pubsepc.yaml", go to the "flutter:" mark and add "assets:" like so:
flutter:
assets:
- path
"path", in my example, describes a top level folder containing assets like pictures.
You can freely describe its name.

Related

In file picker in flutter, path was not unique

I'm trying with two different images with same name. But the path was same for two picked images. it was not unique.So that I uploaded in server second image with the same name of first uploaded image. But server had both the image are same and it had first image. So how to handle this case and customize the path?
You can use the path_provider to define the customize directory on your app.
So, copy the file with your customize path and rename the file name.
BTW, do NOT save the absolute path of File on iOS.
The iOS use SandBox to access the file. When you get the file path every time. The file path will be different.
class FileUtils {
final String avatarPath = '/avatar/';
Future<String> getAvatarDirectoryPath() async {
final String appDirPath = await getApplicationSupportDirectory().path;
final Directory avatarDirPath = await Directory(appDirPath + avatarPath).create();
return directory.path;
}
}
// Example
{
final XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
final File imageFile = File(image.path);
final File newFile = File(await FileUtils().getAvatarDirectoryPath() + 'userAvatar.png');
await imageFile.copy(newFile.path);
}

Store image uploaded by user into Flutter Web as an actual .jpg file

I am using the flutter_web_image_picker package to allow the user to select -and then upload to Firebase- an image.
However, the package returns an image widget, which I can display, but I cannot upload to Firebase. Therefore, I am trying to read the package's code and update it to fit my needs.
In general, I think the packages main functionalities are:
It gets the file
//...
final reader = html.FileReader();
reader.readAsDataUrl(input.files[0]);
await reader.onLoad.first;
final encoded = reader.result as String;
Then it 'strippes' it
final stripped = encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '');
final imageName = input.files?.first?.name;
//...
To finally return it as a Widget:
final imageName = imageName;
final imageData = base64.decode(stripped);
return Image.memory(imageData, semanticLabel: imageName);
As I said, it works perfectly, however, I need to adapt it to my needs:
I would like to get the image as a .jpg file so that I can upload it to Firebase.
Is any of the variables above the actual .jpg file? Is there any transformation that I should perform to get a .jpg file?
Thanks!
I based my answer on this post.
Basically, on the flutter_web_image_picker package, before the code I posted, there were a few lines that get an actual html file:
final html.FileUploadInputElement input = html.FileUploadInputElement();
input..accept = 'image/*';
input.click();
await input.onChange.first;
if (input.files.isEmpty) return null;
Then using firebase's pacakge, I uploaded the image as follow:
import 'package:firebase/firebase.dart' as fb;
fb.StorageReference storageRef = fb.storage().ref('myLocation/filename.jpg');
fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(input.files[0]).future;
Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
return imageUri;

Saving images and videos for offline access

I am developing an app that fetches a custom object from my REST API. The object's class is called MyItem and it looks like this:
class MyItem {
String title;
String profilePicURL;
String videoURL;
}
As you can see, the class contains two URLs, that points to a png and mp4 files.
I would like to implement a feature, which allows the user to download the object, in order to access its content offline. I have no problem saving the title property, but how can I save the two URLs (because I don't want the URL itself to be saved, I would like to save the file it points to).
Any idea what is the best way doing that in Flutter and Dart?
Thank you!
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
var directory = await getApplicationDocumentsDirectory();
Dio dio = Dio();
//Below function will download the file you want from url and save it locally
void Download(String title, String downloadurl) async{
try{
await dio.download(downloadurl,"${directory.path}/$title.extensionoffile",
onReceiveProgress: (rec,total){
print("Rec: $rec, Total:$total");
setState(() {
//just to save completion in percentage
String progressString = ((rec/total)*100).toStringAsFixed(0)+"%";
}
);
});
}
catch(e){
//Catch your error here
}
}
Now again wherever you want just use
var directory = await getApplicationDocumentsDirectory();
String filepath = "{directory.path}/filename.fileextension";
Now you can use this Image.file('filepath'); //to display those image
also you can use
video player plugin
where again VideoPlayerController.file('filepath') //to show video but read documention properly
These are just a whole steps or a broader view, you need to use them as a map and build your code.That is have a proper file name and extension saved or correctly fetched or mapped

Flutter: Custom name for screenshot image

I am following the following flutter package to take a screenshot of my one app page:
https://pub.dev/packages/screenshot
I have successfully implemented the example and I can see my screenshots in the gallery.
My issue is that I would like to be able to NAME those images when they are stored in the gallery using some sort of numbering system. e.g. INV_0001, INV_0002.
Is there a way to do this in code? I have the following code that successfully takes the screenshot, but does not rename the file.
CODE
_imageGallerySaver() async {
final directory = (await getApplicationDocumentsDirectory()).path; //from path_provide package
String fileName = "Bob";
String pathName = '$directory/$fileName.png';
//print(path);
screenshotController
.capture(
path: pathName,
).then((File image) async {
print("image: $image");
setState(() {
_imageFile = image;
});
print(pathName);
final result =
await ImageGallerySaver.saveImage(image.readAsBytesSync());
print("File Saved to Gallery. result: $result");
//print("path: $path");
}).catchError((onError) {
print(onError);
});
}
SNIPPET
print("File Saved to Gallery. result: $result");
results in the following output:
File Saved to Gallery. result: file:///storage/emulated/0/app_name/1581602261670.png
I would like to rename the "1581602261670" part, if possible. Thank you
In your code, you are passing that file name to construct the path, then why not change the name there itself.
Anyway, you can rename an existing file using
await file.rename (newPath
):
Can't rename files using this method. Need to use a package called Gallery Saver:
https://pub.dev/packages/gallery_saver
This package allows you to set your own file name and save to the gallery.

Getting FirebaseVisionImage from manipulated image in Flutter

I'm trying to do some pre-processing in my image before using Firebase MLkit. Previously, I was simply loading my image and then passing it directly like this.
File file = await FilePicker.getFile(type: FileType.IMAGE);
final FirebaseVisionImage visionImage = FirebaseVisionImage.fromFile(file);
VisionText visionText = await textRecognizer.processImage(visionImage);
But now, I wanted to do some processing on the image. I did this using Flutter's Image package like this.
import 'package:image/image.dart' as Img;
File file = await FilePicker.getFile(type: FileType.IMAGE);
Img.Image image = Img.decodeImage(file.readAsBytesSync());
var img = Img.invert(image);
Now, how do I pass this new object to FirebaseVisionImage. I see that there is this function:
FirebaseVisionImage.fromBytes(bytes, metadata)
I'm guessing I can get bytes from the above image object using img.getBytes() but I'm confused how to set the metadata.
EDIT:
I see that one can write the image to a temporary file doing
img.writeAsBytesSync(decoded.ToList());
and then use that image again using FirebaseVisionImage.fromFile() but I would really prefer not to do that.