Flutter: local_image_provider is not showing all images - android

I was looking for a way to display a phone's gallery in a GridView. Came across the local_image_provider library. It does it's job pretty well. Not a lot of problems except the fact that using the "findLatest" method on the LocalImageProvider does not return the newest images from the gallery (it is the only way to show take images from the gallery and put them into a list as far as I know). Instead, the list I create from using this method on for example 25 newest images from the gallery skips quite a lot of images. It shows returns mostly screenshots and some downloaded pictures, along with some images taken with my camera. (I am testing this app on my phone). I simply can not find any info on this library so I have decided to ask myself. Here is some relevant code:
import 'package:local_image_provider/local_image_provider.dart' as lip;
Future<List<ImageProvider>> getLocalImage() async {
lip.LocalImageProvider imageProvider = lip.LocalImageProvider();
bool hasPermission = await imageProvider.initialize();
if ( hasPermission) {
List<lip.LocalImage> images = await imageProvider.findLatest(20);
if ( !images.isEmpty ) {
lip.LocalImage image = images.first;
lip.DeviceImage deviceImg = lip.DeviceImage( image );
List<ImageProvider> list = [];
images.forEach((element) {
list.add(lip.DeviceImage(element));
});
return list;
}
else {
print("No images found on the device.");
throw Exception();
}}
else {
print("The user has denied access to images on their device.");
throw Exception();
}
}
I then use this function as a future for a future builder which builds a gridview.

Related

How to get the thumbnail of an Android gallery picture, in NativeScript?

I understand that Android automatically creates a thumbnail, for every picture taken by the camera. I need to be able to display that thumbnail.
I'm using nativescript-imagepicker plugin to select images. The plugin returns only the size and src of the selected image(s), for instance:
'/storage/emulated/0/DCIM/DSCF2060.jpg'
How could i use this src, to retrieve the corresponding thumbnail(is it even possible?).
The Android API is very confusing for me(not to mention the Java), so any help will be greatly appreciated.
Use ThumbnailUtils
export function onGetImageButtonTap(args) {
let context = imagepicker.create({
mode: "single"
});
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected) {
const size = layout.toDevicePixels(96);
const bitmap = android.media.ThumbnailUtils.extractThumbnail(android.graphics.BitmapFactory.decodeFile(selected.android),
size, size);
args.object.page.getViewById("thumbnailImg").src = fromNativeSource(bitmap);
});
}).catch(function (e) {
console.log(e)
});
}
Playground Sample

Flutter NetworkImage handle 403 error

In my Flutter mobile app while loading profile image of users through NetworkImage(), I am getting 403 status code in response.
How can I handle this by displaying an Image from my assets folder in case of 403 status code or if image URL is broken etc.
Currently I've handled it by sending a HTTP GET request to the image URL and checking if the status code is 200. If it is 200 I use the NetworkImage() or else I use AssetImage() to load the image and use a FutureBuilder() to build the Widget.
While this works perfectly, I feel this a lot of trouble for handling such a small scenario and it can be done in a better way that I am unaware of.
What is the best way to handle such scenarios?
Please try below approach. Here, If image is available, It will load network image else it will redirect to the error callback. In error callback you can return the widget you want. In your case, you want to load from asset so you can use it like as below. If you want to check error status code, you need to parse the exception that I have print.
Image.network('https://www.outbrain.com/techblog/wp-content/uploads/2017/05/road-sign-361513_960_720.jpg',
errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
print("Exception >> ${exception.toString()}");
return Image.asset('assets/images/lake.jpg');
},
)
You did it simple for this scenario, I didnt see any trouble:
if (response.statusCode == 200) {
return NetworkImage();
} else {
return AssetImage();
}
I achieved this by using precacheImage. This will precache your image to flutter cache. It also has a onError function where you can handle errors while caching the image.
String validatedUrl;
precacheImage(
NetworkImage(urlToCheck),
context,
onError: (
exception,
stacktrace,
) {
print(exception.toString());
setState(() {
validatedUrl = '';
});
},
).whenComplete(() {
if (validatedUrl == null) {
setState(() {
validatedUrl = urlToCheck;
});
}
});
Then validatedUrl is either null, empty or carries the validated url.
null -> not validated yet
empty -> error while downloading image
url -> successfully downloaded image

Android 4.4.2 crash during picking image

During developing application in Xamarin Android we encountered strange error. The pick image/video (whether its from camera or documents UI) application sometimes crashes with no error. Scenario is that we open application, make steps to the activity, where the images are chosen, and then open the camera or document UI by standard way:
public void ChooseMediaAfterTypeChose (bool photo, bool camera) {
try {
string title = "";
int id;
Intent iIntent;
if (camera) {
if (photo) {
iIntent = new Intent("android.media.action.IMAGE_CAPTURE");
id = Const.AND_pickImageID_camera;
App._file = new File (App._dir, "myPhoto.jpg");
iIntent.PutExtra (Android.Provider.MediaStore.ExtraOutput, Uri.FromFile (App._file));
} else {
iIntent = new Intent("android.media.action.VIDEO_CAPTURE");
id = Const.AND_pickVideoID_camera;
App._file = new File (App._dir, "myVideo.mp4");
iIntent.PutExtra (Android.Provider.MediaStore.ExtraOutput, Uri.FromFile (App._file));
}
} else {
iIntent = new Intent ();
iIntent.SetAction (Intent.ActionGetContent);
if (photo) {
iIntent.SetType ("image/jpg");
title = Static.mainData.currentTexts.ChoosePhoto;
id = Const.AND_pickImageID_galery;
} else {
iIntent.SetType ("video/mp4");
title = Static.mainData.currentTexts.ChooseVideo;
id = Const.AND_pickVideoID_galery;
}
}
if (camera) {
StartActivityForResult (iIntent, id);
} else {
StartActivityForResult (Intent.CreateChooser (iIntent, title), id);
}
} catch (Exception ex) {
ShowError (Static.mainData.currentTexts.MediaError);
W.L(ex.Message);
}
}
The chosen application crashes during image/video picking (E.g. during browsing images in gallery wthout picking any). When that happens we never get to any method in our code.
What we have:
When user don't pick photos, the application runs without any memory crash
Sometimes the picking proceedes without error.
We think that the issue is mainly on Android 4.4.2 (It happend to us only on devices with this android - on other android version devices we didn't encounter it)
What we tried:
We put all permissions to manifest (read/write external storage, hardware.camera etc.)
We delete almost all memory stored content to save up memory
All Activities are unload from memory when they leave the screen
Logcat says that every process connected (Application and the active application) just died with no trace to any error
Our question is if anyone stumbled to similar issue and how to handle it. The second question is if there is any way to find out whats happening.
EDIT:
App._dir code added.
App._dir = new Java.IO.File (
Environment.GetExternalStoragePublicDirectory (
Environment.DirectoryPictures), "Camera");
if (!App._dir.Exists ())
{
App._dir.Mkdirs( );
}

Flex mobile take multiple photo

I develop mobile application with flex 4.6 and ı need take photo and ı did it but some forms need multiple photo. How can ı take multiple photo on phone?
My codes are;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
if (CameraUI.isSupported){
myCam = new CameraUI();
myCam.addEventListener(MediaEvent.COMPLETE, onComplete);
}
}
......
protected function button5_clickHandler(event:MouseEvent):void
{
theImage.filters = [];
theImage1.filters = [];
theImage2.filters = [];
theImage3.filters = [];
if (CameraUI.isSupported){
myCam.launch(MediaType.IMAGE);
}
}
private function onComplete(evt:MediaEvent):void{
theImage.source = evt.data.file.url;
theImage1.source= evt.data.file.url;
theImage2.source=evt.data.file.url;
theImage3.source=evt.data.file.url;
}
It appears as though you are storing the same data in multiple variables. If you need a dynamic number of photos, try adding it to an ArrayCollection like this:
private function onComplete(evt:MediaEvent):void{
myPhotos.add(evt.data.file.url);
}
That way, for every photo taken, you simply add it to a list of all the photos you have so far.

How to Save Full Resolution Image Back to CameraRoll (Android)

Device - Nexus One
OS - Android 2.3.4
Class - CameraRoll
Method - addBitmapData()
Error - [ErrorEvent type="error" bubbles=false
cancelable=false eventPhase=2 text="Error #2038: File I/O Error."
errorID=2038]
I'm trying to develop a photo app but am having problems saving the full sized version of the image back to the CameraRoll. This is very frustrating as I've only seen examples saving the stage to CameraRoll (which I can get to work).
Is there a limitation to saving back to CameraRoll?? When I try to load an image (2592 x 1944) and save it directly back to CameraRoll using addBitmapData(), I get the following error.
[ErrorEvent type="error" bubbles=false cancelable=false eventPhase=2 text="Error #2038: File I/O Error." errorID=2038]
Here's a code sample.
// class vars for CameraRoll and Loader
private var _cameraRoll:CameraRoll = new CameraRoll();
private var _loader:Loader = new Loader();
// launch _cameraRoll
private function launchCameraRoll(e:MouseEvent):void {
_cameraRoll.addEventListener(MediaEvent.SELECT, loadImg);
_cameraRoll.browseForImage();
}
// open selected image using _loader
private function loadImg(e:MediaEvent):void {
if (e.data.isAsync) {
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, saveImage);
_loader.loadFilePromise(e.data);
} else {
_loader.loadFilePromise(e.data);
saveImage();
}
}
// once loaded, save image immediately back to _cameraRoll
private function saveImage(e:Event = null):void {
_cameraRoll.addEventListener(ErrorEvent.ERROR, onError);
_cameraRoll.addEventListener(Event.COMPLETE, onComplete);
var bmd:BitmapData = new BitmapData(_loader.width, _loader.height);
bmd.draw(_loader);
_cameraRoll.addBitmapData(bmd);
}
// trace error
private function onError(e:ErrorEvent):void {
trace(e); // [ErrorEvent type="error" bubbles=false cancelable=false eventPhase=2 text="Error #2038: File I/O Error." errorID=2038]
}
// show complete status
private function onComplete(e:Event):void {
trace("complete");
}
I had the same problem (even with real small images).
I solved it by uncommenting this line in the <android><manifestAdditions> section of the [Application]-app.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
have you tried to save image in lower res? e.g. 1024x768? Maybe there is a limitation on the size that your device supports, I've found this or maybe the disk space is problem like mentioned here
best regards

Categories

Resources