java8读取图片并输出图片到指定位置
时间: 2024-02-20 21:02:01 浏览: 24
要读取图片并输出图片到指定位置,你可以使用 Java 的图形库,比如 Java 2D 或 JavaFX。以下是使用 JavaFX 读取和输出图片的示例代码:
```java
import java.io.File;
import java.io.IOException;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javax.imageio.ImageIO;
public class ImageIOExample {
public static void main(String[] args) throws IOException {
// 读取图片
File file = new File("input.png");
Image inputImage = new Image(file.toURI().toString());
// 创建一个输出图像
WritableImage outputImage = new WritableImage(
(int) inputImage.getWidth(),
(int) inputImage.getHeight()
);
// 处理输入图像,将颜色反转
for (int x = 0; x < outputImage.getWidth(); x++) {
for (int y = 0; y < outputImage.getHeight(); y++) {
Color color = inputImage.getPixelReader().getColor(x, y);
color = color.invert();
outputImage.getPixelWriter().setColor(x, y, color);
}
}
// 将输出图像保存到文件
File outputFile = new File("output.png");
ImageIO.write(SwingFXUtils.fromFXImage(outputImage, null), "png", outputFile);
}
}
```
这个示例程序读取了名为 `input.png` 的文件,并将其加载到一个 `Image` 对象中。然后它创建了一个大小与输入图像相同的 `WritableImage` 对象,遍历输入图像中的每个像素,将颜色反转,并将结果写入输出图像。最后,它将输出图像保存到名为 `output.png` 的文件中。你可以根据需要修改输入图像、处理算法和输出文件名。