Reading file to imageView - file

I'm tryin to pick a file and read it into an imageView. I'm using java fx.
Here's my code:
public void changeImage() {
try {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose Image");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("All Files", "*.*"));
File selectedFile = fileChooser.showOpenDialog(ScreenController.stage);
if (selectedFile != null) {
File file = selectedFile;
File desc = new File("/" + file.getName());
FileUtils.copyFile(file, desc);
Image img = new Image(desc.getPath());
profileImage.setImage(img);
}
} catch (Exception e) {
System.err.println(e);
}
}
The problem seems to be Image img = new Image (desc.getPath()); getting an error that the file does not exist. But it does and it is a image.
// Alex

The Image constructor needs a String representation of a URL, not a filesystem path.
Replace
Image img = new Image(desc.getPath());
with
Image img = new Image(desc.toURI().toURL().toExternalForm());

Related

how to upload multiple files in c# windows application

I want to upload multiple files using single upload button. When I select more than one files it uploads and leaves rest of the files. Here is my code:
private void buttonBrowse_Click(object sender, EventArgs e)
{
try
{
var o = new OpenFileDialog();
o.Multiselect = true;
if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string FileName = o.FileName;
string filenames = Path.GetFileName(o.FileName);
FileName = FileName.Replace(filenames,"").ToString();
FTPUtility obj = new FTPUtility();
if (obj.UploadDocsToFTP(FileName, filenames))
{
MessageBox.Show("File Uploaded Successfully...", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
loadfiles();
}
}
else
{
MessageBox.Show("File Not Uploaded", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
this.LoadFiles();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Set MultiSelect property of OpenFileDialog to true and then use FileNames property to get all selected files.
o.FileNames.ToList().ForEach(file =>
{
//upoaad each file separately
});
FileNames
Gets the file names of all selected files in the dialog box.
For example your code may be like this:
var o = new OpenFileDialog();
o.Multiselect = true;
if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var ftp = new FTPUtility();
var failedToUploads= new List<string>();
var uploads= new List<string>();
o.FileNames.ToList().ForEach(file =>
{
var upload= ftp.UploadDocsToFTP(file, Path.GetFileName(file)));
if(upload)
uploads.Add(file);
else
failedToUploads.Add(file);
});
var message= string.Format("Files Uploaded: \n {0}", string.Join("\n", uploads.ToArray()));
if(failedToUploads.Count>0)
message += string.Format("\nFailed to Upload: \n {0}", string.Join("\n", failedToUploads.ToArray()));
MessageBox.Show(message);
this.LoadFiles();
}
This way you can show a message that informs the user about his uploaded files or which one of them that is failed to upload.

How to load XML file online and process?

I want to make an android app that is actually a RSS reader. This will load XML file from a particular link like http://kalaerkantho.com/rss.xml. After downloading I know how to parse it. But my question is how to download it first so that I can process the downloaded file.
Try this:
private static void downloadFile(String url, String filePath) {
try {
File outputFile = new File(filePath);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}
Adapted from this answer.

display bytes from database as image in imageview in javafx

please I have been stuck on how to convert my stored images from my
database and display it as an image in imageview in javafx.
All the
previously asked questions have not helped me.
I'm using objectdb as my database
I also used fxml to build my GUI
for (Person p : person) {
name.setText(p.getName());
gender.setText(p.getGender());
byte[] byteArray = p.getImage();
image.setImage(new Image(new ByteArrayInputStream(byteArray)));
}
I'll show a detailed step on saving to the database using a file chooser and writing an image to a file in a directory(folder) on your hard drive, and also displaying it to imageview in fmxl GUI.
The following below are triggered during a button event or initialized
from the controller
FileChooser choose = new FileChooser();
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
choose.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = choose.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
byte[] b;
try (ByteArrayOutputStream out = new ByteArrayOutputStream(262144)) {
ImageIO.write(bufferedImage, "jpg", out);
out.flush();
b = out.toByteArray();
}
EntityService service = new EntityService();
Person p = new Person();
p.setId(UUID.randomUUID().toString());
p.setImage(b);
service.putPerson(p);
} catch (IOException e) {
e.printStackTrace();
}
Person p = service.getPerson();
byte[] byteArray = p.getImage();
ByteArrayInputStream in = new ByteArrayInputStream(byteArray);
BufferedImage read = ImageIO.read(in);
image.setImage(SwingFXUtils.toFXImage(read, null));
String output = "C:\\java\\images\\1.jpg";
try (FileOutputStream fos = new FileOutputStream(output)) {
fos.write(byteArray);
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex);
} catch (IOException ioe) {
System.out.println("IOException : " + ioe);
}

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

Delete image file used by XAML

I'm trying to delete a Image file in WPF, but WPF locks the file.
<Image Source="C:\person.gif" x:Name="PersonImage">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete..." x:Name="DeletePersonImageMenuItem" Click="DeletePersonImageMenuItem_Click"/>
</ContextMenu>
</Image.ContextMenu>
</Image>
And the Click handler just looks like this:
private void DeletePersonImageMenuItem_Click(object sender, RoutedEventArgs e)
{
System.IO.File.Delete(#"C:\person.gif");
}
But, when I try to delete the file it is locked and cannot be removed.
Any tips on how to delete the file?
My application Intuipic deals with this by using a custom converter that frees the image resource. See the code here.
Using code behind, you can use the cache option BitmapCacheOption.OnLoad:
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bi.UriSource = new Uri(PathToImage);
bi.EndInit();
PersonImage.Source = bi;
Because I struggled to find it, I will add that if you want to replace the deleted image dynamically, you need to add the argument BitmapCreateOptions.IgnoreImageCache.
First Remove it from the PersonImage control then delete the image. Hope that will help.
As you have assigned to the control in source, and remove it without unassigning the control source.
PersonImage.Source = null;
System.IO.File.Delete(#"C:\person.gif");
hope that will help.
The most easiest way to do this will be, creating a temporary copy of your image file and using it as a source.. and then at end of your app, deleting all temp files..
static List<string> tmpFiles = new List<string>();
static string GetTempCopy(string src)
{
string copy = Path.GetTempFileName();
File.Copy(src, copy);
tmpFiles.Add(copy);
return copy;
}
static void DeleteAllTempFiles()
{
foreach(string file in tmpFiles)
{
File.Delete(file);
}
}
Image caching in WPF also can be configured to do this, but for some reason my various attempts failed and we get unexpected behaviour like not being able to delete or refresh the image etc, so we did this way.
Do not attach the physical file to the object.
BitmapImage bmp;
static int filename = 0;
static string imgpath = "";
private void saveButton_Click(object sender, RoutedEventArgs e)
{
try
{
filename = filename + 1;
string locimagestored = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();
locimagestored = locimagestored + "\\StoredImage\\";
imgpath = locimagestored + filename + ".png";
webCameraControl.GetCurrentImage().Save(imgpath);
Bitmap bitmap = new Bitmap(#imgpath);
IntPtr hBitmap = bitmap.GetHbitmap();
ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ;
if (filename == 1)
{
imgSavedOnline0.Source = wpfBitmap;
bitmap.Dispose();
}
else if (filename == 2)
{
imgSavedOnline1.Source = wpfBitmap;
bitmap.Dispose();
}
else if (filename == 3)
{
imgSavedOnline2.Source = wpfBitmap;
bitmap.Dispose();
}
else if (filename == 4)
{
imgSavedOnline3.Source = wpfBitmap;
bitmap.Dispose();
}
System.IO.DirectoryInfo di2 = new DirectoryInfo(locimagestored);
foreach (FileInfo file in di2.GetFiles())
{
file.Delete();
}
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}

Resources