使用JavaFX将BMP加载到字节数组中

问题描述 投票:0回答:1

我正在尝试使用JavaFX创建一个简单的Bitmap类,该类允许我加载,使用,修改和保存位图到文件(用于科学模拟器)。我在将图像加载到字节数组时遇到问题。

1-我是否纠正每个像素在缓冲区中需要3个字节的空间?

2- getPixels函数收到以下异常:

java.lang.ClassCastException:类javafx.scene.image.PixelFormat $ ByteRgb无法转换为类javafx.scene.image.WritablePixelFormat(javafx.scene.image.PixelFormat $ ByteRgb和javafx.scene.image.WritablePixelFormat都位于加载程序“ app”的未命名模块)

强制转换为(WritablePixelFormat)由Intellij建议。我在做什么错?

3-如何使用getPixels函数将整个图像加载到RGB整数的2D数组中? (以简化像素的使用)

谢谢。

public class BMP
{
    byte[] buffer;
    int width;
    int height;

    public BMP()
    {
    }

    public void load(String filename) throws FileNotFoundException
    {
        //Creating an image
        Image image = new Image(new FileInputStream(filename));
        this.width = (int)image.getWidth();
        this.height = (int)image.getHeight();
        this.buffer = new byte[width * height * 3];

        //Reading color from the loaded image
        PixelReader pixelReader = image.getPixelReader();

        //Reading pixels of the image
        /*
        for(int y = 0; y < height; y++) {
            for(int x = 0; x < width; x++) {
                //Retrieving the color of the pixel of the loaded image
                Color color = pixelReader.getColor(x, y);
                System.out.println(color.toString());
            }
        }*/

        pixelReader.getPixels(
                0,
                0,
                width,
                height,
                (WritablePixelFormat<ByteBuffer>) PixelFormat.getByteRgbInstance(),
                buffer,
                0,
                width * 3
        );
    }

    public static void main(String[] args)
    {
        BMP bmp1 = new BMP();

        try
        {
            bmp1.load("e:/1.bmp");
            System.out.println("Width:"+ bmp1.width + " length:" + bmp1.height);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    }
}
javafx bitmap
1个回答
0
投票

使用已加载的图像及其PixelReader,您可以构造一个WritableImage,它将为您提供PixelWriter。这足以处理图像。我不会将其提取到数组中。

© www.soinside.com 2019 - 2024. All rights reserved.