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
Related
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';
I would like to do image annotation for my Ionic Application. So the flow of the app would be using the camera plugin to take a picture and use FabricJs to draw on the image then save the file.
I hit the roadblock when I am trying to save or overwrite the file. Apparently the source "http://localhost:8080/file/data/user/0/***/files/1547183479807.png" file does not update.
The flow of the app
1) Take picture with #ionic-native/camera
2) Copy the file to a local directory
3) Use this.win.Ionic.WebView.convertFileSrc to convert the file name to "http://localhost:8080/file/data/user/0/***/files/1547183479807.png"
4) Push to another page to access the canvas
5) Use the link to setBackground to my canvas (FabricJs)
6) Draw on the image (Manually)
7) Save the file via overwriting the existing file but nothing works from here on.
I tried to
- overwrite with writeFile & writeExisitingFile, did not work.
- removeFile and writeFile and did not work.
- tried converting to ArrayBuffer rather than Blob and did not work
- tried creating another new file, did not work too (it seems like after I push to a new page, all the file functions does not affect the files)
- tried using native cordova but did not work too.
- delete that same files twice, (first time I did not get an error but the second time I got an error saying "File Does not exist" but when I view the source, the file is also there and appearing in my thumbnail on my App.
private copyFileToLocalDir(namePath, currentName, newFileName,id,index) {
this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
const keys = id.split('-');
let filename = this.file.dataDirectory + newFileName;
this.fp = this.win.Ionic.WebView.convertFileSrc(filename) ;
this.navCtrl.push(AnnotationsPage, {
filepath: this.fp,
filename: newFileName
});
this.presentToast("Image Successfully Added",'middle');
}, error => {
this.presentToast('Error while storing file.','middle');
});
}
Annotation.ts
savePicture() {
let image = this.canvas.toDataURL({
format: 'png'
});
this.saveBase64(image);
}
public saveBase64(base64:string):Promise<string>{
return new Promise((resolve, reject)=>{
var realData = base64.split(",")[1]
let blob=this.b64toBlob(realData,"image/png")
this.file.writeFile(this.file.dataDirectory,this.filename,blob,{replace:true})
// this.file.writeExistingFile(this.file.dataDirectory,this.filename, blob)
.then((val)=>{
console.log('Write Info',val)
let fp = this.win.Ionic.WebView.convertFileSrc(this.file.dataDirectory+this.filename) ;
})
.catch((err)=>{
console.log('error writing blob')
console.log(err);
// reject(err)
})
})
}
b64toBlob(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
I check the base64 file, it is working fine (Throw the data to an online converter and it display the picture.
After the function "copyFileToLocalDir", it seems like I am unable to modify the files store in the local directory.
Thanks in advance. Feel free to ask me more question. 7 hours and no result.
Update on the testing, I am doing.
Did File.readAsDataUrl and as expected the file file:///data/user/0/*/files/1547231914843.png updated from the old image to the new edited. (Tested the base64 on some online converter) but it still does not reflect on the source http://localhost:8080/file/data/user/0/***/files/1547231914843.png
Thanks to all those who read through.
After tons of testing, I found out that Ionic Webview's files, will not be updated unless you recall them again (Kind of like a cache and apparently there is no way to reset or flush the cache).
So in my case, I would need to remove the image from the webview and call it out again then it will go back to retrieve again or create another file with another file name and display it.
I'm trying to use the share() method, including an image, but I'm having trouble supplying the proper path to the image. Where should I put the image file, and what is the path (putting in the default package and trying "jar:///myimage.png" didn't work), and why is this not documented clearly?
image can be stored in storage which is following path for window
C:\Users\userName.cn1
and the image can be read by using following codes
InputStream is = Storage.getInstance().createInputStream("tizbn.JPG");
EncodedImage i = EncodedImage.create(is, is.available());
Loading image from default folder
Image i =EncodedImage.create("/tizbn.png");
Loading image From Theme
EncodedImage current = (EncodedImage) fetchResourceFile().getImage("tizbn.png");
The share API works with https://www.codenameone.com/javadoc/com/codename1/io/FileSystemStorage.html[FileSystemStorage] and not with https://www.codenameone.com/javadoc/com/codename1/io/Storage.html[Storage].
You need to save the file into a file system path which is always an absolute path, we recommend using the app home to store files. There is a sample in the developer guide section on the ShareButton covering this:
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");
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
I've tried to open local PDFs stored in the www/Documents folder in my XCode project. The code I put in .js file is:
Cordova.exec("ChildBrowserCommand.showWebPage", "file:///www/Documents"+pdf );
Where pdf is the name of the file, which changes for every file. It works fine on the simulator but it doesn't work on device. How can I fix this?
Thanks!
I am using below function to load files in childbrowser, it creates the correct local url in case you want to load the internal files:
function loadChildBrowser(isInternal, URL) {
if(isInternal){
var strPath = window.location.href;
var path = strPath.substr(0,strPath.lastIndexOf('/')) + URL;
cb.showWebPage(encodeURI(path));
}
else{
cb.showWebPage(URL);
}
}
Edit
Try this for your case:
function loadChildBrowser(isInternal, URL) {
if(isInternal){
var strPath = window.location.href;
var path = strPath.substr(0,strPath.lastIndexOf('/')) + URL;
Cordova.exec("ChildBrowserCommand.showWebPage", encodeURI(path) );
}
else{
Cordova.exec("ChildBrowserCommand.showWebPage", URL );
}
}