Store and view images in JAVA database - Netbeans

烈酒焚心 提交于 2019-12-25 19:37:36

问题


I am creating a simple photo catalogue using JAVA and Netbeans. I have the basic Swing layout all OK and I can store and retrieve text/number etc from/to the database, delta records etc etc. This is all Fine.

I am really not sure how to go about storing the images and viewing them in the jFrame.

I want to store the images as a file path I think (as opposed to BLOB) as I have read this is better?

I am using getText and setText to display the database entries on the form at present and this is all fine. Like below:

String location = rs.getString("Location");

textLocation.setText(location);

I am using the JavaDB derby database connection.

I have searched for a tutorial but have not had much luck. There are tutees fro images etc but not really how to store/retrieve them from a database.

If anyone can point me in the right direction or to a good tutorial covering this that would be grand.

* UPDATE *

Thanks for the help. I thought I would just share what ended up working.

Set path to location of images folder:

private static final String PATH = "/images/";

Assign string

String image = rs.getString("ImageURL");

Add image to label

image_label.setIcon(new javax.swing.ImageIcon(getClass().getResource(PATH + image)));

Thanks again.


回答1:


Things to consider, (if your image files are embedded resources, and not dependent on your file system)

  1. How will you store the image paths? You can simple just store the file names image.png

  2. What complete file path will you ultimately use. Have a set path (excluding the image file name), and based off your application file structure that is the path you will use, concatenated with with image file name. Example

    ProjectRoot
             src
                resources
                       images
                            image.png
    
    private static final String PATH = "/resources/images/";
    
  3. How will you load the image. You should read the image from the class path, using getClass().getResource() and you can just load the images to an ImageIcon and eventually adding them to JLabel. Example

    String location = rs.getString("Location");
    Image image = ImageIO.read(getClass().getResource(PATH + location));
    ImageIcon icon = new ImageIcon(image);
    JLabel label = new JLabel(icon);
    // add label to something.
    


来源:https://stackoverflow.com/questions/23190614/store-and-view-images-in-java-database-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!