This question already has answers here:
error: Instance member 'cropImage' can't be accessed using static access
(2 answers)
Closed 12 months ago.
**i spent all night trying get cropped image, need some help **
image_cropper: ^1.5.0 # Used to Crop/Rotate Selected images from user's device
///Error
Error: Member not found: 'ImageCropper.cropImage'.
final croppedImage = await ImageCropper.cropImage(
///images_source
class ImageSourceSheet extends StatelessWidget {
// Constructor
ImageSourceSheet({required this.onImageSelected});
// Callback function to return image file
final Function(File?) onImageSelected;
// ImagePicker instance
final picker = ImagePicker();
Future<void> selectedImage(BuildContext context, File? image) async {
// init i18n
final i18n = AppLocalizations.of(context);
// Check file
if (image != null) {
final croppedImage = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatioPresets: [CropAspectRatioPreset.square],
maxWidth: 400,
maxHeight: 400,
androidUiSettings: AndroidUiSettings(
toolbarTitle: i18n.translate("edit_crop_image"),
toolbarColor: Theme.of(context).primaryColor,
toolbarWidgetColor: Colors.white,
));
onImageSelected(croppedImage);
}
}
You need to use ImageCropper().cropImage(...).
final croppedImage = await ImageCropper().cropImage(....)
You can check example code.
Related
I want to have a feature in my Flutter App like Snapcodes on Snapchat. Basically custom “QR” Codes (they aren’t scannable to anything besides Snapchat so not really QR codes) with the app icon in them that launch a users profile when scanned in the app. I can make a simple version of this with plain QR codes using a pub package and Firebase Deeplinking but that isn’t what I want. What I think needs to be done is to create my own “qr” code generator that makes code holding a uid and then a way to decode them when scanned but I have no idea how to do that. Any ideas or pub packages that can do this?
Added for comment:
So I was looking through my old project and I got this ( The Idea of the source code below is that your taking a screenshot programmatically):
import 'dart:ui' as ui; //
final _renderObjectKey = new GlobalKey();
int randomDigit;
Timer _timer;
String userID;
void startTimer() {
//Generate random numbers attached to userID to make qrcode change periodically: improve on this!!!
var range = new Random();
_timer = new Timer.periodic(Duration(seconds: 10), (timer) {
setState(() {
randomDigit = range.nextInt(800) + 100;
});
});
}
#override
void initState() {
super.initState();
userID = auth.currentUser.uid; //if you are using firebaseauth
startTimer();
}
#override
void dispose() {
_timer.cancel();
super.dispose();
}
......
// The widget below is placed inside the body of scaffold
RepaintBoundary(
key: _renderObjectKey,
child:Stack(
alignment: Alignment.center,
children:[
BarcodeWidget(
color: Color(0xFFF9F9F9),
barcode: Barcode.qrCode(
errorCorrectLevel:BarcodeQRCorrectionLevel.high,),
data: '$userID$randomDigit', // this could be uuid
width: height * 0.32, // you can adjust to your liking
height: height * 0.32,
) // BarcodeWidget,
Container( height: 50,width: 50,child:AssetImage('assets/icon.png') // you can do whatever here
])//Stack
)//Repaint boundary
This is where the sauce is:
For android:
void _takePhoto(String _dataString) async {
int randomDigit;
var range = new Random();
randomDigit = range.nextInt(1000000) + 1;
RenderRepaintBoundary boundary =
_renderObjectKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file =
await new File('${tempDir.path}/image$randomDigit.png').create();
await file.writeAsBytes(pngBytes).then((value) {
GallerySaver.saveImage(value.path, albumName: 'Android Photo album')
.then((bool success) {});
});
}
For Ios:
Future<Uint8List> _getWidgetImage(String _dataString) async {
try {
RenderRepaintBoundary boundary =
_renderObjectKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
var pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.png').create();
await file.writeAsBytes(pngBytes);
await Share.file(_dataString, '$_dataString.png', pngBytes, 'image/png');
var bs64 = base64Encode(pngBytes);
debugPrint(bs64.length.toString());
return pngBytes;
} catch (exception) {
print(exception);
}
}
Calling the functions:
_takePhoto('$userID$randomDigit');//Android in a textbutton your choice
_getWidgetImage('$userID$randomDigit');//IOS in a textbtuton
keep in mind that I have not been tracking the flutter dependencies I used in this project but I will include them from my pubspec.yaml file:
qr_flutter: ^3.2.0
qrcode: ^1.0.4
barcode: ^1.17.1
share: ^0.6.5+4
gallery_saver: ^2.0.1
path_provider: ^1.6.24
path: ^1.7.0
esys_flutter_share: ^1.0.2
Note: Copy and paste will not work. This will need adjustments.
class ImagesCropper {
static Future<File?> cropImage(XFile file) async {
final File? croppedImage = await ImageCropper.cropImage(
sourcePath: file.path,
aspectRatioPresets:
Platform.isAndroid ? crossAspectRatioAndroid : crossAspectRatioIos,
androidUiSettings: androidUiSettings,
iosUiSettings: iosUiSettings,
);
return croppedImage;
}
}
i put the full code here:
https://controlc.com/9590e7b1
and here's the error in debug console
debug console
Just change ImageCropper.cropImage to ImageCropper().cropImage. This will use a new instance of ImageCropper.
It looks like you are using the ImageCropper package. https://github.com/hnvn/flutter_image_cropper/blob/master/lib/src/cropper.dart#L61 There was an error because the method isn't static so you have to create a new instance of the class to access it
await ImageCropper().cropImage...
The full code correction is below
class ImagesCropper {
static Future<File?> cropImage(XFile file) async {
final File? croppedImage = await ImageCropper().cropImage(
sourcePath: file.path,
aspectRatioPresets:
Platform.isAndroid ? crossAspectRatioAndroid : crossAspectRatioIos,
androidUiSettings: androidUiSettings,
iosUiSettings: iosUiSettings,
);
return croppedImage;
}
}
There are lot of references of uploading a dart:io 'File' but I want to upload a material.dart Image to firebase.
My Image comes from a processed Thumbnail of a video and not just picked by a Image picker.
This is how I generate a thumbnail,
Future<ThumbnailResult> genThumbnail(url) async {
//WidgetsFlutterBinding.ensureInitialized();
Uint8List bytes;
final Completer<ThumbnailResult> completer = Completer();
bytes = await VideoThumbnail.thumbnailData(
video: url,
imageFormat: ImageFormat.JPEG,
maxHeight: 250,
maxWidth: 300,
timeMs: 0,
quality: 0);
int _imageDataSize = bytes.length;
print("image size: $_imageDataSize");
final _image = Image.memory(bytes);
//final _file =File.fromRawPath(bytes);
_image.image
.resolve(ImageConfiguration())
.addListener(ImageStreamListener((ImageInfo info, bool _) {
completer.complete(ThumbnailResult(
image: _image,
dataSize: _imageDataSize,
height: info.image.height,
width: info.image.width,
));
}));
return completer.future;
}
and this is how File is uploaded to firebase
String Thumbfileurl = await uploadFile(thumbResult.image, fileName, fileType);
And inside uploadFile()
final StorageUploadTask uploadTask = storageReference.putFile(file);
So as you see , A File is needed , but i have an Image , is there a way to Convert Image to File or is there any workaround to achieve this .
I am using the image_picker and image_cropper plugin to select or capture the image with the help of the camera and Gallery. I got an image file from an image_picker. Now, I am using the Image.asset() widget to show the image in the Circle Avatar. Can anyone please tell me how I convert an image File to an asset image?
My code:
//Function that decides if image is returned or not(If not, then it will show the default circle avator)
File getImageWidget() {
if (_selectedImage != null) {
return _selectedImage;
} else {
return null;
}
}
//Function to set the image in the circle avatar
circleAva(){
return profileIconSelector(
setProfileIconHighQuality(getImageWidget() ?? userDetails.profile_pic,
userDetails.loginInitFrom),
userDetails.name,
SizeConfig.heightMultiplier * 5);
}
//Function to get image from Camera or Gallery
getImage(ImageSource source) async {
this.setState((){
_inProcess = true;
});
File image = await ImagePicker.pickImage(source: source);
if(image != null){
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(
ratioX: 1, ratioY: 1),
compressQuality: 100,
maxWidth: 700,
maxHeight: 700,
compressFormat: ImageCompressFormat.jpg,
androidUiSettings: AndroidUiSettings(
toolbarColor: Colors.deepOrange,
toolbarTitle: "Cropper",
statusBarColor: Colors.deepOrange.shade900,
backgroundColor: Colors.white,
)
);
this.setState((){
_selectedImage = cropped;
_inProcess = false;
});
} else {
this.setState((){
_inProcess = false;
});
}
}
You can't add asset images from your app. Asset images are images that you add to your project manually, but you can save the path to the image once it has been picked, then use Image.file(File.fromUri(Uri.file(IMAGE_PATH))).
Fortunately, I found the solution for this by myself.
In the case of the Image.file() widget, we have to provide the image of a File type.
And, In the case of the AssetImage() or Image.asset() widget, we need to pass the image path of String type.
So the Solution to use Image of File type in AssetImage() or
Image.asset() widget:
File _selectedImage = fetchedFromCameraOrGallery;
getImageWidget() {
if (_selectedImage != null) {
return CircleAvatar(
radius: SizeConfig.heightMultiplier * 5,
backgroundImage: AssetImage(
_selectedImage.path, //Convert File type of image to asset image path
),
);
}
}
We have to simply use the _selectedImage.path that will convert the image file of File type to a valid Asset image path format.
I managed to choose an image from gallery using the image picker and it is as follows
Future pickImage() async {
File _originalImage = await ImagePicker.pickImage(
source: ImageSource.camera);
if (_originalImage != null) {
File _croppedImage = await ImageCropper.cropImage(
sourcePath: _originalImage.path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9
],
androidUiSettings: AndroidUiSettings(
toolbarColor: BaengColors.blue,
toolbarTitle: 'Baeng Omang Cropper',
statusBarColor: BaengColors.blue[700],
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false
)
);
this.setState(() {
_imagePicked = _croppedImage;
isLoaded = true;
getTextFromImage();
});
}
}
Tried to debug it several times and it was not showing any kind of bug nor problem, but the image cropping activity remains black(without) the image selected from the image picker.
Please help
Just add maxHeight And maxWidth in Image_Picker
File _originalImage = await ImagePicker.pickImage(source: ImageSource.camera,
imageQuality: 20,
maxHeight: 500,maxWidth: 500);