2012-02-18 57 views
0

我在数据库中存储了一些图像,同时检索它们,我想将其大小调整为177x122。我怎么能在JAVA中做到这一点? 这是我用来从数据库检索图像的一些代码,需要做些什么改变才能获得177x122的图像。从数据库中以不同大小检索图像

PreparedStatement pstm1 = con.prepareStatement("select * from image"); 
      ResultSet rs1 = pstm1.executeQuery(); 
      while(rs1.next()) { 
       InputStream fis1; 
       FileOutputStream fos; 
       String image_id; 
       try { 
        fis1 = rs1.getBinaryStream("image"); 
        image_id=rs1.getString("image_id"); 
        fos = new FileOutputStream(new File("images" + (image_id) + ".jpg")); 
        int c; 
        while ((c = fis1.read()) != -1) { 
         fos.write(c); 
        } 
        fis1.close(); 
        fos.close(); 
        JOptionPane.showMessageDialog(null, "Image Successfully Retrieved"); 

       } catch (Exception ex) { 
        System.out.println(ex); 
       } 
      } 

回答

3

您可以使用AWT提供的BufferedImage和Graphics2D类来调整图像大小。 Source

BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type); 
Graphics2D g = resizedImage.createGraphics(); 
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); 
g.dispose(); 
1

假设在image列中的数据是图像格式的Java图像I/O可以读取(如JP​​EG和PNG),则Thumbnailator库应该能够实现这一点。

这将检索来自ResultSet图像数据作为InputStream并写入指定的文件中的代码可以这样写:

// Get the information we need from the database. 
String imageId = rs1.getString("image_id"); 
InputStream is = rs1.getBinaryStream("image"); 

// Perform the thumbnail generation. 
// You may want to substitute variables for the hard-coded 177 and 122. 
Thumbnails.of(is) 
    .size(177, 122) 
    .toFile("images" + (imageId) + ".jpg"); 

// Thumbnailator does not automatically close InputStreams 
// (which is actually a good thing!), so we'll have to close it. 
is.close(); 

(我应该放弃,我还没有实际运行该代码针对一个实际的数据库。)

Thumbnailator将读取从InputStreamimage柱检索二进制数据的图像数据,然后调整图像的大小以装配到172 X 122区域,最后输出吨他将缩略图作为JPEG指定给指定的文件。

默认情况下,Thumbnailator将在调整图像大小时保留原始图像的宽高比(以防止缩略图看起来失真),因此图像大小不一定是172 x 122。如果此行为不合需要,则调用forceSize方法代替size方法可以实现这一点。

声明:我维护Thumbnailator库。

相关问题