2012-02-18 16 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クラスを使用して、イメージのサイズを変更できます。 image列のデータを仮定し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

は、Javaイメージは、I/Oが読み取ることができる画像フォーマット(JPEGやPNGなど)、Thumbnailatorライブラリはこれを達成することができるはずです。

InputStreamとしてResultSetから画像データを取得し、指定したファイルに記述したコードは次のように書くことができます。(私は実際にこのコードを実行していないことを放棄すべきである

// 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はimageカラムからバイナリデータを取得InputStreamからの画像データを読み取り、その後、172 X 122の領域に収まるように画像のサイズを変更し、最終的に出力T彼は指定されたファイルにJPEGとしてのサムネイルを表示します。

デフォルトでは、画像のサイズを変更するときにサムネイル画像が元の画像のアスペクト比を保持するので、画像サイズは必ずしも172×122になるとは限りません。代わりにsizeメソッドの代わりにforceSizeメソッドを使用することができます。

免責事項:私はThumbnailatorライブラリを維持しています。

関連する問題