Java阅读多个图像

时间:2018-05-14 14:17:33

标签: java image-processing bufferedimage javax.imageio

我有一个Mysql数据库,其中包含存储在本地驱动器中的图像路径。我需要编写一个Java程序,逐个读取这些图像。

我写了以下代码:

import java.sql.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


public class ReadMultipleImages
{

  public static void main(String[] args)
  {
    try
    {

      String myDriver = "com.mysql.cj.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost/db?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "user", "password");

      String query = "SELECT * FROM test";

      Statement st = conn.createStatement();

      ResultSet rs = st.executeQuery(query);

      while (rs.next())
      {

        String img = rs.getString("img");

        BufferedImage in = ImageIO.read(new File(img));     
        System.out.println("Width of Image : " + in.getWidth());

      }
      st.close();
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }
  }
}

它不适用于多个图像路径。但是,当我通过直接单图像路径时:

BufferedImage in = ImageIO.read(new File('/tmp/frame_004.jpej'));

它给了我想要的确切结果。我的发现是它只适用于单个图像路径而不是更多。如何处理变量 img 返回的多个图像?

1 个答案:

答案 0 :(得分:0)

最后还有车轮上的东西:

import java.sql.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


public class ReadMultipleImages
{

  public static void main(String[] args)
  {
    try
    {

      String myDriver = "com.mysql.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost:port/db_name?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "user", "password");

      String query = "SELECT * FROM metadata";

      Statement st = conn.createStatement();

      ResultSet rs = st.executeQuery(query);

      while (rs.next())
      {

    String srno = rs.getString("srno"); 
    String path = rs.getString("path");
    String file = rs.getString("file");

    // PATH: /home/memon/images/, FILE: frame_1524043865776151594.jpeg

    String loc = path + file;

    System.out.println("location : " + loc);

    BufferedImage in = ImageIO.read(new File(loc));     
        System.out.println("SRno. "+srno+" Width of Image : " + in.getWidth() + " X " + in.getHeight());

      }
      st.close();
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }
  }
}

输出:

location : /home/memon/images/frame_1524043865776151594.jpeg
SRno. 0 Width of Image : 262 X 90
location : /home/memon/images/frame_1524043865776151595.jpeg
SRno. 1 Width of Image : 1920 X 1080