display bytes from database as image in imageview in javafx - database

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

Related

Retrieve Image from SQLITE DB and open it in imageView using JFXbutton

I'm trying to create desktop App (scenebuilder) and I want to retrieve path of Image from DATABASE (SQLITE) and Attach it to button to open it in ImageView but I'm facing a problem while doing that.
Note: I'm trying to learn Java
My code
#FXML
private ImageView imageView;
#FXML
void btn10 (ActionEvent event) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "SELECT * FROM image WHERE rowid = 1" ;
System.out.println(sql);
ResultSet rs = stmt.executeQuery( sql );
while ( rs.next() ) {
String path=rs.getString("imaging");
imageView.setImage(new Image(path));
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
and I got this in result
Opened database successfully
SELECT * FROM image WHERE rowid = 1
java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
Deleting directory C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run538077077
jfxsa-run:
BUILD SUCCESSFUL (total time: 10 seconds)
and MyDatabase
All comments are welcome :D help me please :D
This is code from a program I wrote that retrieves an image blob from sqlite. You can download and run the program from here. It's running, but it's an incomplete program.
In your code, once you get the image using ideas from my code then just use that image to set your ImageView.
String sqlTCNote = "SELECT * FROM Company;";
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:contactFX.db");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(sqlTCNote))
{
while(rset.next())
{
Company c1 = new Company();
c1.setName(rset.getString("company_name"));
c1.setShortName(rset.getString("short_name"));
c1.setStreet(rset.getString("street"));
c1.setCity(rset.getString("city"));
c1.setState(rset.getString("state"));
c1.setZip(rset.getString("zip"));
c1.setPhoneNumber(rset.getString("phone_number"));
c1.setTollFreeNumber(rset.getString("toll_free_number"));
c1.setEmailAddress(rset.getString("email_address"));
c1.setMissionStatement(rset.getString("mission_statement"));
c1.setPersonalNote(rset.getString("personal_note"));
c1.setWebSiteAddress(rset.getString("website_address"));
//This is the part you are interested in!
InputStream input = rset.getBinaryStream("image");
InputStreamReader inputReader = new InputStreamReader(input);
if(inputReader.ready())
{
File tempFile = new File("tempFile.jpg");
FileOutputStream fos = new FileOutputStream(tempFile);
byte[] buffer = new byte[1024];
while(input.read(buffer) > 0){
fos.write(buffer);
}
Image image = new Image(tempFile.toURI().toURL().toString());
c1.setImage(image);
}
for(int i = 0; i < 10; i++)
{
c1.addEmployee(new Employee());
}
companyData.add(c1);
}
}
catch(SQLException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
}

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.

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.

Reading file to imageView

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

How can I save and open a file in winForms?

I have this application where I use windowsForm and UserControl to draw some diagrams. After I am done I want to save them or I want to open an existing file that I created before and keep working on the diagram. So, I want to use the save and open dialog File to save or open my diagrams.
EDIT:
this is what i have :
//save the object to the file
public bool ObjectToFile(Object model, string FileName)
{
try
{
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, model);
byte[] _ByteArray = _MemoryStream.ToArray();
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray.ToArray(), 0, _ByteArray.Length);
_FileStream.Close();
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;
return true;
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return false;
}
//load the object from the file
public Object FileToObject(string FileName)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
long _TotalBytes = new System.IO.FileInfo(FileName).Length;
byte[] _ByteArray = _BinaryReader.ReadBytes((Int32)_TotalBytes);
_FileStream.Close();
_FileStream.Dispose();
_FileStream = null;
_BinaryReader.Close();
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
_MemoryStream.Position = 0;
return _BinaryFormatter.Deserialize(_MemoryStream);
}
catch (Exception _Exception)
{
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return null;
}
and now I want to do this but it's not working
public void save()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.OpenFile() != null)
{
ObjectToFile(model, saveFileDialog1.FileName);
}
}
}
but if I try without the fileDialog and i just use
ObjectToFile(model, "d:\\objects.txt");
this works. And I want to save it where I want and with my own name.
Check out the SaveFileDialog and OpenFileDialog classes. They are pretty similar, and can be used like this:
using(SaveFileDialog sfd = new SaveFileDialog()) {
sfd.Filter = "Text Files|*.txt|All Files|*.*";
if(sfd.ShowDialog() != DialogResult.OK) {
return;
}
ObjectToFile(sfd.FileName);
}
The mechanics of actually saving your file are, obviously, outside the scope of this answer.
Edit: I've updated my answer to reflect the new information in your post.

Resources