0

Javaでは、ある場所から別の場所に画像ファイルをコピーしています。プログラムは正常に実行されていますが、宛先ファイルのサイズをソースファイルのサイズとは異なるものにしたいのですが。新しい場所でファイルのサイズを変更する他の方法はありますか?私は次のコードを使用しています:

public class NewJFrame extends javax.swing.JFrame {

    public NewJFrame() {
        initComponents();
    }

    public static void copyFile(File sourceFile, File destFile)
            throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }

        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();

            // previous code: destination.transferFrom(source, 0, source.size());
            // to avoid infinite loops, should be:
            long count = 0;
            long size = source.size();
            while ((count += destination.transferFrom(source, count, size
                    - count)) < size)
                ;
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            File sourceFile = new File(
                    "d:/adesh/golden_temple_amritsar_india-normal.jpg");

            File destFile = new File(
                    "d:/adesh2/golden_temple_amritsar_india-normal.jpg");

            copyFile(sourceFile, destFile);
        } catch (Exception ex) {
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
}
4

1 に答える 1

1

仕様に従って画像のサイズを変更するためのコードを次に示します。copyFile メソッド内で、

int 幅 = 100、高さ = 75; /* ここで幅と高さを設定します */

BufferedImage inputImage=ImageIO.read(sourceFile);

BufferedImage outputImage=new BufferedImage(幅、高さ、BufferedImage.TYPE_INT_RGB);

Graphics2D g=outputImage.createGraphics();

g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);

g.clearRect(0, 0, 幅, 高さ);

g.drawImage(inputImage, 0, 0, width, height, null);

g.dispose();

ImageIO.write(outputImage,"jpg",destFile); /* 最初のパラメータは BufferedImage のオブジェクト、2 番目のパラメータは書き込むイメージのタイプ、jpg、bmp、png などを使用でき、3 番目のパラメータは宛先ファイル オブジェクトです。*/

于 2013-03-12T05:13:40.670 に答える