【问题标题】:Copy an image to another location with different size将图像复制到不同大小的另一个位置
【发布时间】:2013-02-26 11:53:19
【问题描述】:

我正在尝试使用 Java 将图像文件从一个位置复制到另一个位置。现在我想将图像文件保存为特定大小,无论源位置中图像文件的大小是多少。

我正在使用以下代码,它在目标位置生成与源文件大小相同的图像:

public class filecopy {
    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();
            }
        }
    }

    public static void main(String args[]) {
       try {
        File sourceFile = new File("D:/new folder/abc.jpg");
        File destFile = new File("d:/new folder1/abc.jpg");
        copyFile(sourceFile,destFile);
        } catch (IOException ex) {
           ex.printStackTrace();
         }
    }
}

【问题讨论】:

  • 不错的项目,我也一直想自己做。但是你的问题是什么?
  • 仅供参考,您的代码不可编译(最后有一些悬空字符串)。

标签: java file-io file-copying


【解决方案1】:

这是根据您的规范调整图像大小的代码。 在copyFile方法里面,

int width=100,height=75; /* set the width and height here */
BufferedImage inputImage=ImageIO.read(sourceFile);
BufferedImage outputImage=new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
Graphics2D g=outputImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.clearRect(0, 0, width, height);
g.drawImage(inputImage, 0, 0, width, height, null);
g.dispose();
ImageIO.write(outputImage,"jpg",destFile);
/* first parameter is the object of the BufferedImage,
   second parameter is the type of image that you are going to write,
       you can use jpg, bmp, png etc
   third parameter is the destination file object. */

【讨论】:

  • 我想在编译给定代码后调整文件大小建议我举例说明。
  • @adeshsingh 也导入相关包。希望这是你需要的。
猜你喜欢
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多