What path format should I use with bitmapfactory.decodeFile(string pathname)? - android-resources

I want to use the function bitmapfactory.decodeFile(string pathname).
But on using it, NULL is being returned.
Please specify what or how to WRITE the PATHNAME, with an example.
for(int j=0;j<3;j++)
{
img_but[count].setImageBitmap(BitmapFactory.decodeFile("/LogoQuiz/res/drawable-hdpi/logo0.bmp"));
linear[i].addView(img_but[count]);
count++;
}
Instead of such a pathname, what should be used?

If you want to use filenames, then you can not put them inside the drawable folder. The only way you can do this is by putting the images inside the assets folder. If you do not have an assets/ folder, then you must create one inside your main project. It should be in the same branch as your gen/, res/, and src/ folders.
You can have any file structure in your assets folder you want. So for example, you can put your images in the assets/images/ folder. Sound files can go in a assets/sounds/ folder. You access an image like so:
public Bitmap getBitmap(Context ctx, String pathNameRelativeToAssetsFolder) {
InputStream bitmapIs = null;
Bitmap bmp = null;
try {
bitmapIs = ctx.getAssets().open(pathNameRelativeToAssetsFolder);
bmp = BitmapFactory.decodeStream(bitmapIs);
} catch (IOException e) {
// Error reading the file
e.printStackTrace();
if(bmp != null) {
bmp.recycle();
bmp = null
}
} finally {
if(bitmapIs != null) {
bitmapIs.close();
}
}
return bmp;
}
The path name, as the variable name suggests, should be relative to the assets/ folder. So if you have the images straight in the folder, then it's simply imageName.png. If it's in a subfolder, then it's subfolder/imageName.png.
Note: Android will not choose from density folders in the assets folder. It decodes the images as-is. Any further adjustments for screen density and resolution will have to be done by you.
Opening a File from assets folder in android

Related

Files are empty after downloading zip from assets flutter

I have a file and folder structure like
Folder
subfolder x
file_x.txt
file_y.txt
....
subfolder y
file_x.txt
file_y.txt
....
subfolder n
I created zip of complete structure in ubuntu and paste that zip in assets folder of flutter project, added assets in pubspecc.yaml
Now I want to open asset zip add new generated file and download complete zip For this i am using archive package. code to load asset add new file and download is as
downloadZip() async {
/// this function open zip template from assets and add custom file in zip
/// and then download whole zip
String newFileString = '...';
final zipEncoder = ZipEncoder();
List<int> utf8encodedData = utf8.encode(newFileString); // newFileString is content of new file to be added
ArchiveFile newFile =
ArchiveFile("file", utf8encodedData.length, utf8encodedData);
DefaultAssetBundle.of(Get.context!)
.load("files/file.zip")
.then((ByteData value) {
Uint8List wzzip =
value.buffer.asUint8List(value.offsetInBytes, value.lengthInBytes);
InputStream inputFileStream = InputStream(wzzip);
final archive = ZipDecoder().decodeBuffer(inputFileStream);
archive.addFile(newFile);
final encodedFile = zipEncoder.encode(archive);
String content = base64Encode(encodedFile!);
html.AnchorElement(
href:
"data:application/octet-stream;charset=utf-16le;base64,$content")
..setAttribute("download", "project.zip")
..click();
inputFileStream.close();
});
}
Problem: In downloaded zip, folder structure is perfect but all files are empty except newFile that i added

How should i configure about images in pubsec.yml for nested structure

I've set simply the pubsec.yaml and it has been worked successfully as follows;
images/logo1.png
images/logo2.png
//pubsec.yml
# To add assets to your application, add an assets section, like this:
assets:
- images/
//indents are set appropriately
However, it doesn't work when I restructure as following and with no changings is pubsecyml;
images/main/logo1.png
images/sub/logo2.png
image_provider throws errors like
Future<ui.Codec> _loadAsync(AssetBundleImageKey key, DecoderBufferCallback? decode, DecoderCallback? decodeDepreacted) async {
if (decode != null) {
ui.ImmutableBuffer? buffer;
// Hot reload/restart could change whether an asset bundle or key in a
// bundle are available, or if it is a network backed bundle.
try {
buffer = await key.bundle.loadBuffer(key.name);
} on FlutterError {
PaintingBinding.instance.imageCache.evict(key);
rethrow;//here
}
if (buffer == null) {
PaintingBinding.instance.imageCache.evict(key);
throw StateError('Unable to read data');
}
return decode(buffer);
}
ScreenShot for pubsec.yml

Regarding How to draw Unicode text in a PDF file

The following is excellent instruction. This is helpful information.
https://www.syncfusion.com/kb/11976/how-to-draw-unicode-text-in-a-pdf-file-using-google-fonts-package
However, I can't understand how to create the TTF file data by the getFont method. There is no "writeAsBytes" statement. This means the TTF file is always empty.
In what cases is the following condition TRUE?
// Line 11 of getFont
if (fontBytes != null && fontBytes.isNotEmpty) {
In the below KB documentation, we are getting the font from the Google fonts package in Flutter. The Google fonts package fetches the font files via HTTP at runtime and caches them in the application’s file system. In this article, we have used cached files to render the Unicode text in a PDF document. The reported problem is due to the Flutter Google fonts package being updated. And please make sure the device/emulator internet connectivity is properly connected or not. If not, please connect to the internet and try the below code snippet on your end and let us know the result.
Please refer to the below code snippet,
Future<PdfFont> getFont(TextStyle style) async {
//Get the external storage directory
Directory directory = await getApplicationSupportDirectory();
//Create an empty file to write the font data
File file = File('${directory.path}/${style.fontFamily}.ttf');
if (!file.existsSync()) {
List<FileSystemEntity> entityList = directory.listSync();
for (FileSystemEntity entity in entityList) {
if (entity.path.contains(style.fontFamily!)) {
file = File(entity.path);
break;
}
}
}
List<int>? fontBytes;
//Check if entity with the path exists
if (file.existsSync()) {
fontBytes = await file.readAsBytes();
}
if (fontBytes != null && fontBytes.isNotEmpty) {
//Return the google font
return PdfTrueTypeFont(fontBytes, 12);
} else {
//Return the default font
return PdfStandardFont(PdfFontFamily.helvetica, 12);
}
}

Flutter how to specify file path in asset folder

I have a sound file in asset folder and I can check if it exist using code like below:
if (FileSystemEntity.typeSync(
'/Users/admin/Library/Developer/CoreSimulator/Devices/AC8BED2E-4EF1-4777-A399-EBD52E38B5C7/data/Containers/Data/Application/1390EE2C-A5D8-46E0-A414-AAC2B83CD20C/Library/Caches/sounds/3/unbeaten.m4a') !=
FileSystemEntityType.notFound) {
print('file is found');
} else {
print('not found');
}
As you can see I need to use the absolute path. Is there a way to check if the file is in the asset folder using path like 'assets/sounds/3/unbeaten.m4a' without the need to specify the whole path?
As was mentioned by #frank06, by using path_provider, I am able to check if a file is in asset folder or not by using the following code. But this works for iOS only and I am still trying to find a solution for Android. Notice the need to add /Library and /Caches for iOS. For Android, it seems that I can't see the path unlike that of iOS.
I would appreciate it if anyone could provide me some info for that of Android. The appDir looks like this for Android - /data/user/0/com.learnchn.alsospeak/app_flutter/
directory = await getApplicationDocumentsDirectory();
var parent = directory.parent;
var directoryPath = directory.path;
var parentPath = parent.path;
String testString = 'sounds/3/unbeaten.m4a';
parentPath = parentPath + '/Library' '/Caches/' '$testString';

How to load image from folder but not resource folder

I put my image at /Assets/Test/Textures/Player but without success my code is:
IEnumerator loadTexture(string videotype) {
if(videotype.Equals("3d")) {
WWW www = new WWW("file:///Assets/Meta1/Textures/Player/3D_foucs.png");
yield return www;
texture3D.mainTexture = www.texture;
} else if(videotype.Equals("2d") ){
} else if(videotype.Equals("360")) {
}
}
Place your png file in Resources folder of your project and load it using:
Texture2D _texture = Resources.Load("3D_foucs.png") as Texture2D;
EDIT :
If you really want to avoid using Resources.Load() then you can use Application.dataPath to access assets folder. But make sure you read the docs before that.
P.S : WWW is usually good for loading stuff from outside of project.
E.g from Application's Persistent Data or from web server.
Hope it helps