I want to share an image that I took from the CameraController.
I location of the file is as example /data/user/0/com.user.test/cache/2019-09-10 16:32:52.281842.png
How it is possible to share this local image?
I added these two line for read/write to local storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I use the share component from https://pub.dev/packages/esys_flutter_share which works great.
void _sharePicture() async {
print('Share picture');
print(this.imagePath);
final ByteData bytes = await rootBundle.load(this.imagePath);
await Share.file('esys image', 'esys.png', bytes.buffer.asUint8List(), 'image/png', text: 'My optional text.');
}
this.imagePath is the local location of the file: :/data/user/0/com.user.test/cache/2019-09-10 16:32:52.281842.png
Do you first have to save the image? And the use it for sharing? How is it possible to share this local image?
The idea is share Uint8List
This demo use camera_camera package's example. https://github.com/gabuldev/camera_camera/tree/master/example
camera_camera package https://pub.dev/packages/camera_camera is an greate package have well made features and use camera plugin inside
code snippet
after click take picture, the system return a file (val in this example), read bytes and transfer to Uint8List
print("path ${val}");
List<int> bytes = await val.readAsBytes();
Uint8List ubytes = Uint8List.fromList(bytes);
await Share.file('ESYS AMLOG', 'amlog.jpg', ubytes, 'image/jpg');
full code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:camera_camera/camera_camera.dart';
import 'dart:typed_data';
import 'package:esys_flutter_share/esys_flutter_share.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
File val;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Rully")),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera_alt),
onPressed: () async {
val = await showDialog(
context: context,
builder: (context) => Camera(
mode: CameraMode.fullscreen,
orientationEnablePhoto: CameraOrientation.landscape,
/*
imageMask: CameraFocus.square(
color: Colors.black.withOpacity(0.5),
),
*/
));
print("path ${val}");
List<int> bytes = await val.readAsBytes();
Uint8List ubytes = Uint8List.fromList(bytes);
await Share.file('ESYS AMLOG', 'amlog.jpg', ubytes, 'image/jpg');
setState(() {});
}),
body: Center(
child: Container(
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width * 0.8,
child: val != null
? Image.file(
val,
fit: BoxFit.contain,
)
: Text("Tire a foto"))));
}
}
demo screen
In camera_camera example take picture button will show in landscape mdoe
file path display in bottom
For camera plugin official example, I only change the following
code snippet
void onTakePictureButtonPressed() {
takePicture().then((String filePath) async{
if (mounted) {
setState(() {
imagePath = filePath;
videoController?.dispose();
videoController = null;
});
if (filePath != null) {
showInSnackBar('Picture saved to $filePath');
File val = File(filePath);
List<int> bytes = await val.readAsBytes();
Uint8List ubytes = Uint8List.fromList(bytes);
await Share.file('ESYS AMLOG', 'amlog.jpg', ubytes, 'image/jpg');
}
}
});
}
Related
Isar does not persist state, every time I close my mobile application and open it again, previous values are not there, when they should be there. I'm fetching those values from Isar.
Please show with a counter app example how this works.
I'm attaching files.
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:isarapp/counter_schema.dart';
import 'package:isar/isar.dart';
import 'package:isarapp/home_screen.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var directory = await getApplicationDocumentsDirectory();
var path = directory.path;
await Isar.open(
[CounterObjectSchema],
directory: path,
inspector: true,
name: "isardb",
);
runApp(const MyApp());
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context, WidgetRef ref) {
return ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomeScreen(),
),
);
}
}
I have edited android manifest file to get store permission then using permission_handler for getting storage access.
home_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:isar/isar.dart';
import 'package:isarapp/counter_schema.dart';
import 'package:permission_handler/permission_handler.dart';
final counterProvider1 = StateProvider<int>((ref) {
return 0;
});
class HomeScreen extends ConsumerStatefulWidget {
const HomeScreen({super.key});
#override
ConsumerState<ConsumerStatefulWidget> createState() => _HomeScreenState();
}
getStoragePermission() async {
var status = await Permission.storage.status;
if (status.isDenied) {
Permission.storage.request();
}
}
class _HomeScreenState extends ConsumerState<HomeScreen> {
Isar? isar = Isar.getInstance("isardb");
CounterObject counterObject = CounterObject(counter: 9);
initCounter() async {
var count = await isar?.collection<CounterObject>().get(counterObject.id);
//reset counter on launch
ref.read(counterProvider1.notifier).state = count?.counter ?? -1;
}
increment() async {
counterObject.counter = counterObject.counter + 1;
//update state
ref.read(counterProvider1.notifier).state = counterObject.counter;
//writing counterValue to isardb on every increment call
isar?.writeTxn(
() async => await isar?.collection<CounterObject>().put(counterObject),
);
}//increment
#override
void initState() {
getStoragePermission();
//putting counterObject in
isar?.writeTxn(
() async => await isar?.counterObjects.put(counterObject),
);
initCounter();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Text(
ref.watch(counterProvider1).toString(),
style: const TextStyle(fontSize: 54),
),
GestureDetector(
onTap: () => increment(),
child: Container(
width: 200,
height: 40,
color: Colors.blue[300],
child: const Center(child: Text("Add")),
),
),
],
),
),
),
);
}
}
CounterObjectSchema
import 'package:isar/isar.dart';
part 'counter_schema.g.dart';
#collection
class CounterObject {
Id id = Isar.autoIncrement;
int counter;
CounterObject({required this.counter});
}
I have written the code by taking help from official documentation of each plugin. Inspite of that I am getting errors mentioned below. Can anyone help what is the issue ?
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:path/path.dart';
import 'package:photofilters/photofilters.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as imageLib;
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File _image;
String fileName;
Filter _filter;
List<Filter> filters = presetFiltersList;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
fileName = basename(pickedFile.path);
var image = imageLib.decodeImage(pickedFile.readAsBytesSync());
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
getImage();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotoFilterSelector(
image: _image,
filters: filters,
filename: fileName,
loader: Center(child: CircularProgressIndicator()),
),
));
},
label: Text("+"),
icon: Icon(
Icons.print,
color: Colors.black,
),
),
);
}
}
ERRORS :
The method 'readAsBytesSync' isn't defined for the type 'PickedFile'.
Try correcting the name to the name of an existing method, or defining a method named 'readAsBytesSync'.
2 positional argument(s) expected, but 1 found.
Try adding the missing arguments.
3.The argument type 'String' can't be assigned to the parameter type 'List'.
The argument type 'File' can't be assigned to the parameter type 'Image'.
You can copy paste run full code below
Step 1: Use imageLib.Image _image; not File _image;
Step 2: Use _file.readAsBytesSync()
File _file = File(pickedFile.path);
_image = imageLib.decodeImage(_file.readAsBytesSync());
Step 3: onPressed need to use async and await
onPressed: () async{
await getImage();
working demo
full code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter/semantics.dart';
import 'package:path/path.dart';
import 'package:photofilters/photofilters.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as imageLib;
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
imageLib.Image _image;
//File _image;
String fileName;
Filter _filter;
List<Filter> filters = presetFiltersList;
final picker = ImagePicker();
Future getImage() async {
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
fileName = basename(pickedFile.path);
File _file = File(pickedFile.path);
_image = imageLib.decodeImage(_file.readAsBytesSync());
setState(() {
if (pickedFile != null) {
//_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () async{
await getImage();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotoFilterSelector(
title: Text("Photo Filter Example"),
image: _image,
filters: filters,
filename: fileName,
loader: Center(child: CircularProgressIndicator()),
),
));
},
label: Text("+"),
icon: Icon(
Icons.print,
color: Colors.black,
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
Is there a way to resize an image without having it previously written to storage?
I am using a pdf library that for the images needs the bytes of it.
What I do is get image with an http.get and I get the bytes to put it in the pdf.
The problem is that I need to resize the image BEFORE putting it in the pdf.
The only thing I have is the url of the image or the uint8list
Response response = await http.get(imageUrl);
Uint8List imgBytes = response.bodyBytes;
Later:
Image(
PdfImage.file(pdf.document,
bytes: imageBytes)
),
Pdf lib I use: https://pub.dev/packages/pdf
You can copy paste run full code below
You can use ui.instantiateImageCodec and specify targetHeight and targetWidth
You can see output image size become smaller after resize
code snippet
String imageUrl = 'https://picsum.photos/250?image=9';
http.Response response = await http.get(imageUrl);
originalUnit8List = response.bodyBytes;
ui.Image originalUiImage = await decodeImageFromList(originalUnit8List);
ByteData originalByteData = await originalUiImage.toByteData();
print('original image ByteData size is ${originalByteData.lengthInBytes}');
var codec = await ui.instantiateImageCodec(originalUnit8List,
targetHeight: 50, targetWidth: 50);
var frameInfo = await codec.getNextFrame();
ui.Image targetUiImage = frameInfo.image;
ByteData targetByteData =
await targetUiImage.toByteData(format: ui.ImageByteFormat.png);
print('target image ByteData size is ${targetByteData.lengthInBytes}');
targetlUinit8List = targetByteData.buffer.asUint8List();
output of working demo
I/flutter (17023): original image ByteData size is 250000
I/flutter (17023): target image ByteData size is 4060
working demo
full code
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Uint8List targetlUinit8List;
Uint8List originalUnit8List;
void _resizeImage() async {
String imageUrl = 'https://picsum.photos/250?image=9';
http.Response response = await http.get(imageUrl);
originalUnit8List = response.bodyBytes;
ui.Image originalUiImage = await decodeImageFromList(originalUnit8List);
ByteData originalByteData = await originalUiImage.toByteData();
print('original image ByteData size is ${originalByteData.lengthInBytes}');
var codec = await ui.instantiateImageCodec(originalUnit8List,
targetHeight: 50, targetWidth: 50);
var frameInfo = await codec.getNextFrame();
ui.Image targetUiImage = frameInfo.image;
ByteData targetByteData =
await targetUiImage.toByteData(format: ui.ImageByteFormat.png);
print('target image ByteData size is ${targetByteData.lengthInBytes}');
targetlUinit8List = targetByteData.buffer.asUint8List();
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
originalUnit8List == null
? Container()
: Image.memory(originalUnit8List),
targetlUinit8List == null
? Container()
: Image.memory(targetlUinit8List),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _resizeImage,
tooltip: 'Resize',
child: Icon(Icons.add),
),
);
}
}
I have a table in postgresql that has a field with a pdf file in base64 format. When I get it from flutter, how can I show it with pdf viewer ?, has anyone done it ??
I appreciate your help
In pubspec.yaml add the following dependency:
dependencies:
flutter_full_pdf_viewer: ^1.0.6 # for pdf
Then run flutter pub get in Android Studio terminal to update dependencies.
Create the file 'pdfBase64Viewer.dart:
import 'dart:async'; // asynchroneous function (await)
import 'dart:io'; // write the file on user's phone
import 'dart:convert'; // handle base64 decoding
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:path_provider/path_provider.dart';
class PdfBase64Viewer extends StatefulWidget {
final String url;
const PdfBase64Viewer(String this.url);
#override
_PdfBase64ViewerState createState() => new _PdfBase64ViewerState();
}
class _PdfBase64ViewerState extends State<PdfBase64Viewer> {
String pathPDF = "";
#override
void initState() {
super.initState();
createFileOfPdfUrl(widget.url).then((f) {
setState(() {
pathPDF = f.path;
print(pathPDF);
});
});
}
Future<File> createFileOfPdfUrl(is_base_64) async {
final filename = widget.url.substring(widget.url.lastIndexOf("/") + 1);
var request = await HttpClient().getUrl(Uri.parse(widget.url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
var base64String = utf8.decode(bytes);
var decodedBytes = base64Decode(base64String.replaceAll('\n', ''));
String dir = (await getApplicationDocumentsDirectory()).path;
File file = new File('$dir/$filename');
await file.writeAsBytes(decodedBytes.buffer.asUint8List());
return file;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Plugin example app')),
body: Center(
child: RaisedButton(
child: Text("Open PDF"),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => PDFScreen(pathPDF)),
),
),
),
);
}
}
class PDFScreen extends StatelessWidget {
String pathPDF = "";
PDFScreen(this.pathPDF);
#override
Widget build(BuildContext context) {
return PDFViewerScaffold(
appBar: AppBar(
title: Text("Document"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: () {},
),
],
),
path: pathPDF);
}
}
You can adapt above class in order to assign to the variable base64String the String value that you get from your DB.
You can use it the following way:
import 'pdfBase64Viewer.dart';
(...)
child: PdfBase64Viewer("https://filebin.net/qmvmxbgn6pzgkbzb/sample.base64?t=7g5s9rwr") // url of your base64 file
(...)
You might want to check the following documentation:
Base64
Full Pdf Viewer
I am trying to create a new Image from two existing images using Canvas
one Img from asset ("asset image")
one Img from network
To achieve that first problem is to draw "asset image" on Canvas using drawImage.. this is where I am facing the problem.
drawCircle is working fine, But for using drawImage as per following code, it is outputting blank image.
I am new to using Canvas and experimenting, any help appreciated..
Complete code..
import 'package:flutter/material.dart';
//import 'package:path_provider/path_provider.dart';
import 'dart:ui' as ui;
import 'dart:typed_data';
import 'dart:async';
//import 'dart:io';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Image _image;
ui.Image imagetoDraw;
#override
void initState() {
super.initState();
_image = new Image.network(
'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png',
);
getImageFromAsset();
}
getImageFromAsset() async {
imagetoDraw = await load('images/loading.png');
print('...getImageFromAsset done');
}
Future<ui.Image> load(String asset) async {
ByteData data = await rootBundle.load(asset);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
ui.FrameInfo fi = await codec.getNextFrame();
return fi.image;
}
_generateImage() {
_generate().then((val) => setState(() {
_image = val;
}));
}
Future<Image> _generate() async {
ui.PictureRecorder recorder = new ui.PictureRecorder();
Canvas c = new Canvas(recorder);
var rect = new Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
c.clipRect(rect);
final paint = new Paint();
paint.strokeWidth = 2.0;
paint.color = const Color(0xFF333333);
paint.style = PaintingStyle.fill;
final offset = new Offset(50.0, 50.0);
// c.drawCircle(offset, 40.0, paint);
c.drawImage(imagetoDraw, offset, paint);
var picture = recorder.endRecording();
final pngBytes = await picture
.toImage(100, 100)
.toByteData(format: ui.ImageByteFormat.png);
var image = Image.memory(pngBytes.buffer.asUint8List());
return image;
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_image,
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _generateImage,
tooltip: 'Generate',
child: new Icon(Icons.add),
),
);
}
}
The image asset path seems to be the problem. I can not say that for sure, as There is no pubspec.yaml asset declarations here.
Let's assume that you have added assets in pubspec.yaml as below:
assets:
- assets/images/image_01.png
- assets/images/image_02.jpg
In that case, you need to specify the path of asset 'assets/images/image_01.png'.
Means the exact path that is defined inside the pubspec.yaml file.
i.e. In your case, imagetoDraw = await load('assets/images/image_01.png');
Tip: You can directly use Image.asset('assets/images/image_01.png'); to get the image from assets.
The source I have referred to: Load Image from assets in flutter
I hope this helps.