Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

Tuesday, July 24, 2012

Image path in Java



I am creating a batch file which contains a button with image. While running the application in my PC, the image is displayed correctly. But whenever the file is run on a different PC, the image is not displayed. Only the button is shown. 

To display the image without explicitly writing where the file is located, you can create a package within the project and copy the images to that package. Then compile and execute the jar file in any PC. The image will be displayed.

Friday, January 28, 2011

Java program to insert image as byte array to postgres database

//Program to insert an image into postgres database as byte array

import java.sql.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class insertImage
{
  public static void main(String[] args)
  {
    PreparedStatement statement = null;
    {
      FileInputStream fin = null;
      try
      {
        System.out.println("Insert Image Example!");
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://x.x.x.x:5432/MYDB";
        Connection oConnection = DriverManager.getConnection(url, "username", "password");
        System.out.println("Sucessfully connected to Postgres Database");
        File imgfile = new File("myimage.jpg");
        fin = new FileInputStream(imgfile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        for (int readNum; (readNum = fin.read(buf)) != -1;)
        {
          bos.write(buf, 0, readNum);
          byte[] bytes = bos.toByteArray();
          String sql = "INSERT INTO my_table (byte_array) VALUES (?)";
          statement = oConnection.prepareStatement(sql);
          statement.setBytes(1, bytes);
          statement.executeUpdate();
          System.out.println("Image inserted into database!");

        }
        statement.close();
        oConnection.close();
      }
      catch (Exception ex)
      {
        System.out.println("Exception:- " + ex);
      }
      try
      {
        fin.close();
      }
      catch (IOException ex)
      {
        System.out.println(" IOException:- " + ex);
      }
    }
  }
}