cn1 - get file path to image for share() - share

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");

Related

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';

IONIC3 - WriteFile & WriteExistingFile is unable to overwrite the file

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.

Unable to display image from cordova.file.documentsDirectory

I am trying to access an image that i download from remote server. My code to download the file is as below :
var targetPath = cordova.file.documentsDirectory + propp+".png";
var trustHosts = true;
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
console.log("Local file transfer done");
r = angular.toJson(result.nativeURL);
}, function(err) {
// Error
console.log("error");
});
Then I stored tatgetPath in my local sqlite database. In another page I get this from sqlite and try to display with img tag. But it display like broken Image on Emulator as well as on actual device.
My file url is :
file:///var/mobile/Containers/Data/Application/F7B3169B-D8E3-4F62-AD0B-37CFA381F1CC/Documents/home_bg_image.png
I want to display this image as a background image bit I don't understand how to do this.
After downloading the image you have to paste it in platform/android/assets/www/img-- folder to display the image as
var filedirPath = $ionicPlatform.is('android') ? '/android_asset/www/img/' : 'img';
if not find the path of the image and access the file to display for reference please check this link File path
Having any queries reply ..

Facebook change image in page tab

I'm trying to change a facebook page tab image programatically. The idea is when my app will finish the instalation process, it will be change the image of the tab where it place it. After finish the process and give permissions to the app, The response of fb is "unautorized"
{"error":{"message":"(#300) Edit failure","type":"OAuthException","code":300}}
I searched about this error, the most close aproach was: https://developers.facebook.com/bugs/255313014574414/.
I tried the same CURL example described in the error and have the same response.
The strange thing is, when i tried change the image inside fb, it fails too. I think the problem is when the app ask permissions to install in the user page, and don't have enough permits.
But i don't know hot i chage the permit to authorize chage the image of the pagetab.
var fbparams = new Dictionary<string, object>();
string path = #"c:\test.jpg";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
var picture = new FacebookMediaObject
{
//Tell facebook that we are sending image
ContentType = "image/jpeg",
//Give name to the image
FileName = "test"
};
//Create a new byteArray with right length
var img = tabImageInfo.Media;
//Convert the image content into bytearray
fs.Read(img, 0, img.Length);`enter code here`
//Close the stream
fs.Close();
//Put the bytearray into Picture
picture.SetValue(img);
//Add the image into parameters
fbparams.Add("custom_image", picture);
fb.Post(tab.id, fbparams);

Resize an image resource in CQ5

I am trying to resize a given JCR image resource and store it as a new rendition. The use case is to generate thumbnails in "any" scale.
I wanted to use the com.day.cq.dam.core.process.CreateThumbnailProcess, but this it is not available in the project, i am working on.
I found a quite low level approach, to resize an image identified by jcrPathToImage to int targetWidth and int targetHeight.
Resize Image
Resource resource = getResourceResolver().getResource(jcrPathToImage);
Asset asset = resource.adaptTo(Asset.class);
Layer layer = new Layer(asset.getOriginal().getStream())
layer.resize(targetWidth, targetHeight);
Create new rendition in JCR
Extract mime type of the original image
Image image = new Image(resource);
String mimeType = image.getMimeType();
Store the resized Image using its asset representation.
ByteArrayOutputStream bout = null;
ByteArrayInputStream bin = null;
try {
bout = new ByteArrayOutputStream(2048);
layer.write(mimeType, 1, bout);
bin = new ByteArrayInputStream(bout.toByteArray());
asset.addRendition(resizedImgName, bin, mimeType);
} finally {
// close streams ...
}
you can configure the DAM Update Asset workflow to give the renditions you want to get created
http://localhost:4502/etc/workflow/models/dam/update_asset.html
in this workflow model select the thumbnail creation step and in the process tab of that step you can add your custom thumbnail values
[140:100],[48:48],[319:319],[90,90]