BufferedImage转换WritableImage
时间: 2023-10-24 19:22:17 浏览: 170
IplImage 与BufferedImage互相转换
要将 `BufferedImage` 转换为 `WritableImage`,可以按照以下步骤进行操作:
1. 创建一个 `WritableImage` 对象,它的宽度和高度与 `BufferedImage` 相同。
```java
WritableImage wImage = new WritableImage(bufferedImage.getWidth(), bufferedImage.getHeight());
```
2. 获取 `WritableImage` 的像素写入器,用于将像素数据从 `BufferedImage` 传输到 `WritableImage` 中。
```java
PixelWriter writer = wImage.getPixelWriter();
```
3. 将 `BufferedImage` 的像素数据转换为 `javafx.scene.paint.Color` 对象,并将其写入到 `WritableImage` 中。
```java
for (int x = 0; x < bufferedImage.getWidth(); x++) {
for (int y = 0; y < bufferedImage.getHeight(); y++) {
int argb = bufferedImage.getRGB(x, y);
Color color = Color.rgb((argb >> 16) & 0xff, (argb >> 8) & 0xff, argb & 0xff, (argb >> 24) & 0xff);
writer.setColor(x, y, color);
}
}
```
完整的代码如下所示:
```java
import java.awt.image.BufferedImage;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
public class BufferedImageToWritableImage {
public static WritableImage convert(BufferedImage bufferedImage) {
WritableImage wImage = new WritableImage(bufferedImage.getWidth(), bufferedImage.getHeight());
PixelWriter writer = wImage.getPixelWriter();
for (int x = 0; x < bufferedImage.getWidth(); x++) {
for (int y = 0; y < bufferedImage.getHeight(); y++) {
int argb = bufferedImage.getRGB(x, y);
Color color = Color.rgb((argb >> 16) & 0xff, (argb >> 8) & 0xff, argb & 0xff, (argb >> 24) & 0xff);
writer.setColor(x, y, color);
}
}
return wImage;
}
public static void main(String[] args) {
BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
WritableImage wImage = convert(bufferedImage);
// Do something with the WritableImage...
}
}
```
阅读全文