Invalid data displaying image from path - flutter

I am downloading an image from Internet to the device and then updating a SQLITE table to store the image path:
Future<void> _download(String archivo, String docId, OfertaDB doc) async {
final docUrl = Constantes.docsProyecto+archivo;
final response = await http.get(Uri.parse(docUrl));
// Get the image name
final imageName = path.basename(docUrl);
// Get the document directory path
final appDir = await getApplicationDocumentsDirectory();
// This is the saved image path
// You can use it to display the saved image later
final localPath = path.join(appDir.path, imageName);
// Downloading
final imageFile = File(localPath);
await imageFile.writeAsBytes(response.bodyBytes);
print("path de ofertas ${appDir.path}/${imageName}");
var documentoDescargado = OfertaDB(
id: doc.id,
header: doc.header,
estado: doc.estado,
titulo: doc.titulo,
titulofr: doc.titulofr,
texto: doc.texto,
textofr: doc.textofr,
fechas: doc.fechas,
imagen: doc.imagen,
path: "${appDir.path}/${imageName}"
);
await dbHelper.updateOferta(documentoDescargado);
}
Then on another screen I need to display the image from SQLITE table:
var pathAr = news_promos.path;
print("path es ${pathAr}");//output /data/user/0/red.faro.labelconciergeflutter/app_flutter/Ezg7a9joalimaldivesvilla.jpeg
File image = File(pathAr);
Then to display the image:
Container(
alignment: Alignment.center,
width: 100,
height: 100,
child: image != null
? Image.file(image!, fit: BoxFit.cover)
: const Text('Please select an image'),
),
But the image is not displayed, it is shown an Exception: invalid image data error
What is wrong in the code used?

Related

File Picker png format images is giving issues

I was using ImagePicker in my application to select and upload images, but it recently started giving me errors, and constantly glitches when selecting png format images.
For this reason I switched to File picker. But it only works somewhat, and my application still gets stuck. I can only see its display, the image unfortunately does not get stored in the backend (jpg and jpeg images work fine).
Here is the image picker code (if there is a workaround uploading png images using this package, it would be much appreciated):
final ImagePicker _picker = ImagePicker();
Future imageSelectorGallery() async {
var image = (await _picker.pickImage(
source: ImageSource.gallery,
));
if (image != null) {
Uint8List imageBytes = await image
.readAsBytes(); // A fixed-length list of 8-bit unsigned integers which is the file read as bytes
String baseimage = base64Encode(imageBytes);
if (mounted) setState(() {});
post = baseimage;
Navigator.push(context,MaterialPageRoute(builder: (context) => CreatePosts(post,user,caption,upvotes)));
}
}
Here is the file picker code which I have implemented, any help figuring out the error here would also be appreciated:
Future imageSelectorGallery() async {
FilePickerResult? image = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
);
if (image != null) {
Uint8List? imageBytes = image.files.first.bytes;
String baseimage = base64Encode(imageBytes!);
if (mounted) setState(() {});
post = baseimage;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreatePosts(post, user, caption, upvotes)));
} else {
print("File picker error");
}
}
The image is displayed using:
child: Container(
height:
MediaQuery.of(context).size.height / 4.3,
width: MediaQuery.of(context).size.width / 3.4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
image: DecorationImage(
fit: BoxFit.cover,
image: Image.memory(
_bytesImage,
gaplessPlayback: true,
).image,
))),
),

Save and print generated barcode as image

I am using the barcode_widget to generate both barcode and 2d QR code. But I also need to print and save the codes.
My Current code for generating bar code and qr code is as below:
Center(
child: BarcodeWidget(
data: widget.product.productId!,
barcode: Barcode.code128(),
width: 200,
height: 200,
drawText: false,
),
),
and
BarcodeWidget(
data: widget.product.productId!,
barcode: Barcode.qrCode(),
),
Both are inside a Column and I have two buttons called save and print. So how can I save and print the generated codes?
You can use RepaintBoundary
Follow these steps:
1. Create a key.
GlobalKey _screenShotKey = GlobalKey();
2. Wrap the barcode in a repaint boundary and attach the key
RepaintBoundary(
key: _screenShotKey,
child: Center(
child: BarcodeWidget(
data: widget.product.productId!,
barcode: Barcode.code128(),
width: 200,
height: 200,
drawText: false,
),
)
)
3. Import dart:ui as ui
import 'dart:ui' as ui;
4. Create a method to take a screenshot of the widget and save it.
Future<File> takeScreenshot() async {
RenderRepaintBoundary boundary =
_screenShotKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final tempPath = (await getTemporaryDirectory()).path;
final path = tempPath + "qr.png";
File imgFile = File(path);
return imgFile.writeAsBytes(pngBytes);
}
5. To save in gallery/photos app; Use GallerySaver package
void save() async {
takeScreenshot().then((value) async {
bool saved = await GallerySaver.saveImage(value.path);
print(saved);
}).catchError((onError) {});
}

upload Image to firebase storage and NOT File

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 .

Getting a "File$" instead of a File in flutter

I am allowing users to grab a profile pic and upload that picture as file to my server, but I'm getting this error when inputting the image via ImagePickerWeb:
<error>:<getObject: Unexpected error from chrome devtools:>
I don't know if it's my browser or me, but this is what I'm trying:
Future<void> getMultipleImageInfos() async {
var imageFile =
await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
}
Then displaying that photo here:
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
)

How to use preference for showing profile picture in my application in flutter

I want to display a profile picture of the user when they log in. I am using the image URL stored in firestore database.
I want to keep the image in the app until logout. Every time I start the app, Image is called from that URL but I want to store it. I am new to flutter and have no clue to achieve this task.
Future<void> _getImage(ImageSource source) async {
var image = await ImagePicker.pickImage(source: source);
if (image != null) {
setState(() {
_cropImage(image);
});
}
Navigator.pop(context);
}
// Crop fetched image
_cropImage(File image) async {
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(ratioY: 1.0, ratioX: 1.0));
if (cropped != null) {
setState(() {
_imageFile = cropped;
uploadFile();
});
}
}
// Upload image file to firestrore Storage and get image URL
Future uploadFile() async {
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('${Path.basename(_imageFile.path)}}');
StorageUploadTask uploadTask = storageReference.putFile(_imageFile);
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
var url = downUrl.toString();
await uploadTask.onComplete;
setState(() {
imageUrl = url.toString();
});
// Show message on successful image upload
AppUtils.showToast('Picture Uploaded', green, white);
// Updating database with Image URL
Firestore.instance
.collection('account')
.document(widget.user)
.updateData({"url": imageUrl});
}
// Display Image
ClipRRect(
borderRadius: BorderRadius.circular(200.0),
clipBehavior: Clip.hardEdge,
child: Container(
height: 200,
width: 200,
child: widget.photoUrl == null
? Image(
image: NetworkImage(
'https://cdn1.iconfinder.com/data/icons/technology-devices-2/100/Profile-512.png'),
fit: BoxFit.fill,
)
: Image(
image: NetworkImage(widget.photoUrl),
fit: BoxFit.fill,
))),
What you need is a proper State Management throughout your app.
You can check the Provider Package to get started.
You can find more information about State Management here and here