Resize the image before uploading images from openGallery method - codenameone

I want to resize the image from the gallery and then upload it. Since users may select large sized images that may take much time to upload. Say I want to resize the image to 1024px width and the height rescaling with respect to the width. I used openGallery method where I don't find any parameter for specifying the width for the img to be resized. I think if I am not mistaken, (for camera img) Capture.capturePhoto(Display.getInstance().getDisplayWidth() / 2, -1) does the trick. How can I achieve it for the images from the gallery? Thankyou
Display.getInstance().openGallery(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
if (evt == null) {
System.out.println("user cancelled");
return;
}
eventImgpath = (String) evt.getSource();
Image i = Image.createImage(eventImgpath);
eventImage.setIcon(i.scaledWidth(Display.getInstance().getDisplayWidth()));
eventImage.getParent().revalidate();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, Display.GALLERY_IMAGE);
//sending the img path to connectionRequest
String eventImgPathFinal = eventImgpath;
AddBusinessForumConnection abfc = new AddBusinessForumConnection();
abfc.addBusinessForumConnectionMethod(eventImgPathFinal);
Uploading the img
public void addBusinessForumConnectionMethod(String eventImg) {
ConnectionRequest connectionRequest = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
}
#Override
protected void postResponse() {
}
};
AllUrl allUrl = new AllUrl();
connectionRequest.setUrl(allUrl.addBusinessForumUrl);
connectionRequest.setPost(true);
connectionRequest.addArgument("imgUrl", new ImageBase64().getBase64(eventImg));
NetworkManager.getInstance().addToQueueAndWait(connectionRequest);
}

Use the ImageIO to resize:
ByteArrayOutputStream out = = new ByteArrayOutputStream();
ImageIO.getImageIO().save(path, out, ImageIO.FORMAT_JPEG,
maxWidth, -1, 1);
byte [] data = out.toByteArray();

Related

iOS save to storage issue

I've an issue while trying to save an image to the Storage in iOS. Image is downloaded but not saved.
The code is:
Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TreeModel tm = new TreeModel() {
#Override
public Vector getChildren(Object parent) {
String[] files;
if (parent == null) {
files = FileSystemStorage.getInstance().getRoots();
return new Vector<Object>(Arrays.asList(files));
} else {
try {
files = FileSystemStorage.getInstance().listFiles((String) parent);
} catch (IOException err) {
Log.e(err);
files = new String[0];
}
}
String p = (String) parent;
Vector result = new Vector();
for (String s : files) {
result.add(p + s);
}
return result;
}
#Override
public boolean isLeaf(Object node) {
return !FileSystemStorage.getInstance().isDirectory((String) node);
}
};
Command tree = new Command("Show tree") {
#Override
public void actionPerformed(ActionEvent evt) {
Form treeForm = new Form("Tree", new BorderLayout());
Tree t = new Tree(tm) {
#Override
protected String childToDisplayLabel(Object child) {
String n = (String) child;
int pos = n.lastIndexOf("/");
if (pos < 0) {
return n;
}
return n.substring(pos);
}
};
treeForm.add(BorderLayout.CENTER, t);
Command back = new Command("Back") {
#Override
public void actionPerformed(ActionEvent evt) {
hi.showBack();
}
};
Button backButton = new Button(back);
treeForm.add(BorderLayout.SOUTH, backButton);
treeForm.show();
}
};
hi.getToolbar().addCommandToOverflowMenu(tree);
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
String photoURL = "https://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg";
StringBuilder fsPath = new StringBuilder(FileSystemStorage.getInstance().getAppHomePath());
fsPath.append("400px-AGameOfThrones.jpg");
URLImage background = URLImage.createToStorage(placeholder, fsPath.toString(), photoURL);
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("Link");
credit.addActionListener((e) -> Display.getInstance().execute("https://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A")).
add(new Label("B", "Heading")).
add(credit);
ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();
Which was taken from https://www.codenameone.com/javadoc/com/codename1/ui/URLImage.html
The tree is only to see if the image was saved in the Storage.
You are mixing Storage & FileSystemStorage which are very different things see this.
You can use storage which is a flat set of "files" and that's what URLImage.createToStorage does. But then you need to use the Storage API to work with that and it might not be visible in the FileSystemStorage API.
Alternatively you might be looking for URLImage.createToFileSystem().

Write/Read the image from fileSystemStorage and readjust it before saving

I have saved an image using fileSystemStorage with the name of "profile.png". But how cab I read the image and display it afterward. I had used Storage.getInstance.writeObject and
readObject before but I think it doesnt work for images.
userImg.addActionListener((e) -> {
Display.getInstance().openGallery(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
if (evt == null) {
System.out.println("user cancelled");
return;
}
eventImgpath = (String) evt.getSource();
Image i = Image.createImage(eventImgpath);
Image profileImg = i.scaledWidth(Display.getInstance().getDisplayWidth() / 3);
InputStream stream = FileSystemStorage.getInstance().openInputStream(eventImgpath);
OutputStream out = Storage.getInstance().createOutputStream("profile.png");
Util.copy(stream, out);
Util.cleanup(stream);
Util.cleanup(out);
userImg.setIcon(profileImg);
userImg.setPreferredH(20 + Display.getInstance().getDisplayWidth() / 3);
userImg.getParent().revalidate();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, Display.GALLERY_IMAGE);
});
I have one more question. How can I re-adjust the image as an icon in a label? for eg we can readjust or drag to repostion cover img in facebook before saving it. Since it is a profile image while saving it sometime the face is not shown so I need to reposition the image and save it as a label icon. Is there any example for it?
Thankyou

FileSystemStorage isDirectory returns false for a directory

I am trying to write a file browser in CN1 to let the user select a profile picture for upload.
I tried using the FileSystemStorage's isDirectory() method, but it is returning false for a directory.
Code:
private void displayFiles(final Container c, String root)
{
c.removeAll();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
String files[] = fs.listFiles(root);
for(final String file: files)
{
System.out.println(file+"-->"+fs.isDirectory(file));
if(fs.isDirectory(file))
{
Button b = new Button("Folder::"+file);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
displayFiles(c, file);
}
});
c.addComponent(b);
}else
{
Container c1 = new Container(new BoxLayout(BoxLayout.X_AXIS));
Label l = new Label("File::"+file);
CheckBox cb = new CheckBox();
c1.addComponent(l);
c1.addComponent(cb);
c.addComponent(c1);
}
}
} catch (IOException ex) {
}
c.revalidate();
}
Output:
CN1Log__$-->false
CN1Preferences-->false
Cookies-->false
data-->false
FaceBookAccesstmp652635968-->false
folder1-->false
folder2-->false
HELLOCN1FS-->false
myFileName-->false
token-->false
Screenshot of the emulator:
Screenshot of the explorer
The behavior is same on the phone as well
Could this be a bug ?
Is there something that I am not doing correctly ?
Thanks
You need to use the full path for the file:
if(fs.isDirectory(root + file))

How do I get Codenameone to capture video?

I am using the following code to try to capture video with codenameone 2.0
tProperty.setHint("name the property that is a media");
final CheckBox cbVideo = new CheckBox("Video");
final Button bCapture = new Button("Capture Media");
final MediaPlayer mpPlayer = new MediaPlayer();
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect){
try {
if (cbVideo.isSelected()) {
String value = Capture.captureVideo();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}else {
String value = Capture.captureAudio();
mpPlayer.setDataSource(value);
mpPlayer.setName(tProperty.getText());
}
}catch (Exception e){
}
}
});
cM.addComponent(tProperty);
cM.addComponent(cbVideo);
cM.addComponent(bCapture);
cM.addComponent(mpPlayer);
Command [] cmds = new Command[1];
cmds[0] = new Command("Done") {
public void actionPerformed(ActionEvent evt) {
//do Option1
}
};
Dialog.show(editType, cM, cmds);
When running in the simulator, clicking on the CaptureMedia button, it will present the file chooser interface. But then I am unable to choose any file at all whether audio or video because the choose file button is diabled.
How do I get to test the video capture in the simulator?
I think it's a layout problem, you are adding the MediaPlayer component before the video was created, so it's preferred size is 0.
Try to place the video in the border layout center so it's preferred size is ignored and the player will have enough space to display.
Try this:
final Form hi = new Form("Hi World");
hi.setLayout(new BorderLayout());
final Button bCapture = new Button("Capture Media");
bCapture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ect) {
try {
final MediaPlayer mpPlayer = new MediaPlayer();
String value = Capture.captureVideo();
System.out.println("Captured Video " + value);
if (value != null) {
System.out.println("Playing Video");
InputStream is = FileSystemStorage.getInstance().openInputStream(value);
String strMime = "video/mp4";
System.out.println("Input Stream" + is.available());
mpPlayer.setName("bla");
mpPlayer.setDataSource(is, strMime, new Runnable() {
public void run() {
System.out.println("reset the clip for playback");
}
});
hi.addComponent(BorderLayout.CENTER, mpPlayer);
hi.revalidate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
hi.addComponent(BorderLayout.NORTH, bCapture);
hi.show();
There is a regression in playing local videos in the Codename One simulator although it should work on the device. The next update of Codename One will fix it but for now you can workaround it by playing from a stream which should work just fine.
Just use the FileSystemStorage class to get an InputStream to the video and invoke the appropriate playback code. Note that this is less efficient than the play via URL API so when the regression is fixed you should probably return to the URL based API.

How do I set the SDCard path in a Blackberry simulator, and how can I read files from the SDCard using the FileConnection API?

My Blackberry application should read Images which is stored in a SD card.
I have to set a path for the SD Card in the Blackberry simulator so that I can read the image using the FileConnection APIs.
Can anyone give me the solution?
1.create folder and give name-SDCard.
2.in the simulator click on-simulate.
3.choose change SD Card.
4.select your folder SDCard.
5.click on close.
now create file connection
FileConnection fileConnection = (FileConnection)Connector.open(("file:///SDCard/images/a.png")
,Connector.READ, true);
InputStream inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int) fileConnection.fileSize()];
inputStream.read(imageBytes);
inputStream.close();
EncodedImage eimg = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
now u can use this encoded image any where.
If you mean you need to set the simulator path for the SD card, here are the steps how you do this in eclipse:
1- Run the simulator
2- Choose "Smulate"
3- Choose "Change SD Card"
4- Press "Add Directory"
5- Browse and press "OK"
But if you need the code to open the images here it is:
FileConnectionApplication.java:
public class FileConnectionApplication extends UiApplication {
public FileConnectionApplication() {
FileConnectionScreen screen = new FileConnectionScreen();
pushScreen(screen);
}
public static void main(String[] args) {
FileConnectionApplication app = new FileConnectionApplication();
app.enterEventDispatcher();
}
}
FileConnectionScreen.java:
public class FileConnectionScreen extends MainScreen {
private ObjectListField fileList;
private String currentPath = "file:///";
public FileConnectionScreen() {
setTitle("FileConnection");
fileList = new ObjectListField();
fileList.set(new String[] { "store/", "SDCard/" });
add(fileList);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Select", 10, 10) {
public void run() {
loadFile();
}
});
}
private void loadFile() {
currentPath += fileList.get(fileList, fileList.getSelectedIndex());
try {
FileConnection fileConnection = (FileConnection) Connector.open(currentPath);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list();
Vector contentVector = new Vector();
while (directoryEnumerator.hasMoreElements())
contentVector.addElement(directoryEnumerator.nextElement());
String[] directoryContents = new String[contentVector.size()];
contentVector.copyInto(directoryContents);
fileList.set(directoryContents);
} else if (currentPath.toLowerCase().endsWith(".jpg") || currentPath.toLowerCase().endsWith(".png")) {
InputStream inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int) fileConnection.fileSize()];
inputStream.read(imageBytes);
inputStream.close();
EncodedImage eimg = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
UiApplication.getUiApplication().pushScreen(new ImageDisplayScreen(eimg));
}
} catch (IOException ex) {
}
}
}
ImageDisplayScreen.java:
public class ImageDisplayScreen extends MainScreen {
public ImageDisplayScreen(EncodedImage image) {
int displayWidth = Fixed32.toFP(Display.getWidth());
int imageWidth = Fixed32.toFP(image.getWidth());
int scalingFactor = Fixed32.div(imageWidth, displayWidth);
EncodedImage scaledImage = image.scaleImage32(scalingFactor, scalingFactor);
BitmapField bitmapField = new BitmapField();
bitmapField.setImage(scaledImage);
add(bitmapField);
}
}

Resources