how to rename a pickedfile from image_picker in flutter?
I want to rename the image name which is a pickedfile type when i'm uploading that image to the server. when it's uploading image name automatically changes like this scaled_image_picker825656736600296027.jpg
getting image code :-
void takePhoto(ImageSource source) async {
final pickedFile = await _picker.getImage(
source: source,
imageQuality: 20,
);
setState(() {
_imageFile = pickedFile;
});
}
uploading code is :-
void UploadImage() async {
var request = http.MultipartRequest('POST', Uri.parse(URLs.image));
request.fields['CompanyCode']= "${widget.CompanyCode}";
request.fields['empCode'] ='$user_id';
request.fields['documentType']="POD";
if (_imageFile != null && widget.image == null) {
print('Original path: ${_imageFile.path}');
String dir = path.dirname(_imageFile.path);
String newPath = path.join(dir, widget.docketno + '-${DateTime.now()}.jpg');
print('NewPath: ${newPath}');
_imageFile.renameSync(newPath); // renameSync is showing error
request.files
.add(await http.MultipartFile.fromPath('file',_imageFile.path));
}
else if(_imageFile ==null && widget.image != null){
print('AddingUserProfilePic ${widget.image.path}');
request.files.add(await http.MultipartFile.fromPath('file', widget.image.path));
}
var response = await request.send();
var responseBody = await http.Response.fromStream(response);
myData = json.decode(responseBody.body);
print('Status code is : ${response.statusCode} && ${response}');
if (response.statusCode == 200) {
responseResult = myData['filePath'];
print('the filepath is ' + responseResult.substring(60));
image_path = responseResult.substring(60);
Fluttertoast.showToast(msg: 'Uploaded Successfully');
Navigator.push(context, MaterialPageRoute(builder: (context) => delivered(CompanyCode : widget.CompanyCode,docketno :widget.docketno,Year: widget.Year,
drsno:widget.drsno,challan: widget.challan , package :widget.package , response : image_path)));
// Navigator.popUntil(context, (route) {
// return count++ == 2;
// });
} else {
Fluttertoast.showToast(msg: 'Upload Failed');
}
}
renameSync is showing the error that The method 'renameSync' isn't defined for the type 'PickedFile'. so how can i rename my image file????
1 answer
-
answered 2020-11-25 07:26
zhpoo
PickedFile
is notFile
, it's just a result object of picked file.You can use it's path to create a
File
and useFile
'srenameSync
:File(_imageFile.path).renameSync(newPath);
See also questions close to this topic
-
Image not showing properly when reading the image using PIL instead of imagio library
I have this code that converts an image from RGB space to HSI space:
import numpy as np import imageio from matplotlib import pyplot as plt def RGB_TO_HSI(img): with np.errstate(divide='ignore', invalid='ignore'): rgb = np.float32(img) / 255 # Separate color channels red = rgb[:, :, 0] green = rgb[:, :, 1] blue = rgb[:, :, 2] # Calculate Intensity def calc_intensity(red, green, blue): intensity = (red + green + blue + 0.001) / 3 return intensity # Calculate Saturation def calc_saturation(red, green, blue): minimum = np.minimum(np.minimum(red, green), blue) saturation = 1 - (minimum / calc_intensity(red, green, blue)) return saturation # Calculate Hue def calc_hue(red, green, blue): hue = np.copy(red) # Basically have our hue = red for now; we only need its size/dimensions for i in range(0, blue.shape[0]): for j in range(0, blue.shape[1]): if blue[i][j] <= green[i][j]: hue[i][j] = np.arccos(0.5 * ((red[i][j] - green[i][j]) + (red[i][j] - blue[i][j])) / (np.sqrt((red[i][j] - green[i][j]) ** 2 + (red[i][j] - blue[i][j]) * (green[i][j] - blue[i][j])))) else: hue[i][j] = 2 * np.pi - np.arccos(0.5 * ((red[i][j] - green[i][j]) + (red[i][j] - blue[i][j])) / (np.sqrt((red[i][j] - green[i][j]) ** 2 + (red[i][j] - blue[i][j]) * (green[i][j] - blue[i][j])))) return hue # Merge channels into picture and return image hsi = np.zeros(img.shape) # instead of having 3 channels, one for each color (RGB), here we have a channel; for "hue", another for "saturation" and another for "intensity" hsi[:, :, 0], hsi[:, :, 1], hsi[:, :, 2] = calc_hue(red, green, blue), calc_saturation(red, green, blue), calc_intensity(red, green, blue) return hsi cat = imageio.imread("Path...") hsi_cat = RGB_TO_HSI(cat) plt.imshow(hsi_cat) plt.show()
However, adjusting the line in the code to:
hsi = np.zeros(rgb.shape, dtype=np.uint8)
, then loading the image using PIL, and passing it into the function as an argument:cat_p = Image.open("Path...") # Using PIL now his_cat_p = RGB_TO_HSI(cat_p) # Passing the JPEG image into the function his_cat_p = Image.fromarray(his_cat_p) # Converting the result back from an array (return hsi), into JPEG format his_cat_p.show() # Black image appears
This results is a black image, and I'm not quite sure why!
-
Is there a C function/code to convert a char array into BMP file?
I prefer a ready-code to save my time re-writing the format and to avoid errors and didn't seem to find.
-
How to decide on the right target size of an input image for inception_v3? (predictions differ)
I am running an Inception V3 model to make predictions. I am finding out that different target sizes for the input image lead to different predictions.
For the same image, I got different predictions. For (416, 416): tiger_cat (6.228156387805939), for (299, 299): Egyptian_cat (55.72159290313721), for (224, 224): lynx (48.244667053222656).
I thought that the input size should be divided by 32. Which is not the case for (299, 299). But, for another input size I get the error message:
WARNING:tensorflow:Model was constructed with shape (None, 299, 299, 3) for input Tensor("input_13:0", shape=(None, 299, 299, 3), dtype=float32), but it was called on an input with incompatible shape (None, 224, 224, 3).
How do I decide on the best target size?
-
Change color of alternate rows of a data table in flutter
Here is my code
class Reference extends StatefulWidget { @override _ReferenceState createState() => _ReferenceState(); } class _ReferenceState extends State<Reference> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: ListView( children: [ SingleChildScrollView( scrollDirection: Axis.horizontal, child: DataTable( dataRowHeight: 30, dividerThickness: 1.0, columnSpacing: 30, columns: [ DataColumn( label: Text('ID', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold))), DataColumn( label: Text('Parameter', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold))), rows: [ DataRow(cells: [ DataCell(Text('1')), DataCell(Text('a')), ]), DataRow(cells: [ DataCell(Text('2')), DataCell(Text('b')), ]), DataRow(cells: [ DataCell(Text('15')), DataCell(Text('c')), ]), ], ), ), Divider( height: 5, thickness: 5, ), ], )); } }
My table is 50 rows long. I am not using a constructor as The data is predetermined and different in each row. How do I color my alternate rows? Do I have to set the color of each DataRow individually or is there a way to do it automatically? I searched and the solutions that I got all work with constructors for creating rows.
For example I found this on flutter api
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); /// This is the main application widget. class MyApp extends StatelessWidget { static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: Scaffold( appBar: AppBar(title: const Text(_title)), body: MyStatefulWidget(), ), ); } } /// This is the stateful widget that the main application instantiates. class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); } /// This is the private State class that goes with MyStatefulWidget. class _MyStatefulWidgetState extends State<MyStatefulWidget> { static const int numItems = 10; List<bool> selected = List<bool>.generate(numItems, (index) => false); @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, child: DataTable( columns: const <DataColumn>[ DataColumn( label: Text('Number'), ), ], rows: List<DataRow>.generate( numItems, (index) => DataRow( color: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { // All rows will have the same selected color. if (states.contains(MaterialState.selected)) return Theme.of(context).colorScheme.primary.withOpacity(0.08); // Even rows will have a grey color. if (index % 2 == 0) return Colors.grey.withOpacity(0.3); return null; // Use default value for other states and odd rows. }), cells: [DataCell(Text('Row $index'))], selected: selected[index], onSelectChanged: (bool value) { setState(() { selected[index] = value; }); }, ), ), ), ); } }
which works with constructor
-
open or navigate on new Bloc form on pressed event
I have 2 Bloc Registration and Login, Registration click button on the login page. I want to redirect on Registration page from login's Registration Button click, here is the snippate. getting an error like this
child: new RaisedButton( color: Colors.red[800], textColor: Colors.white, child: new Text( 'REGISTER', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w400), ), onPressed: () => BlocListener( //bloc: RegistrationPageBloc, listener: (BuildContext context, RegistrationFormState state) { Navigator.of(context).push( MaterialPageRoute(builder: (BuildContext context) { return RegistrationForm(); })); }), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), ),
-
Flutter: How to show appbar above drawer?
I am building a flutter app and I don't find how to show appbar above drawer. I saw many people asking this but anybody solved it.
-
yfinance returns a strange index
I am using yfinance to fetch stock data and the dataframe returned has a strange index as shown below. How can I get rid of the leading numbers in the Datetime column? For example, in the first row, the Datetime column is 378 2021-01-25 15:10:00-05:00. I would like to get rid of 378 to get only 2021-01-25 15:10:00-05:00 Index from yfinance dataframe
!pip install yfinance import yfinance as yf df = yf.download('INTC',period='5d', interval='5m') df.tail(10)
Interestingly, my df.loc[1,'Datetime'] returns 2021-01-19 09:30:00-05:00. The leading number (378) is missing.
Thank you in advance for your help.
- How to rename duplicate .jpg file name in Mac
-
Linux: Move a batch of files and rename?
I'm currently trying to move and rename a batch of files. The following
for
loop moves the .jpeg files into each subject's folder (subjects.txt
is just a text file containing a column of IDs):for i in `awk '{print $1}' data/subjects.txt`; do find data/ -name ${i}\*_img.jpeg | xargs -I file cp file data/${i}/ ; done
However, renaming each file to "img.jpeg" hasn't worked so far:
for i in `awk '{print $1}' data/subjects.txt`; do find data/ -name ${i}\*_img.jpeg | xargs -I file cp file data/${i}/img.jpeg ; done
Please let me know if you have any suggestions!
I would like to achieve the following:
data/subject_1/img.jpeg data/subject_2/img.jpeg data/subject_3/img.jpeg
-
Stuck after Cropping Image in Gallery Kotlin Crop Image from Gallery
unfortunately I'm stuck again for a few hours. I want to crop an image from the gallery to a certain aspect ratio and paste it into an ImageView. I also want to keep the path of the image in a string. The problem is that the ImageCropper of my gallery hangs as soon as I crop the image. I get stuck on this screen forever. So the cropped image is not passed back to my app.
Here some important parts of the code:
private fun pickImageFromGallery() { val intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" intent.putExtra("crop", "true"); intent.putExtra("aspectX", 3); intent.putExtra("aspectY", 2); intent.putExtra("outputX", 640); intent.putExtra("outputY", 426); intent.putExtra("noFaceDetection", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()) intent.putExtra("return-data", true); startActivityForResult(intent, IMAGE_PICK_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE) { dev_img.setImageURI(data?.data) } else { Toast.makeText( applicationContext, "Vorgang abgebrochen.", Toast.LENGTH_SHORT ).show() } }
Without the intent.putExtra commands the image is taken directly from the gallery into the app. Unfortunately then not cropped. I don't want to use external libraries with my app, so I have hardly found any solutions on the internet. I hope someone recognizes my problem and can help me to correct it. Thank you.
-
Image picker library does not work for flutter app
I am trying to add an image picker package for my flutter app, but it does not work, it also shows that build gradle failed to build. I have read that it is related to native apps operating system and it must have the latest version and latest versions of grade libraries in order to work, I have solved the problem using the shortest solutions, I have downgrade the image picker version to ^0.5.4+1 the simulator started but the image cannot be picked from camera, the preview image is not shown.
image picker: ^0.5.4+1 dependencies { classpath 'com.android.tools.build:gradle:3.6.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip W/Binder ( 7322): Caught a RuntimeException from the binder stub implementation. W/Binder ( 7322): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: Binder:7322_2 W/Binder ( 7322): at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:781) W/Binder ( 7322): at io.flutter.embedding.engine.FlutterJNI.invokePlatformMessageResponseCallback(FlutterJNI.java:718) W/Binder ( 7322): at io.flutter.embedding.engine.dart.DartMessenger$Reply.reply(DartMessenger.java:144) W/Binder ( 7322): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler$1.success(MethodChannel.java:231) W/Binder ( 7322): at io.flutter.plugins.imagepicker.ImagePickerDelegate.finishWithSuccess(ImagePickerDelegate.java:540) W/Binder ( 7322): at io.flutter.plugins.imagepicker.ImagePickerDelegate.handleImageResult(ImagePickerDelegate.java:505) W/Binder ( 7322): at io.flutter.plugins.imagepicker.ImagePickerDelegate.access$000(ImagePickerDelegate.java:66) W/Binder ( 7322): at io.flutter.plugins.imagepicker.ImagePickerDelegate$4.onPathReady(ImagePickerDelegate.java:470) W/Binder ( 7322): at io.flutter.plugins.imagepicker.ImagePickerDelegate$3$1.onScanCompleted(ImagePickerDelegate.java:160) W/Binder ( 7322): at android.media.MediaScannerConnection$ClientProxy.onScanCompleted(MediaScannerConnection.java:204) W/Binder ( 7322): at android.media.MediaScannerConnection$1.scanCompleted(MediaScannerConnection.java:53) W/Binder ( 7322): at android.media.IMediaScannerListener$Stub.onTransact(IMediaScannerListener.java:61) W/Binder ( 7322): at android.os.Binder.execTransact(Binder.java:731)
the code I have written is:
import 'dart:io'; import 'package:flutter/material.dart'; // import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path/path.dart' as path; // import 'package:path_provider/path_provider.dart' as syspaths; class ImageInput extends StatefulWidget { @override _ImageInputState createState() => _ImageInputState(); } class _ImageInputState extends State<ImageInput> { File _storedImage; Future<void> _takePicture() async { final imageFile = await ImagePicker.pickImage( source: ImageSource.camera, maxWidth: 600, ); setState(() { _storedImage = imageFile; }); // final appDir = await syspaths.getApplicationDocumentsDirectory(); // final fileName = path.basename(imageFile.path); // final savedImage = await imageFile.copy('${appDir.path}/$fileName'); print("_storedImage${_storedImage.path}"); } @override Widget build(BuildContext context) { return Row( children: <Widget>[ Expanded( child: Container( width: 150, height: 100, decoration: BoxDecoration( border: Border.all(width: 1, color: Colors.grey), ), child: _storedImage != null ? Image.file( _storedImage, fit: BoxFit.cover, width: double.infinity, ) : Text( 'No Image Taken', textAlign: TextAlign.center, ), alignment: Alignment.center, ), ), // SizedBox( // width: 10, // ), Expanded( child: FlatButton.icon( icon: Icon(Icons.camera), label: Text('Upload'), textColor: Theme.of(context).primaryColor, onPressed: _takePicture, ), ), ], ); } }
I tried to update the image picker package to ^0.6.0+10 another error has appeared:
C:\Users\ASUS\Desktop\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-1.0.11\android\src\main\java\io\flutter\embedding\engine\plugins\lifecycle\FlutterLifecycleAdapter.java:8: error: package androidx.lifecycle does not exist import androidx.lifecycle.Lifecycle; ^ C:\Users\ASUS\Desktop\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_plugin_android_lifecycle-1.0.11\android\src\main\java\io\flutter\embedding\engine\plugins\lifecycle\FlutterLifecycleAdapter.java:22: error: cannot find symbol public static Lifecycle getActivityLifecycle( ^ symbol: class Lifecycle location: class FlutterLifecycleAdapter 2 errors FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':compileReleaseJavaWithJavac'. > Compilation failed; see the compiler error output for details.
-
How to compress a photo picked from gallery in kotlin
I found so many questions on the topic but none had a full working example.
My case is simple:
- get picked image
- compress image
- upload compressed image to Firebase Storage
My current code (without compression):
Fragment:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { RC_PICK_IMAGE -> if (resultCode == Activity.RESULT_OK) data?.data?.let { viewModel.updateUserPicture(it) } } }
ViewModel:
fun updatePhotoUrl(photoUrl: Uri?): Task<Void> = Storage.uploadFile("/$PS_USERS/$uid", photoUrl) .continueWithTask { ... }
Storage: (object to wrap Firebase interactions)
fun uploadFile(path: String, uri: Uri): Task<Uri> { val imageRef = storageRef.child(path) val uploadTask = imageRef.putFile(uri) // Return the task getting the download URL return uploadTask.continueWithTask { task -> if (!task.isSuccessful) { task.exception?.let { throw it } } imageRef.downloadUrl } }
This works perfectly.
Now my question is: what is the right way to add compression in this process?
- I found many answers pointing to the Compressor library (like here & here) and tried it, but it doesn't work with gallery result uris. I found ways to get the actual uri from that (like here), but they feel like a lot of boilerplate code, so it doesn't feel like the best practice.
- I also found many answers using
bitmap.compress
(like here & here) and tried it too, but it asks for a bitmap. Getting the bitmap is easy withMediaStore.Images.Media.getBitmap
, but it is deprecated, and this solution made me doubt if it's the right direction. Also, holding the bitmap in my LiveData object (to show on screen until the actual save, in the edit screen), instead of a uri, feels weird (I use Glide for presenting the images).
On top of that, both solutions demand a context. I think compression is a process that should belong in the backend (or Repository class. The Storage object in my case), So they feel a bit off.
Can someone please share a full working example of this trivial use case?