Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a file/Image in flutter

I am picking a image from gallery/taking a photo using image_picker: ^0.6.2+3 package.

File picture = await ImagePicker.pickImage(
  maxWidth: 800,
  imageQuality: 10,
  source: source, // source can be either ImageSource.camera or ImageSource.gallery
  maxHeight: 800,
);

and I get picture.path as

/Users/[some path]/tmp/image_picker_A0EBD0C1-EF3B-417F-9F8A-5DFBA889118C-18492-00001AD95CF914D3.jpg

Now I want to rename the image to case01wd03id01.jpg

Note : I don't want to move it to new folder

How can I rename it? I could not find it in official docs.

like image 925
L Uttama Avatar asked Jan 24 '20 12:01

L Uttama


3 Answers

Use this function to rename filename only without change path of the file. you can use this function with or without image_picker.

import 'dart:io';

Future<File> changeFileNameOnly(File file, String newFileName) {
  var path = file.path;
  var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
  var newPath = path.substring(0, lastSeparator + 1) + newFileName;
  return file.rename(newPath);
}

read more documentation in file.dart on your dart sdk. hope can help, regard

like image 144
Denis Ramdan Avatar answered Sep 27 '22 00:09

Denis Ramdan


Import path package

import 'package:path/path.dart' as path;

Code below

 final file =File("filepath here"); //your file path
 String dir = path.dirname(file.path); //get directory
 String newPath =path.join(dir, 'new file name'); //rename
 print(newPath); //here the newpath
 file.renameSync(newPath);
like image 36
Rahul Raj Avatar answered Sep 23 '22 00:09

Rahul Raj


First import the path package.

import 'package:path/path.dart' as path;

Then create a new target path to rename the file.

File picture = await ImagePicker.pickImage(
        maxWidth: 800,
        imageQuality: 10,
        source: ImageSource.camera,
        maxHeight: 800,
);
print('Original path: ${picture.path}');
String dir = path.dirname(picture.path);
String newPath = path.join(dir, 'case01wd03id01.jpg');
print('NewPath: ${newPath}');
picture.renameSync(newPath);
like image 42
Manish Avatar answered Sep 26 '22 00:09

Manish