gpt4 book ai didi

java - 将图像复制到不同大小的另一个位置

转载 作者:行者123 更新时间:2023-11-30 07:18:29 26 4
gpt4 key购买 nike

我正在尝试使用 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();
}
}
}

最佳答案

这是根据您的规范调整图像大小的代码。在 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. */

关于java - 将图像复制到不同大小的另一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15336312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com