Flutter: Custom name for screenshot image - flutter

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.

Related

How to create a Button that allow user to download a specific file Flutter

I create a flutter app and I have this one CSV file that used as a template for user. I want to provide a Button that allow user to download this CSV file, so they can use it to have CSV file that already have our template.
The problem is I don't know if the best way is to first store the file online and get the url and use it on the flutter downloader URL or keep it in the local code asset and refer to that file when user tap the download template button. Currently I'm applying the second option and it doesn't work (I don't know if this option is possible or not), the download always fail. I'm using flutter_downloader package.
How to fix this ?
Here's my code, Is something wrong with my code ?
/// Check if the file exist or not
if (await File(externalDir!.path + "/" + fileName).exists()) {
OpenFilex.open(externalDir!.path + "/" + fileName);
} else {
/// Download the file if it doesn't exist in the user's device
final String localPath = (await getApplicationDocumentsDirectory()).path;
/// Dummy file name I want use (it exist in my asset dir"
const String fileName = 'add.png';
final data = await rootBundle.load('assets/logo/add.png');
final bytes = data.buffer.asUint8List();
final File file = File('$localPath/$fileName');
await file.writeAsBytes(bytes);
/// Download the file
final taskId = await FlutterDownloader.enqueue(
url: '',
savedDir: localPath,
fileName: fileName,
showNotification: true,
openFileFromNotification: true,
);
}
To load a file from the AppBundle and then save it to the users phone, do the following:
Put the file in assets/filename.csv and declare it in your pubspec like this:
flutter:
assets:
- assets/filename.csv
Load the file in your code:
import 'package:flutter/services.dart' show ByteData, rootBundle;
(...)
var data = (await rootBundle.load('assets/filename.csv)).buffer.asInt8List();
Save the data to a file (you need the path-provider package if you want to copy the exact code):
import 'package:path_provider/path_provider.dart' as pp;
(...)
var path = (await pp.getApplicationDocumentsDirectory()).path;
var file = File('$path/filename.csv');
await file.writeAsBytes(data, flush: true);
Edit: As Stephan correctly pointed out, if you want to store the file in the downloads folder, you will find additional information about that here. Thank you Stephan!

after using file.copy(path) and getting the new file i get the previos file at that location

I'm trying to update a locally saved image file (user's profile picture).
This is how I do it:
Future<void> setProfilePic(File newProfilePic) async {
String profilePicPath = (await getApplicationDocumentsDirectory()).path +
Platform.pathSeparator +
"profilePic.jpg";
await newProfilePic.copy(profilePicPath); }
Then I try to get the profile picture like so:
Future<File> getCurrentUserProfilePic() async {
String filePath =
(await getApplicationDocumentsDirectory()).path + "/profilePic.jpg";
File profilePicFile = File(filePath);
return profilePicFile; }
The profile picture I get is the previous picture located in that file.
Only after I reopen the app, the widget shows the new profile picture.
I do use await when calling the get function and I do setState().
Does anyone know what the problem is?

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);
}

flutter image picker reduce file size with provider and flutter_image_compress

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.

Flutter how to Convert filePath from content://media/external/images/media/5275 to /storage/emulated/0/DCIM/Camera/IMG_00124.jpg

I have URI LIKE below
content://media/external/images/media/5275
but I want convert it to Like format below:
/storage/emulated/0/DCIM/Camera/IMG_00124.jpg
Anyone who can help me!
Sreng Bona
Thanks!
var path = await FlutterAbsolutePath.getAbsolutePath("content://media/external/images/media/5275");
Add this flutter_absolute_path: ^1.0.6 to your file: pubspec.yaml
It will be working as Well.
Bona SR.
I had to search a lot, but I found a very useful solution to save the image in the cell phone's photo gallery and get the absolute path to use it the way you want.
For this example I used a result obtained from saving an image in the photo gallery, however it could also work to read other files, obviously making the changes that you see necessary, I hope it will help you
uri_to_file
image_gallery_saver
import 'dart:io';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:uri_to_file/uri_to_file.dart';
Future<File> saveImage(File image, String identifier) async {
try {
var result = await
ImageGallerySaver.saveImage(image.readAsBytesSync(),
quality: 60, name: identifier +
"-${DateTime.now().toIso8601String()}");
print(result);
File file = await toFile(Uri.parse(result['filePath']));
print(file);
return file;
} catch (e) {
print(e);
return new File('assets/img/default-img.jpg');
}
}
// example
saveImage(File("path/image.jpg"),"img-test");